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
324
Wiggle Sort II
Medium
<p>Given an integer array <code>nums</code>, reorder it such that <code>nums[0] &lt; nums[1] &gt; nums[2] &lt; nums[3]...</code>.</p> <p>You may assume the input array always has a valid answer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,1,1,6,4] <strong>Output:</strong> [1,6,1,5,1,4] <strong>Explanation:</strong> [1,4,1,5,1,6] is also accepted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,2,3,1] <strong>Output:</strong> [2,3,1,3,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>0 &lt;= nums[i] &lt;= 5000</code></li> <li>It is guaranteed that there will be an answer for the given input <code>nums</code>.</li> </ul> <p>&nbsp;</p> <strong>Follow Up:</strong> Can you do it in <code>O(n)</code> time and/or <strong>in-place</strong> with <code>O(1)</code> extra space?
Greedy; Array; Divide and Conquer; Quickselect; Sorting
Python
class Solution: def wiggleSort(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ arr = sorted(nums) n = len(arr) i, j = (n - 1) >> 1, n - 1 for k in range(n): if k % 2 == 0: nums[k] = arr[i] i -= 1 else: nums[k] = arr[j] j -= 1
325
Maximum Size Subarray Sum Equals k
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the maximum length of a </em><span data-keyword="subarray"><em>subarray</em></span><em> that sums to</em> <code>k</code>. If there is not one, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,5,-2,3], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> The subarray [1, -1, 5, -2] sums to 3 and is the longest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-2,-1,2,1], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [-1, 2] sums to 1 and is the longest. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
C++
class Solution { public: int maxSubArrayLen(vector<int>& nums, int k) { unordered_map<long long, int> d{{0, -1}}; int ans = 0; long long s = 0; for (int i = 0; i < nums.size(); ++i) { s += nums[i]; if (d.count(s - k)) { ans = max(ans, i - d[s - k]); } if (!d.count(s)) { d[s] = i; } } return ans; } };
325
Maximum Size Subarray Sum Equals k
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the maximum length of a </em><span data-keyword="subarray"><em>subarray</em></span><em> that sums to</em> <code>k</code>. If there is not one, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,5,-2,3], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> The subarray [1, -1, 5, -2] sums to 3 and is the longest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-2,-1,2,1], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [-1, 2] sums to 1 and is the longest. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
C#
public class Solution { public int MaxSubArrayLen(int[] nums, int k) { var d = new Dictionary<int, int>(); d[0] = -1; int ans = 0; int s = 0; for (int i = 0; i < nums.Length; i++) { s += nums[i]; if (d.ContainsKey(s - k)) { ans = Math.Max(ans, i - d[s - k]); } if (!d.ContainsKey(s)) { d[s] = i; } } return ans; } }
325
Maximum Size Subarray Sum Equals k
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the maximum length of a </em><span data-keyword="subarray"><em>subarray</em></span><em> that sums to</em> <code>k</code>. If there is not one, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,5,-2,3], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> The subarray [1, -1, 5, -2] sums to 3 and is the longest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-2,-1,2,1], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [-1, 2] sums to 1 and is the longest. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
Go
func maxSubArrayLen(nums []int, k int) (ans int) { d := map[int]int{0: -1} s := 0 for i, x := range nums { s += x if j, ok := d[s-k]; ok && ans < i-j { ans = i - j } if _, ok := d[s]; !ok { d[s] = i } } return }
325
Maximum Size Subarray Sum Equals k
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the maximum length of a </em><span data-keyword="subarray"><em>subarray</em></span><em> that sums to</em> <code>k</code>. If there is not one, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,5,-2,3], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> The subarray [1, -1, 5, -2] sums to 3 and is the longest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-2,-1,2,1], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [-1, 2] sums to 1 and is the longest. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
Java
class Solution { public int maxSubArrayLen(int[] nums, int k) { Map<Long, Integer> d = new HashMap<>(); d.put(0L, -1); int ans = 0; long s = 0; for (int i = 0; i < nums.length; ++i) { s += nums[i]; ans = Math.max(ans, i - d.getOrDefault(s - k, i)); d.putIfAbsent(s, i); } return ans; } }
325
Maximum Size Subarray Sum Equals k
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the maximum length of a </em><span data-keyword="subarray"><em>subarray</em></span><em> that sums to</em> <code>k</code>. If there is not one, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,5,-2,3], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> The subarray [1, -1, 5, -2] sums to 3 and is the longest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-2,-1,2,1], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [-1, 2] sums to 1 and is the longest. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
JavaScript
/** * @param {number[]} nums * @param {number} k * @return {number} */ var maxSubArrayLen = function (nums, k) { const d = new Map(); d.set(0, -1); let ans = 0; let s = 0; for (let i = 0; i < nums.length; ++i) { s += nums[i]; if (d.has(s - k)) { ans = Math.max(ans, i - d.get(s - k)); } if (!d.has(s)) { d.set(s, i); } } return ans; };
325
Maximum Size Subarray Sum Equals k
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the maximum length of a </em><span data-keyword="subarray"><em>subarray</em></span><em> that sums to</em> <code>k</code>. If there is not one, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,5,-2,3], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> The subarray [1, -1, 5, -2] sums to 3 and is the longest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-2,-1,2,1], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [-1, 2] sums to 1 and is the longest. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
Python
class Solution: def maxSubArrayLen(self, nums: List[int], k: int) -> int: d = {0: -1} ans = s = 0 for i, x in enumerate(nums): s += x if s - k in d: ans = max(ans, i - d[s - k]) if s not in d: d[s] = i return ans
325
Maximum Size Subarray Sum Equals k
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the maximum length of a </em><span data-keyword="subarray"><em>subarray</em></span><em> that sums to</em> <code>k</code>. If there is not one, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,5,-2,3], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> The subarray [1, -1, 5, -2] sums to 3 and is the longest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-2,-1,2,1], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [-1, 2] sums to 1 and is the longest. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
Rust
use std::collections::HashMap; impl Solution { pub fn max_sub_array_len(nums: Vec<i32>, k: i32) -> i32 { let mut d = HashMap::new(); d.insert(0, -1); let mut ans = 0; let mut s = 0; for (i, &x) in nums.iter().enumerate() { s += x; if let Some(&j) = d.get(&(s - k)) { ans = ans.max((i as i32) - j); } d.entry(s).or_insert(i as i32); } ans } }
325
Maximum Size Subarray Sum Equals k
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the maximum length of a </em><span data-keyword="subarray"><em>subarray</em></span><em> that sums to</em> <code>k</code>. If there is not one, return <code>0</code> instead.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,5,-2,3], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> The subarray [1, -1, 5, -2] sums to 3 and is the longest. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-2,-1,2,1], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The subarray [-1, 2] sums to 1 and is the longest. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
TypeScript
function maxSubArrayLen(nums: number[], k: number): number { const d: Map<number, number> = new Map(); d.set(0, -1); let ans = 0; let s = 0; for (let i = 0; i < nums.length; ++i) { s += nums[i]; if (d.has(s - k)) { ans = Math.max(ans, i - d.get(s - k)!); } if (!d.has(s)) { d.set(s, i); } } return ans; }
326
Power of Three
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of three. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of three, if there exists an integer <code>x</code> such that <code>n == 3<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 27 <strong>Output:</strong> true <strong>Explanation:</strong> 27 = 3<sup>3</sup> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = -1 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = (-1). </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?
Recursion; Math
C++
class Solution { public: bool isPowerOfThree(int n) { while (n > 2) { if (n % 3) { return false; } n /= 3; } return n == 1; } };
326
Power of Three
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of three. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of three, if there exists an integer <code>x</code> such that <code>n == 3<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 27 <strong>Output:</strong> true <strong>Explanation:</strong> 27 = 3<sup>3</sup> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = -1 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = (-1). </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?
Recursion; Math
Go
func isPowerOfThree(n int) bool { for n > 2 { if n%3 != 0 { return false } n /= 3 } return n == 1 }
326
Power of Three
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of three. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of three, if there exists an integer <code>x</code> such that <code>n == 3<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 27 <strong>Output:</strong> true <strong>Explanation:</strong> 27 = 3<sup>3</sup> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = -1 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = (-1). </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?
Recursion; Math
Java
class Solution { public boolean isPowerOfThree(int n) { while (n > 2) { if (n % 3 != 0) { return false; } n /= 3; } return n == 1; } }
326
Power of Three
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of three. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of three, if there exists an integer <code>x</code> such that <code>n == 3<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 27 <strong>Output:</strong> true <strong>Explanation:</strong> 27 = 3<sup>3</sup> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = -1 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = (-1). </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?
Recursion; Math
JavaScript
/** * @param {number} n * @return {boolean} */ var isPowerOfThree = function (n) { while (n > 2) { if (n % 3 !== 0) { return false; } n = Math.floor(n / 3); } return n === 1; };
326
Power of Three
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of three. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of three, if there exists an integer <code>x</code> such that <code>n == 3<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 27 <strong>Output:</strong> true <strong>Explanation:</strong> 27 = 3<sup>3</sup> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = -1 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = (-1). </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?
Recursion; Math
Python
class Solution: def isPowerOfThree(self, n: int) -> bool: while n > 2: if n % 3: return False n //= 3 return n == 1
326
Power of Three
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of three. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of three, if there exists an integer <code>x</code> such that <code>n == 3<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 27 <strong>Output:</strong> true <strong>Explanation:</strong> 27 = 3<sup>3</sup> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = -1 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = (-1). </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?
Recursion; Math
Rust
impl Solution { pub fn is_power_of_three(mut n: i32) -> bool { while n > 2 { if n % 3 != 0 { return false; } n /= 3; } n == 1 } }
326
Power of Three
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of three. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of three, if there exists an integer <code>x</code> such that <code>n == 3<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 27 <strong>Output:</strong> true <strong>Explanation:</strong> 27 = 3<sup>3</sup> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = -1 <strong>Output:</strong> false <strong>Explanation:</strong> There is no x where 3<sup>x</sup> = (-1). </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?
Recursion; Math
TypeScript
function isPowerOfThree(n: number): boolean { while (n > 2) { if (n % 3 !== 0) { return false; } n = Math.floor(n / 3); } return n === 1; }
327
Count of Range Sum
Hard
<p>Given an integer array <code>nums</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of range sums that lie in</em> <code>[lower, upper]</code> <em>inclusive</em>.</p> <p>Range sum <code>S(i, j)</code> is defined as the sum of the elements in <code>nums</code> between indices <code>i</code> and <code>j</code> inclusive, where <code>i &lt;= j</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,5,-1], lower = -2, upper = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0], lower = 0, upper = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>-10<sup>5</sup> &lt;= lower &lt;= upper &lt;= 10<sup>5</sup></code></li> <li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
C++
class BinaryIndexedTree { public: BinaryIndexedTree(int _n) : n(_n) , c(_n + 1) {} void update(int x, int v) { while (x <= n) { c[x] += v; x += x & -x; } } int query(int x) { int s = 0; while (x) { s += c[x]; x -= x & -x; } return s; } private: int n; vector<int> c; }; class Solution { public: int countRangeSum(vector<int>& nums, int lower, int upper) { using ll = long long; int n = nums.size(); ll s[n + 1]; s[0] = 0; for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } ll arr[(n + 1) * 3]; for (int i = 0, j = 0; i <= n; ++i, j += 3) { arr[j] = s[i]; arr[j + 1] = s[i] - lower; arr[j + 2] = s[i] - upper; } sort(arr, arr + (n + 1) * 3); int m = unique(arr, arr + (n + 1) * 3) - arr; BinaryIndexedTree tree(m); int ans = 0; for (int i = 0; i <= n; ++i) { int l = lower_bound(arr, arr + m, s[i] - upper) - arr + 1; int r = lower_bound(arr, arr + m, s[i] - lower) - arr + 1; ans += tree.query(r) - tree.query(l - 1); tree.update(lower_bound(arr, arr + m, s[i]) - arr + 1, 1); } return ans; } };
327
Count of Range Sum
Hard
<p>Given an integer array <code>nums</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of range sums that lie in</em> <code>[lower, upper]</code> <em>inclusive</em>.</p> <p>Range sum <code>S(i, j)</code> is defined as the sum of the elements in <code>nums</code> between indices <code>i</code> and <code>j</code> inclusive, where <code>i &lt;= j</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,5,-1], lower = -2, upper = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0], lower = 0, upper = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>-10<sup>5</sup> &lt;= lower &lt;= upper &lt;= 10<sup>5</sup></code></li> <li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
Go
type BinaryIndexedTree struct { n int c []int } func newBinaryIndexedTree(n int) *BinaryIndexedTree { c := make([]int, n+1) return &BinaryIndexedTree{n, c} } func (this *BinaryIndexedTree) update(x, delta int) { for x <= this.n { this.c[x] += delta x += x & -x } } func (this *BinaryIndexedTree) query(x int) int { s := 0 for x > 0 { s += this.c[x] x -= x & -x } return s } func countRangeSum(nums []int, lower int, upper int) (ans int) { n := len(nums) s := make([]int, n+1) for i, x := range nums { s[i+1] = s[i] + x } arr := make([]int, (n+1)*3) for i, j := 0, 0; i <= n; i, j = i+1, j+3 { arr[j] = s[i] arr[j+1] = s[i] - lower arr[j+2] = s[i] - upper } sort.Ints(arr) m := 0 for i := range arr { if i == 0 || arr[i] != arr[i-1] { arr[m] = arr[i] m++ } } arr = arr[:m] tree := newBinaryIndexedTree(m) for _, x := range s { l := sort.SearchInts(arr, x-upper) + 1 r := sort.SearchInts(arr, x-lower) + 1 ans += tree.query(r) - tree.query(l-1) tree.update(sort.SearchInts(arr, x)+1, 1) } return }
327
Count of Range Sum
Hard
<p>Given an integer array <code>nums</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of range sums that lie in</em> <code>[lower, upper]</code> <em>inclusive</em>.</p> <p>Range sum <code>S(i, j)</code> is defined as the sum of the elements in <code>nums</code> between indices <code>i</code> and <code>j</code> inclusive, where <code>i &lt;= j</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,5,-1], lower = -2, upper = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0], lower = 0, upper = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>-10<sup>5</sup> &lt;= lower &lt;= upper &lt;= 10<sup>5</sup></code></li> <li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
Java
class BinaryIndexedTree { private int n; private int[] c; public BinaryIndexedTree(int n) { this.n = n; this.c = new int[n + 1]; } public void update(int x, int v) { while (x <= n) { c[x] += v; x += x & -x; } } public int query(int x) { int s = 0; while (x != 0) { s += c[x]; x -= x & -x; } return s; } } class Solution { public int countRangeSum(int[] nums, int lower, int upper) { int n = nums.length; long[] s = new long[n + 1]; for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } long[] arr = new long[n * 3 + 3]; for (int i = 0, j = 0; i <= n; ++i, j += 3) { arr[j] = s[i]; arr[j + 1] = s[i] - lower; arr[j + 2] = s[i] - upper; } Arrays.sort(arr); int m = 0; for (int i = 0; i < arr.length; ++i) { if (i == 0 || arr[i] != arr[i - 1]) { arr[m++] = arr[i]; } } BinaryIndexedTree tree = new BinaryIndexedTree(m); int ans = 0; for (long x : s) { int l = search(arr, m, x - upper); int r = search(arr, m, x - lower); ans += tree.query(r) - tree.query(l - 1); tree.update(search(arr, m, x), 1); } return ans; } private int search(long[] nums, int r, long x) { int l = 0; while (l < r) { int mid = (l + r) >> 1; if (nums[mid] >= x) { r = mid; } else { l = mid + 1; } } return l + 1; } }
327
Count of Range Sum
Hard
<p>Given an integer array <code>nums</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of range sums that lie in</em> <code>[lower, upper]</code> <em>inclusive</em>.</p> <p>Range sum <code>S(i, j)</code> is defined as the sum of the elements in <code>nums</code> between indices <code>i</code> and <code>j</code> inclusive, where <code>i &lt;= j</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,5,-1], lower = -2, upper = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0], lower = 0, upper = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>-10<sup>5</sup> &lt;= lower &lt;= upper &lt;= 10<sup>5</sup></code></li> <li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
Python
class BinaryIndexedTree: def __init__(self, n): self.n = n self.c = [0] * (n + 1) def update(self, x, v): while x <= self.n: self.c[x] += v x += x & -x def query(self, x): s = 0 while x > 0: s += self.c[x] x -= x & -x return s class Solution: def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int: s = list(accumulate(nums, initial=0)) arr = sorted(set(v for x in s for v in (x, x - lower, x - upper))) tree = BinaryIndexedTree(len(arr)) ans = 0 for x in s: l = bisect_left(arr, x - upper) + 1 r = bisect_left(arr, x - lower) + 1 ans += tree.query(r) - tree.query(l - 1) tree.update(bisect_left(arr, x) + 1, 1) return ans
327
Count of Range Sum
Hard
<p>Given an integer array <code>nums</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of range sums that lie in</em> <code>[lower, upper]</code> <em>inclusive</em>.</p> <p>Range sum <code>S(i, j)</code> is defined as the sum of the elements in <code>nums</code> between indices <code>i</code> and <code>j</code> inclusive, where <code>i &lt;= j</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,5,-1], lower = -2, upper = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0], lower = 0, upper = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>-10<sup>5</sup> &lt;= lower &lt;= upper &lt;= 10<sup>5</sup></code></li> <li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
TypeScript
class BinaryIndexedTree { private n: number; private c: number[]; constructor(n: number) { this.n = n; this.c = Array(n + 1).fill(0); } update(x: number, v: number) { while (x <= this.n) { this.c[x] += v; x += x & -x; } } query(x: number): number { let s = 0; while (x > 0) { s += this.c[x]; x -= x & -x; } return s; } } function countRangeSum(nums: number[], lower: number, upper: number): number { const n = nums.length; const s = Array(n + 1).fill(0); for (let i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } let arr: number[] = Array((n + 1) * 3); for (let i = 0, j = 0; i <= n; ++i, j += 3) { arr[j] = s[i]; arr[j + 1] = s[i] - lower; arr[j + 2] = s[i] - upper; } arr.sort((a, b) => a - b); let m = 0; for (let i = 0; i < arr.length; ++i) { if (i === 0 || arr[i] !== arr[i - 1]) { arr[m++] = arr[i]; } } arr = arr.slice(0, m); const tree = new BinaryIndexedTree(m); let ans = 0; for (const x of s) { const l = search(arr, m, x - upper); const r = search(arr, m, x - lower); ans += tree.query(r) - tree.query(l - 1); tree.update(search(arr, m, x), 1); } return ans; } function search(nums: number[], r: number, x: number): number { let l = 0; while (l < r) { const mid = (l + r) >> 1; if (nums[mid] >= x) { r = mid; } else { l = mid + 1; } } return l + 1; }
328
Odd Even Linked List
Medium
<p>Given the <code>head</code> of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return <em>the reordered list</em>.</p> <p>The <strong>first</strong> node is considered <strong>odd</strong>, and the <strong>second</strong> node is <strong>even</strong>, and so on.</p> <p>Note that the relative order inside both the even and odd groups should remain as it was in the input.</p> <p>You must solve the problem&nbsp;in <code>O(1)</code>&nbsp;extra space complexity and <code>O(n)</code> 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/0300-0399/0328.Odd%20Even%20Linked%20List/images/oddeven-linked-list.jpg" style="width: 300px; height: 123px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [1,3,5,2,4] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0328.Odd%20Even%20Linked%20List/images/oddeven2-linked-list.jpg" style="width: 500px; height: 142px;" /> <pre> <strong>Input:</strong> head = [2,1,3,5,6,4,7] <strong>Output:</strong> [2,3,6,7,1,5,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>6</sup> &lt;= Node.val &lt;= 10<sup>6</sup></code></li> </ul>
Linked List
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* oddEvenList(ListNode* head) { if (!head) { return nullptr; } ListNode* a = head; ListNode *b = head->next, *c = b; while (b && b->next) { a->next = b->next; a = a->next; b->next = a->next; b = b->next; } a->next = c; return head; } };
328
Odd Even Linked List
Medium
<p>Given the <code>head</code> of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return <em>the reordered list</em>.</p> <p>The <strong>first</strong> node is considered <strong>odd</strong>, and the <strong>second</strong> node is <strong>even</strong>, and so on.</p> <p>Note that the relative order inside both the even and odd groups should remain as it was in the input.</p> <p>You must solve the problem&nbsp;in <code>O(1)</code>&nbsp;extra space complexity and <code>O(n)</code> 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/0300-0399/0328.Odd%20Even%20Linked%20List/images/oddeven-linked-list.jpg" style="width: 300px; height: 123px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [1,3,5,2,4] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0328.Odd%20Even%20Linked%20List/images/oddeven2-linked-list.jpg" style="width: 500px; height: 142px;" /> <pre> <strong>Input:</strong> head = [2,1,3,5,6,4,7] <strong>Output:</strong> [2,3,6,7,1,5,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>6</sup> &lt;= Node.val &lt;= 10<sup>6</sup></code></li> </ul>
Linked List
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func oddEvenList(head *ListNode) *ListNode { if head == nil { return nil } a := head b, c := head.Next, head.Next for b != nil && b.Next != nil { a.Next = b.Next a = a.Next b.Next = a.Next b = b.Next } a.Next = c return head }
328
Odd Even Linked List
Medium
<p>Given the <code>head</code> of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return <em>the reordered list</em>.</p> <p>The <strong>first</strong> node is considered <strong>odd</strong>, and the <strong>second</strong> node is <strong>even</strong>, and so on.</p> <p>Note that the relative order inside both the even and odd groups should remain as it was in the input.</p> <p>You must solve the problem&nbsp;in <code>O(1)</code>&nbsp;extra space complexity and <code>O(n)</code> 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/0300-0399/0328.Odd%20Even%20Linked%20List/images/oddeven-linked-list.jpg" style="width: 300px; height: 123px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [1,3,5,2,4] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0328.Odd%20Even%20Linked%20List/images/oddeven2-linked-list.jpg" style="width: 500px; height: 142px;" /> <pre> <strong>Input:</strong> head = [2,1,3,5,6,4,7] <strong>Output:</strong> [2,3,6,7,1,5,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>6</sup> &lt;= Node.val &lt;= 10<sup>6</sup></code></li> </ul>
Linked List
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode oddEvenList(ListNode head) { if (head == null) { return null; } ListNode a = head; ListNode b = head.next, c = b; while (b != null && b.next != null) { a.next = b.next; a = a.next; b.next = a.next; b = b.next; } a.next = c; return head; } }
328
Odd Even Linked List
Medium
<p>Given the <code>head</code> of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return <em>the reordered list</em>.</p> <p>The <strong>first</strong> node is considered <strong>odd</strong>, and the <strong>second</strong> node is <strong>even</strong>, and so on.</p> <p>Note that the relative order inside both the even and odd groups should remain as it was in the input.</p> <p>You must solve the problem&nbsp;in <code>O(1)</code>&nbsp;extra space complexity and <code>O(n)</code> 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/0300-0399/0328.Odd%20Even%20Linked%20List/images/oddeven-linked-list.jpg" style="width: 300px; height: 123px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [1,3,5,2,4] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0328.Odd%20Even%20Linked%20List/images/oddeven2-linked-list.jpg" style="width: 500px; height: 142px;" /> <pre> <strong>Input:</strong> head = [2,1,3,5,6,4,7] <strong>Output:</strong> [2,3,6,7,1,5,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>6</sup> &lt;= Node.val &lt;= 10<sup>6</sup></code></li> </ul>
Linked List
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None: return None a = head b = c = head.next while b and b.next: a.next = b.next a = a.next b.next = a.next b = b.next a.next = c return head
328
Odd Even Linked List
Medium
<p>Given the <code>head</code> of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return <em>the reordered list</em>.</p> <p>The <strong>first</strong> node is considered <strong>odd</strong>, and the <strong>second</strong> node is <strong>even</strong>, and so on.</p> <p>Note that the relative order inside both the even and odd groups should remain as it was in the input.</p> <p>You must solve the problem&nbsp;in <code>O(1)</code>&nbsp;extra space complexity and <code>O(n)</code> 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/0300-0399/0328.Odd%20Even%20Linked%20List/images/oddeven-linked-list.jpg" style="width: 300px; height: 123px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5] <strong>Output:</strong> [1,3,5,2,4] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0328.Odd%20Even%20Linked%20List/images/oddeven2-linked-list.jpg" style="width: 500px; height: 142px;" /> <pre> <strong>Input:</strong> head = [2,1,3,5,6,4,7] <strong>Output:</strong> [2,3,6,7,1,5,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>6</sup> &lt;= Node.val &lt;= 10<sup>6</sup></code></li> </ul>
Linked List
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function oddEvenList(head: ListNode | null): ListNode | null { if (!head) { return null; } let [a, b, c] = [head, head.next, head.next]; while (b && b.next) { a.next = b.next; a = a.next; b.next = a.next; b = b.next; } a.next = c; return head; }
329
Longest Increasing Path in a Matrix
Hard
<p>Given an <code>m x n</code> integers <code>matrix</code>, return <em>the length of the longest increasing path in </em><code>matrix</code>.</p> <p>From each cell, you can either move in four directions: left, right, up, or down. You <strong>may not</strong> move <strong>diagonally</strong> or move <strong>outside the boundary</strong> (i.e., wrap-around is not allowed).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0329.Longest%20Increasing%20Path%20in%20a%20Matrix/images/grid1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[9,9,4],[6,6,8],[2,1,1]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest increasing path is <code>[1, 2, 6, 9]</code>. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0329.Longest%20Increasing%20Path%20in%20a%20Matrix/images/tmp-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> matrix = [[3,4,5],[3,2,6],[2,2,1]] <strong>Output:</strong> 4 <strong>Explanation: </strong>The longest increasing path is <code>[3, 4, 5, 6]</code>. Moving diagonally is not allowed. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[1]] <strong>Output:</strong> 1 </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;= 200</code></li> <li><code>0 &lt;= matrix[i][j] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Memoization; Array; Dynamic Programming; Matrix
C++
class Solution { public: int longestIncreasingPath(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); int f[m][n]; memset(f, 0, sizeof(f)); int ans = 0; int dirs[5] = {-1, 0, 1, 0, -1}; function<int(int, int)> dfs = [&](int i, int j) -> int { if (f[i][j]) { return f[i][j]; } for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[i][j]) { f[i][j] = max(f[i][j], dfs(x, y)); } } return ++f[i][j]; }; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { ans = max(ans, dfs(i, j)); } } return ans; } };
329
Longest Increasing Path in a Matrix
Hard
<p>Given an <code>m x n</code> integers <code>matrix</code>, return <em>the length of the longest increasing path in </em><code>matrix</code>.</p> <p>From each cell, you can either move in four directions: left, right, up, or down. You <strong>may not</strong> move <strong>diagonally</strong> or move <strong>outside the boundary</strong> (i.e., wrap-around is not allowed).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0329.Longest%20Increasing%20Path%20in%20a%20Matrix/images/grid1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[9,9,4],[6,6,8],[2,1,1]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest increasing path is <code>[1, 2, 6, 9]</code>. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0329.Longest%20Increasing%20Path%20in%20a%20Matrix/images/tmp-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> matrix = [[3,4,5],[3,2,6],[2,2,1]] <strong>Output:</strong> 4 <strong>Explanation: </strong>The longest increasing path is <code>[3, 4, 5, 6]</code>. Moving diagonally is not allowed. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[1]] <strong>Output:</strong> 1 </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;= 200</code></li> <li><code>0 &lt;= matrix[i][j] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Memoization; Array; Dynamic Programming; Matrix
Go
func longestIncreasingPath(matrix [][]int) (ans int) { m, n := len(matrix), len(matrix[0]) f := make([][]int, m) for i := range f { f[i] = make([]int, n) } dirs := [5]int{-1, 0, 1, 0, -1} var dfs func(i, j int) int dfs = func(i, j int) int { if f[i][j] != 0 { return f[i][j] } for k := 0; k < 4; k++ { x, y := i+dirs[k], j+dirs[k+1] if 0 <= x && x < m && 0 <= y && y < n && matrix[x][y] > matrix[i][j] { f[i][j] = max(f[i][j], dfs(x, y)) } } f[i][j]++ return f[i][j] } for i := 0; i < m; i++ { for j := 0; j < n; j++ { ans = max(ans, dfs(i, j)) } } return }
329
Longest Increasing Path in a Matrix
Hard
<p>Given an <code>m x n</code> integers <code>matrix</code>, return <em>the length of the longest increasing path in </em><code>matrix</code>.</p> <p>From each cell, you can either move in four directions: left, right, up, or down. You <strong>may not</strong> move <strong>diagonally</strong> or move <strong>outside the boundary</strong> (i.e., wrap-around is not allowed).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0329.Longest%20Increasing%20Path%20in%20a%20Matrix/images/grid1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[9,9,4],[6,6,8],[2,1,1]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest increasing path is <code>[1, 2, 6, 9]</code>. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0329.Longest%20Increasing%20Path%20in%20a%20Matrix/images/tmp-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> matrix = [[3,4,5],[3,2,6],[2,2,1]] <strong>Output:</strong> 4 <strong>Explanation: </strong>The longest increasing path is <code>[3, 4, 5, 6]</code>. Moving diagonally is not allowed. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[1]] <strong>Output:</strong> 1 </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;= 200</code></li> <li><code>0 &lt;= matrix[i][j] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Memoization; Array; Dynamic Programming; Matrix
Java
class Solution { private int m; private int n; private int[][] matrix; private int[][] f; public int longestIncreasingPath(int[][] matrix) { m = matrix.length; n = matrix[0].length; f = new int[m][n]; this.matrix = matrix; int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { ans = Math.max(ans, dfs(i, j)); } } return ans; } private int dfs(int i, int j) { if (f[i][j] != 0) { return f[i][j]; } int[] dirs = {-1, 0, 1, 0, -1}; for (int k = 0; k < 4; ++k) { int x = i + dirs[k]; int y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[i][j]) { f[i][j] = Math.max(f[i][j], dfs(x, y)); } } return ++f[i][j]; } }
329
Longest Increasing Path in a Matrix
Hard
<p>Given an <code>m x n</code> integers <code>matrix</code>, return <em>the length of the longest increasing path in </em><code>matrix</code>.</p> <p>From each cell, you can either move in four directions: left, right, up, or down. You <strong>may not</strong> move <strong>diagonally</strong> or move <strong>outside the boundary</strong> (i.e., wrap-around is not allowed).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0329.Longest%20Increasing%20Path%20in%20a%20Matrix/images/grid1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[9,9,4],[6,6,8],[2,1,1]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest increasing path is <code>[1, 2, 6, 9]</code>. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0329.Longest%20Increasing%20Path%20in%20a%20Matrix/images/tmp-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> matrix = [[3,4,5],[3,2,6],[2,2,1]] <strong>Output:</strong> 4 <strong>Explanation: </strong>The longest increasing path is <code>[3, 4, 5, 6]</code>. Moving diagonally is not allowed. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[1]] <strong>Output:</strong> 1 </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;= 200</code></li> <li><code>0 &lt;= matrix[i][j] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Memoization; Array; Dynamic Programming; Matrix
Python
class Solution: def longestIncreasingPath(self, matrix: List[List[int]]) -> int: @cache def dfs(i: int, j: int) -> int: ans = 0 for a, b in pairwise((-1, 0, 1, 0, -1)): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and matrix[x][y] > matrix[i][j]: ans = max(ans, dfs(x, y)) return ans + 1 m, n = len(matrix), len(matrix[0]) return max(dfs(i, j) for i in range(m) for j in range(n))
329
Longest Increasing Path in a Matrix
Hard
<p>Given an <code>m x n</code> integers <code>matrix</code>, return <em>the length of the longest increasing path in </em><code>matrix</code>.</p> <p>From each cell, you can either move in four directions: left, right, up, or down. You <strong>may not</strong> move <strong>diagonally</strong> or move <strong>outside the boundary</strong> (i.e., wrap-around is not allowed).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0329.Longest%20Increasing%20Path%20in%20a%20Matrix/images/grid1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> matrix = [[9,9,4],[6,6,8],[2,1,1]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest increasing path is <code>[1, 2, 6, 9]</code>. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0329.Longest%20Increasing%20Path%20in%20a%20Matrix/images/tmp-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> matrix = [[3,4,5],[3,2,6],[2,2,1]] <strong>Output:</strong> 4 <strong>Explanation: </strong>The longest increasing path is <code>[3, 4, 5, 6]</code>. Moving diagonally is not allowed. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[1]] <strong>Output:</strong> 1 </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;= 200</code></li> <li><code>0 &lt;= matrix[i][j] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Memoization; Array; Dynamic Programming; Matrix
TypeScript
function longestIncreasingPath(matrix: number[][]): number { const m = matrix.length; const n = matrix[0].length; const f: number[][] = Array(m) .fill(0) .map(() => Array(n).fill(0)); const dirs = [-1, 0, 1, 0, -1]; const dfs = (i: number, j: number): number => { if (f[i][j] > 0) { return f[i][j]; } for (let k = 0; k < 4; ++k) { const x = i + dirs[k]; const y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[i][j]) { f[i][j] = Math.max(f[i][j], dfs(x, y)); } } return ++f[i][j]; }; let ans = 0; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { ans = Math.max(ans, dfs(i, j)); } } return ans; }
330
Patching Array
Hard
<p>Given a sorted integer array <code>nums</code> and an integer <code>n</code>, add/patch elements to the array such that any number in the range <code>[1, n]</code> inclusive can be formed by the sum of some elements in the array.</p> <p>Return <em>the minimum number of patches required</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3], n = 6 <strong>Output:</strong> 1 Explanation: Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. So we only need 1 patch. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,10], n = 20 <strong>Output:</strong> 2 Explanation: The two patches can be [2, 4]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2], n = 5 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in <strong>ascending order</strong>.</li> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Array
C++
class Solution { public: int minPatches(vector<int>& nums, int n) { long long x = 1; int ans = 0; for (int i = 0; x <= n;) { if (i < nums.size() && nums[i] <= x) { x += nums[i++]; } else { ++ans; x <<= 1; } } return ans; } };
330
Patching Array
Hard
<p>Given a sorted integer array <code>nums</code> and an integer <code>n</code>, add/patch elements to the array such that any number in the range <code>[1, n]</code> inclusive can be formed by the sum of some elements in the array.</p> <p>Return <em>the minimum number of patches required</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3], n = 6 <strong>Output:</strong> 1 Explanation: Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. So we only need 1 patch. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,10], n = 20 <strong>Output:</strong> 2 Explanation: The two patches can be [2, 4]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2], n = 5 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in <strong>ascending order</strong>.</li> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Array
Go
func minPatches(nums []int, n int) (ans int) { x := 1 for i := 0; x <= n; { if i < len(nums) && nums[i] <= x { x += nums[i] i++ } else { ans++ x <<= 1 } } return }
330
Patching Array
Hard
<p>Given a sorted integer array <code>nums</code> and an integer <code>n</code>, add/patch elements to the array such that any number in the range <code>[1, n]</code> inclusive can be formed by the sum of some elements in the array.</p> <p>Return <em>the minimum number of patches required</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3], n = 6 <strong>Output:</strong> 1 Explanation: Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. So we only need 1 patch. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,10], n = 20 <strong>Output:</strong> 2 Explanation: The two patches can be [2, 4]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2], n = 5 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in <strong>ascending order</strong>.</li> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Array
Java
class Solution { public int minPatches(int[] nums, int n) { long x = 1; int ans = 0; for (int i = 0; x <= n;) { if (i < nums.length && nums[i] <= x) { x += nums[i++]; } else { ++ans; x <<= 1; } } return ans; } }
330
Patching Array
Hard
<p>Given a sorted integer array <code>nums</code> and an integer <code>n</code>, add/patch elements to the array such that any number in the range <code>[1, n]</code> inclusive can be formed by the sum of some elements in the array.</p> <p>Return <em>the minimum number of patches required</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3], n = 6 <strong>Output:</strong> 1 Explanation: Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. So we only need 1 patch. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,10], n = 20 <strong>Output:</strong> 2 Explanation: The two patches can be [2, 4]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2], n = 5 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in <strong>ascending order</strong>.</li> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Array
Python
class Solution: def minPatches(self, nums: List[int], n: int) -> int: x = 1 ans = i = 0 while x <= n: if i < len(nums) and nums[i] <= x: x += nums[i] i += 1 else: ans += 1 x <<= 1 return ans
330
Patching Array
Hard
<p>Given a sorted integer array <code>nums</code> and an integer <code>n</code>, add/patch elements to the array such that any number in the range <code>[1, n]</code> inclusive can be formed by the sum of some elements in the array.</p> <p>Return <em>the minimum number of patches required</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3], n = 6 <strong>Output:</strong> 1 Explanation: Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. So we only need 1 patch. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,10], n = 20 <strong>Output:</strong> 2 Explanation: The two patches can be [2, 4]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2], n = 5 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in <strong>ascending order</strong>.</li> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Array
TypeScript
function minPatches(nums: number[], n: number): number { let x = 1; let ans = 0; for (let i = 0; x <= n; ) { if (i < nums.length && nums[i] <= x) { x += nums[i++]; } else { ++ans; x *= 2; } } return ans; }
331
Verify Preorder Serialization of a Binary Tree
Medium
<p>One way to serialize a binary tree is to use <strong>preorder traversal</strong>. When we encounter a non-null node, we record the node&#39;s value. If it is a null node, we record using a sentinel value such as <code>&#39;#&#39;</code>.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0331.Verify%20Preorder%20Serialization%20of%20a%20Binary%20Tree/images/pre-tree.jpg" style="width: 362px; height: 293px;" /> <p>For example, the above binary tree can be serialized to the string <code>&quot;9,3,4,#,#,1,#,#,2,#,6,#,#&quot;</code>, where <code>&#39;#&#39;</code> represents a null node.</p> <p>Given a string of comma-separated values <code>preorder</code>, return <code>true</code> if it is a correct preorder traversal serialization of a binary tree.</p> <p>It is <strong>guaranteed</strong> that each comma-separated value in the string must be either an integer or a character <code>&#39;#&#39;</code> representing null pointer.</p> <p>You may assume that the input format is always valid.</p> <ul> <li>For example, it could never contain two consecutive commas, such as <code>&quot;1,,3&quot;</code>.</li> </ul> <p><strong>Note:&nbsp;</strong>You are not allowed to reconstruct the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> preorder = "1,#" <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> preorder = "9,#,#,1" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li> <li><code>preorder</code> consist of integers in the range <code>[0, 100]</code> and <code>&#39;#&#39;</code> separated by commas <code>&#39;,&#39;</code>.</li> </ul>
Stack; Tree; String; Binary Tree
C++
class Solution { public: bool isValidSerialization(string preorder) { vector<string> stk; stringstream ss(preorder); string s; while (getline(ss, s, ',')) { stk.push_back(s); while (stk.size() >= 3 && stk[stk.size() - 1] == "#" && stk[stk.size() - 2] == "#" && stk[stk.size() - 3] != "#") { stk.pop_back(); stk.pop_back(); stk.pop_back(); stk.push_back("#"); } } return stk.size() == 1 && stk[0] == "#"; } };
331
Verify Preorder Serialization of a Binary Tree
Medium
<p>One way to serialize a binary tree is to use <strong>preorder traversal</strong>. When we encounter a non-null node, we record the node&#39;s value. If it is a null node, we record using a sentinel value such as <code>&#39;#&#39;</code>.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0331.Verify%20Preorder%20Serialization%20of%20a%20Binary%20Tree/images/pre-tree.jpg" style="width: 362px; height: 293px;" /> <p>For example, the above binary tree can be serialized to the string <code>&quot;9,3,4,#,#,1,#,#,2,#,6,#,#&quot;</code>, where <code>&#39;#&#39;</code> represents a null node.</p> <p>Given a string of comma-separated values <code>preorder</code>, return <code>true</code> if it is a correct preorder traversal serialization of a binary tree.</p> <p>It is <strong>guaranteed</strong> that each comma-separated value in the string must be either an integer or a character <code>&#39;#&#39;</code> representing null pointer.</p> <p>You may assume that the input format is always valid.</p> <ul> <li>For example, it could never contain two consecutive commas, such as <code>&quot;1,,3&quot;</code>.</li> </ul> <p><strong>Note:&nbsp;</strong>You are not allowed to reconstruct the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> preorder = "1,#" <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> preorder = "9,#,#,1" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li> <li><code>preorder</code> consist of integers in the range <code>[0, 100]</code> and <code>&#39;#&#39;</code> separated by commas <code>&#39;,&#39;</code>.</li> </ul>
Stack; Tree; String; Binary Tree
Go
func isValidSerialization(preorder string) bool { stk := []string{} for _, s := range strings.Split(preorder, ",") { stk = append(stk, s) for len(stk) >= 3 && stk[len(stk)-1] == "#" && stk[len(stk)-2] == "#" && stk[len(stk)-3] != "#" { stk = stk[:len(stk)-3] stk = append(stk, "#") } } return len(stk) == 1 && stk[0] == "#" }
331
Verify Preorder Serialization of a Binary Tree
Medium
<p>One way to serialize a binary tree is to use <strong>preorder traversal</strong>. When we encounter a non-null node, we record the node&#39;s value. If it is a null node, we record using a sentinel value such as <code>&#39;#&#39;</code>.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0331.Verify%20Preorder%20Serialization%20of%20a%20Binary%20Tree/images/pre-tree.jpg" style="width: 362px; height: 293px;" /> <p>For example, the above binary tree can be serialized to the string <code>&quot;9,3,4,#,#,1,#,#,2,#,6,#,#&quot;</code>, where <code>&#39;#&#39;</code> represents a null node.</p> <p>Given a string of comma-separated values <code>preorder</code>, return <code>true</code> if it is a correct preorder traversal serialization of a binary tree.</p> <p>It is <strong>guaranteed</strong> that each comma-separated value in the string must be either an integer or a character <code>&#39;#&#39;</code> representing null pointer.</p> <p>You may assume that the input format is always valid.</p> <ul> <li>For example, it could never contain two consecutive commas, such as <code>&quot;1,,3&quot;</code>.</li> </ul> <p><strong>Note:&nbsp;</strong>You are not allowed to reconstruct the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> preorder = "1,#" <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> preorder = "9,#,#,1" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li> <li><code>preorder</code> consist of integers in the range <code>[0, 100]</code> and <code>&#39;#&#39;</code> separated by commas <code>&#39;,&#39;</code>.</li> </ul>
Stack; Tree; String; Binary Tree
Java
class Solution { public boolean isValidSerialization(String preorder) { List<String> stk = new ArrayList<>(); for (String s : preorder.split(",")) { stk.add(s); while (stk.size() >= 3 && stk.get(stk.size() - 1).equals("#") && stk.get(stk.size() - 2).equals("#") && !stk.get(stk.size() - 3).equals("#")) { stk.remove(stk.size() - 1); stk.remove(stk.size() - 1); stk.remove(stk.size() - 1); stk.add("#"); } } return stk.size() == 1 && stk.get(0).equals("#"); } }
331
Verify Preorder Serialization of a Binary Tree
Medium
<p>One way to serialize a binary tree is to use <strong>preorder traversal</strong>. When we encounter a non-null node, we record the node&#39;s value. If it is a null node, we record using a sentinel value such as <code>&#39;#&#39;</code>.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0331.Verify%20Preorder%20Serialization%20of%20a%20Binary%20Tree/images/pre-tree.jpg" style="width: 362px; height: 293px;" /> <p>For example, the above binary tree can be serialized to the string <code>&quot;9,3,4,#,#,1,#,#,2,#,6,#,#&quot;</code>, where <code>&#39;#&#39;</code> represents a null node.</p> <p>Given a string of comma-separated values <code>preorder</code>, return <code>true</code> if it is a correct preorder traversal serialization of a binary tree.</p> <p>It is <strong>guaranteed</strong> that each comma-separated value in the string must be either an integer or a character <code>&#39;#&#39;</code> representing null pointer.</p> <p>You may assume that the input format is always valid.</p> <ul> <li>For example, it could never contain two consecutive commas, such as <code>&quot;1,,3&quot;</code>.</li> </ul> <p><strong>Note:&nbsp;</strong>You are not allowed to reconstruct the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> preorder = "1,#" <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> preorder = "9,#,#,1" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li> <li><code>preorder</code> consist of integers in the range <code>[0, 100]</code> and <code>&#39;#&#39;</code> separated by commas <code>&#39;,&#39;</code>.</li> </ul>
Stack; Tree; String; Binary Tree
Python
class Solution: def isValidSerialization(self, preorder: str) -> bool: stk = [] for c in preorder.split(","): stk.append(c) while len(stk) > 2 and stk[-1] == stk[-2] == "#" and stk[-3] != "#": stk = stk[:-3] stk.append("#") return len(stk) == 1 and stk[0] == "#"
331
Verify Preorder Serialization of a Binary Tree
Medium
<p>One way to serialize a binary tree is to use <strong>preorder traversal</strong>. When we encounter a non-null node, we record the node&#39;s value. If it is a null node, we record using a sentinel value such as <code>&#39;#&#39;</code>.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0331.Verify%20Preorder%20Serialization%20of%20a%20Binary%20Tree/images/pre-tree.jpg" style="width: 362px; height: 293px;" /> <p>For example, the above binary tree can be serialized to the string <code>&quot;9,3,4,#,#,1,#,#,2,#,6,#,#&quot;</code>, where <code>&#39;#&#39;</code> represents a null node.</p> <p>Given a string of comma-separated values <code>preorder</code>, return <code>true</code> if it is a correct preorder traversal serialization of a binary tree.</p> <p>It is <strong>guaranteed</strong> that each comma-separated value in the string must be either an integer or a character <code>&#39;#&#39;</code> representing null pointer.</p> <p>You may assume that the input format is always valid.</p> <ul> <li>For example, it could never contain two consecutive commas, such as <code>&quot;1,,3&quot;</code>.</li> </ul> <p><strong>Note:&nbsp;</strong>You are not allowed to reconstruct the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> preorder = "1,#" <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> preorder = "9,#,#,1" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li> <li><code>preorder</code> consist of integers in the range <code>[0, 100]</code> and <code>&#39;#&#39;</code> separated by commas <code>&#39;,&#39;</code>.</li> </ul>
Stack; Tree; String; Binary Tree
TypeScript
function isValidSerialization(preorder: string): boolean { const stk: string[] = []; for (const s of preorder.split(',')) { stk.push(s); while (stk.length >= 3 && stk.at(-1) === '#' && stk.at(-2) === '#' && stk.at(-3) !== '#') { stk.splice(-3, 3, '#'); } } return stk.length === 1 && stk[0] === '#'; }
332
Reconstruct Itinerary
Hard
<p>You are given a list of airline <code>tickets</code> where <code>tickets[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.</p> <p>All of the tickets belong to a man who departs from <code>&quot;JFK&quot;</code>, thus, the itinerary must begin with <code>&quot;JFK&quot;</code>. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.</p> <ul> <li>For example, the itinerary <code>[&quot;JFK&quot;, &quot;LGA&quot;]</code> has a smaller lexical order than <code>[&quot;JFK&quot;, &quot;LGB&quot;]</code>.</li> </ul> <p>You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0332.Reconstruct%20Itinerary/images/itinerary1-graph.jpg" style="width: 382px; height: 222px;" /> <pre> <strong>Input:</strong> tickets = [[&quot;MUC&quot;,&quot;LHR&quot;],[&quot;JFK&quot;,&quot;MUC&quot;],[&quot;SFO&quot;,&quot;SJC&quot;],[&quot;LHR&quot;,&quot;SFO&quot;]] <strong>Output:</strong> [&quot;JFK&quot;,&quot;MUC&quot;,&quot;LHR&quot;,&quot;SFO&quot;,&quot;SJC&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0332.Reconstruct%20Itinerary/images/itinerary2-graph.jpg" style="width: 222px; height: 230px;" /> <pre> <strong>Input:</strong> tickets = [[&quot;JFK&quot;,&quot;SFO&quot;],[&quot;JFK&quot;,&quot;ATL&quot;],[&quot;SFO&quot;,&quot;ATL&quot;],[&quot;ATL&quot;,&quot;JFK&quot;],[&quot;ATL&quot;,&quot;SFO&quot;]] <strong>Output:</strong> [&quot;JFK&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;SFO&quot;] <strong>Explanation:</strong> Another possible reconstruction is [&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;ATL&quot;,&quot;SFO&quot;] but it is larger in lexical order. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tickets.length &lt;= 300</code></li> <li><code>tickets[i].length == 2</code></li> <li><code>from<sub>i</sub>.length == 3</code></li> <li><code>to<sub>i</sub>.length == 3</code></li> <li><code>from<sub>i</sub></code> and <code>to<sub>i</sub></code> consist of uppercase English letters.</li> <li><code>from<sub>i</sub> != to<sub>i</sub></code></li> </ul>
Depth-First Search; Graph; Eulerian Circuit
C++
class Solution { public: vector<string> findItinerary(vector<vector<string>>& tickets) { sort(tickets.rbegin(), tickets.rend()); unordered_map<string, vector<string>> g; for (const auto& ticket : tickets) { g[ticket[0]].push_back(ticket[1]); } vector<string> ans; auto dfs = [&](this auto&& dfs, string& f) -> void { while (!g[f].empty()) { string t = g[f].back(); g[f].pop_back(); dfs(t); } ans.emplace_back(f); }; string f = "JFK"; dfs(f); reverse(ans.begin(), ans.end()); return ans; } };
332
Reconstruct Itinerary
Hard
<p>You are given a list of airline <code>tickets</code> where <code>tickets[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.</p> <p>All of the tickets belong to a man who departs from <code>&quot;JFK&quot;</code>, thus, the itinerary must begin with <code>&quot;JFK&quot;</code>. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.</p> <ul> <li>For example, the itinerary <code>[&quot;JFK&quot;, &quot;LGA&quot;]</code> has a smaller lexical order than <code>[&quot;JFK&quot;, &quot;LGB&quot;]</code>.</li> </ul> <p>You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0332.Reconstruct%20Itinerary/images/itinerary1-graph.jpg" style="width: 382px; height: 222px;" /> <pre> <strong>Input:</strong> tickets = [[&quot;MUC&quot;,&quot;LHR&quot;],[&quot;JFK&quot;,&quot;MUC&quot;],[&quot;SFO&quot;,&quot;SJC&quot;],[&quot;LHR&quot;,&quot;SFO&quot;]] <strong>Output:</strong> [&quot;JFK&quot;,&quot;MUC&quot;,&quot;LHR&quot;,&quot;SFO&quot;,&quot;SJC&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0332.Reconstruct%20Itinerary/images/itinerary2-graph.jpg" style="width: 222px; height: 230px;" /> <pre> <strong>Input:</strong> tickets = [[&quot;JFK&quot;,&quot;SFO&quot;],[&quot;JFK&quot;,&quot;ATL&quot;],[&quot;SFO&quot;,&quot;ATL&quot;],[&quot;ATL&quot;,&quot;JFK&quot;],[&quot;ATL&quot;,&quot;SFO&quot;]] <strong>Output:</strong> [&quot;JFK&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;SFO&quot;] <strong>Explanation:</strong> Another possible reconstruction is [&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;ATL&quot;,&quot;SFO&quot;] but it is larger in lexical order. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tickets.length &lt;= 300</code></li> <li><code>tickets[i].length == 2</code></li> <li><code>from<sub>i</sub>.length == 3</code></li> <li><code>to<sub>i</sub>.length == 3</code></li> <li><code>from<sub>i</sub></code> and <code>to<sub>i</sub></code> consist of uppercase English letters.</li> <li><code>from<sub>i</sub> != to<sub>i</sub></code></li> </ul>
Depth-First Search; Graph; Eulerian Circuit
Go
func findItinerary(tickets [][]string) (ans []string) { sort.Slice(tickets, func(i, j int) bool { return tickets[i][0] > tickets[j][0] || (tickets[i][0] == tickets[j][0] && tickets[i][1] > tickets[j][1]) }) g := make(map[string][]string) for _, ticket := range tickets { g[ticket[0]] = append(g[ticket[0]], ticket[1]) } var dfs func(f string) dfs = func(f string) { for len(g[f]) > 0 { t := g[f][len(g[f])-1] g[f] = g[f][:len(g[f])-1] dfs(t) } ans = append(ans, f) } dfs("JFK") for i := 0; i < len(ans)/2; i++ { ans[i], ans[len(ans)-1-i] = ans[len(ans)-1-i], ans[i] } return }
332
Reconstruct Itinerary
Hard
<p>You are given a list of airline <code>tickets</code> where <code>tickets[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.</p> <p>All of the tickets belong to a man who departs from <code>&quot;JFK&quot;</code>, thus, the itinerary must begin with <code>&quot;JFK&quot;</code>. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.</p> <ul> <li>For example, the itinerary <code>[&quot;JFK&quot;, &quot;LGA&quot;]</code> has a smaller lexical order than <code>[&quot;JFK&quot;, &quot;LGB&quot;]</code>.</li> </ul> <p>You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0332.Reconstruct%20Itinerary/images/itinerary1-graph.jpg" style="width: 382px; height: 222px;" /> <pre> <strong>Input:</strong> tickets = [[&quot;MUC&quot;,&quot;LHR&quot;],[&quot;JFK&quot;,&quot;MUC&quot;],[&quot;SFO&quot;,&quot;SJC&quot;],[&quot;LHR&quot;,&quot;SFO&quot;]] <strong>Output:</strong> [&quot;JFK&quot;,&quot;MUC&quot;,&quot;LHR&quot;,&quot;SFO&quot;,&quot;SJC&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0332.Reconstruct%20Itinerary/images/itinerary2-graph.jpg" style="width: 222px; height: 230px;" /> <pre> <strong>Input:</strong> tickets = [[&quot;JFK&quot;,&quot;SFO&quot;],[&quot;JFK&quot;,&quot;ATL&quot;],[&quot;SFO&quot;,&quot;ATL&quot;],[&quot;ATL&quot;,&quot;JFK&quot;],[&quot;ATL&quot;,&quot;SFO&quot;]] <strong>Output:</strong> [&quot;JFK&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;SFO&quot;] <strong>Explanation:</strong> Another possible reconstruction is [&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;ATL&quot;,&quot;SFO&quot;] but it is larger in lexical order. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tickets.length &lt;= 300</code></li> <li><code>tickets[i].length == 2</code></li> <li><code>from<sub>i</sub>.length == 3</code></li> <li><code>to<sub>i</sub>.length == 3</code></li> <li><code>from<sub>i</sub></code> and <code>to<sub>i</sub></code> consist of uppercase English letters.</li> <li><code>from<sub>i</sub> != to<sub>i</sub></code></li> </ul>
Depth-First Search; Graph; Eulerian Circuit
Java
class Solution { private Map<String, List<String>> g = new HashMap<>(); private List<String> ans = new ArrayList<>(); public List<String> findItinerary(List<List<String>> tickets) { Collections.sort(tickets, (a, b) -> b.get(1).compareTo(a.get(1))); for (List<String> ticket : tickets) { g.computeIfAbsent(ticket.get(0), k -> new ArrayList<>()).add(ticket.get(1)); } dfs("JFK"); Collections.reverse(ans); return ans; } private void dfs(String f) { while (g.containsKey(f) && !g.get(f).isEmpty()) { String t = g.get(f).remove(g.get(f).size() - 1); dfs(t); } ans.add(f); } }
332
Reconstruct Itinerary
Hard
<p>You are given a list of airline <code>tickets</code> where <code>tickets[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.</p> <p>All of the tickets belong to a man who departs from <code>&quot;JFK&quot;</code>, thus, the itinerary must begin with <code>&quot;JFK&quot;</code>. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.</p> <ul> <li>For example, the itinerary <code>[&quot;JFK&quot;, &quot;LGA&quot;]</code> has a smaller lexical order than <code>[&quot;JFK&quot;, &quot;LGB&quot;]</code>.</li> </ul> <p>You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0332.Reconstruct%20Itinerary/images/itinerary1-graph.jpg" style="width: 382px; height: 222px;" /> <pre> <strong>Input:</strong> tickets = [[&quot;MUC&quot;,&quot;LHR&quot;],[&quot;JFK&quot;,&quot;MUC&quot;],[&quot;SFO&quot;,&quot;SJC&quot;],[&quot;LHR&quot;,&quot;SFO&quot;]] <strong>Output:</strong> [&quot;JFK&quot;,&quot;MUC&quot;,&quot;LHR&quot;,&quot;SFO&quot;,&quot;SJC&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0332.Reconstruct%20Itinerary/images/itinerary2-graph.jpg" style="width: 222px; height: 230px;" /> <pre> <strong>Input:</strong> tickets = [[&quot;JFK&quot;,&quot;SFO&quot;],[&quot;JFK&quot;,&quot;ATL&quot;],[&quot;SFO&quot;,&quot;ATL&quot;],[&quot;ATL&quot;,&quot;JFK&quot;],[&quot;ATL&quot;,&quot;SFO&quot;]] <strong>Output:</strong> [&quot;JFK&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;SFO&quot;] <strong>Explanation:</strong> Another possible reconstruction is [&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;ATL&quot;,&quot;SFO&quot;] but it is larger in lexical order. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tickets.length &lt;= 300</code></li> <li><code>tickets[i].length == 2</code></li> <li><code>from<sub>i</sub>.length == 3</code></li> <li><code>to<sub>i</sub>.length == 3</code></li> <li><code>from<sub>i</sub></code> and <code>to<sub>i</sub></code> consist of uppercase English letters.</li> <li><code>from<sub>i</sub> != to<sub>i</sub></code></li> </ul>
Depth-First Search; Graph; Eulerian Circuit
Python
class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: def dfs(f: str): while g[f]: dfs(g[f].pop()) ans.append(f) g = defaultdict(list) for f, t in sorted(tickets, reverse=True): g[f].append(t) ans = [] dfs("JFK") return ans[::-1]
332
Reconstruct Itinerary
Hard
<p>You are given a list of airline <code>tickets</code> where <code>tickets[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.</p> <p>All of the tickets belong to a man who departs from <code>&quot;JFK&quot;</code>, thus, the itinerary must begin with <code>&quot;JFK&quot;</code>. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.</p> <ul> <li>For example, the itinerary <code>[&quot;JFK&quot;, &quot;LGA&quot;]</code> has a smaller lexical order than <code>[&quot;JFK&quot;, &quot;LGB&quot;]</code>.</li> </ul> <p>You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0332.Reconstruct%20Itinerary/images/itinerary1-graph.jpg" style="width: 382px; height: 222px;" /> <pre> <strong>Input:</strong> tickets = [[&quot;MUC&quot;,&quot;LHR&quot;],[&quot;JFK&quot;,&quot;MUC&quot;],[&quot;SFO&quot;,&quot;SJC&quot;],[&quot;LHR&quot;,&quot;SFO&quot;]] <strong>Output:</strong> [&quot;JFK&quot;,&quot;MUC&quot;,&quot;LHR&quot;,&quot;SFO&quot;,&quot;SJC&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0332.Reconstruct%20Itinerary/images/itinerary2-graph.jpg" style="width: 222px; height: 230px;" /> <pre> <strong>Input:</strong> tickets = [[&quot;JFK&quot;,&quot;SFO&quot;],[&quot;JFK&quot;,&quot;ATL&quot;],[&quot;SFO&quot;,&quot;ATL&quot;],[&quot;ATL&quot;,&quot;JFK&quot;],[&quot;ATL&quot;,&quot;SFO&quot;]] <strong>Output:</strong> [&quot;JFK&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;SFO&quot;] <strong>Explanation:</strong> Another possible reconstruction is [&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;ATL&quot;,&quot;SFO&quot;] but it is larger in lexical order. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tickets.length &lt;= 300</code></li> <li><code>tickets[i].length == 2</code></li> <li><code>from<sub>i</sub>.length == 3</code></li> <li><code>to<sub>i</sub>.length == 3</code></li> <li><code>from<sub>i</sub></code> and <code>to<sub>i</sub></code> consist of uppercase English letters.</li> <li><code>from<sub>i</sub> != to<sub>i</sub></code></li> </ul>
Depth-First Search; Graph; Eulerian Circuit
TypeScript
function findItinerary(tickets: string[][]): string[] { const g: Record<string, string[]> = {}; tickets.sort((a, b) => b[1].localeCompare(a[1])); for (const [f, t] of tickets) { g[f] = g[f] || []; g[f].push(t); } const ans: string[] = []; const dfs = (f: string) => { while (g[f] && g[f].length) { const t = g[f].pop()!; dfs(t); } ans.push(f); }; dfs('JFK'); return ans.reverse(); }
333
Largest BST Subtree
Medium
<p>Given the root of a binary tree, find the largest <span data-keyword="subtree">subtree</span>, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes.</p> <p>A <strong>Binary Search Tree (BST)</strong> is a tree in which all the nodes follow the below-mentioned properties:</p> <ul> <li>The left subtree values are less than the value of their parent (root) node&#39;s value.</li> <li>The right subtree values are greater than the value of their parent (root) node&#39;s value.</li> </ul> <p><strong>Note:</strong> A subtree must include all of its descendants.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0333.Largest%20BST%20Subtree/images/tmp.jpg" style="width: 571px; height: 302px;" /></strong></p> <pre> <strong>Input:</strong> root = [10,5,15,1,8,null,7] <strong>Output:</strong> 3 <strong>Explanation: </strong>The Largest BST Subtree in this case is the highlighted one. The return value is the subtree&#39;s size, which is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [4,2,7,2,3,5,null,2,null,null,null,null,null,1] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Can you figure out ways to solve it with <code>O(n)</code> time complexity?</p>
Tree; Depth-First Search; Binary Search Tree; Dynamic Programming; 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 ans; int largestBSTSubtree(TreeNode* root) { ans = 0; dfs(root); return ans; } vector<int> dfs(TreeNode* root) { if (!root) return {INT_MAX, INT_MIN, 0}; auto left = dfs(root->left); auto right = dfs(root->right); if (left[1] < root->val && root->val < right[0]) { ans = max(ans, left[2] + right[2] + 1); return {min(root->val, left[0]), max(root->val, right[1]), left[2] + right[2] + 1}; } return {INT_MIN, INT_MAX, 0}; } };
333
Largest BST Subtree
Medium
<p>Given the root of a binary tree, find the largest <span data-keyword="subtree">subtree</span>, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes.</p> <p>A <strong>Binary Search Tree (BST)</strong> is a tree in which all the nodes follow the below-mentioned properties:</p> <ul> <li>The left subtree values are less than the value of their parent (root) node&#39;s value.</li> <li>The right subtree values are greater than the value of their parent (root) node&#39;s value.</li> </ul> <p><strong>Note:</strong> A subtree must include all of its descendants.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0333.Largest%20BST%20Subtree/images/tmp.jpg" style="width: 571px; height: 302px;" /></strong></p> <pre> <strong>Input:</strong> root = [10,5,15,1,8,null,7] <strong>Output:</strong> 3 <strong>Explanation: </strong>The Largest BST Subtree in this case is the highlighted one. The return value is the subtree&#39;s size, which is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [4,2,7,2,3,5,null,2,null,null,null,null,null,1] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Can you figure out ways to solve it with <code>O(n)</code> time complexity?</p>
Tree; Depth-First Search; Binary Search Tree; Dynamic Programming; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func largestBSTSubtree(root *TreeNode) int { ans := 0 var dfs func(root *TreeNode) []int dfs = func(root *TreeNode) []int { if root == nil { return []int{math.MaxInt32, math.MinInt32, 0} } left := dfs(root.Left) right := dfs(root.Right) if left[1] < root.Val && root.Val < right[0] { ans = max(ans, left[2]+right[2]+1) return []int{min(root.Val, left[0]), max(root.Val, right[1]), left[2] + right[2] + 1} } return []int{math.MinInt32, math.MaxInt32, 0} } dfs(root) return ans }
333
Largest BST Subtree
Medium
<p>Given the root of a binary tree, find the largest <span data-keyword="subtree">subtree</span>, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes.</p> <p>A <strong>Binary Search Tree (BST)</strong> is a tree in which all the nodes follow the below-mentioned properties:</p> <ul> <li>The left subtree values are less than the value of their parent (root) node&#39;s value.</li> <li>The right subtree values are greater than the value of their parent (root) node&#39;s value.</li> </ul> <p><strong>Note:</strong> A subtree must include all of its descendants.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0333.Largest%20BST%20Subtree/images/tmp.jpg" style="width: 571px; height: 302px;" /></strong></p> <pre> <strong>Input:</strong> root = [10,5,15,1,8,null,7] <strong>Output:</strong> 3 <strong>Explanation: </strong>The Largest BST Subtree in this case is the highlighted one. The return value is the subtree&#39;s size, which is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [4,2,7,2,3,5,null,2,null,null,null,null,null,1] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Can you figure out ways to solve it with <code>O(n)</code> time complexity?</p>
Tree; Depth-First Search; Binary Search Tree; Dynamic Programming; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int ans; public int largestBSTSubtree(TreeNode root) { ans = 0; dfs(root); return ans; } private int[] dfs(TreeNode root) { if (root == null) { return new int[] {Integer.MAX_VALUE, Integer.MIN_VALUE, 0}; } int[] left = dfs(root.left); int[] right = dfs(root.right); if (left[1] < root.val && root.val < right[0]) { ans = Math.max(ans, left[2] + right[2] + 1); return new int[] { Math.min(root.val, left[0]), Math.max(root.val, right[1]), left[2] + right[2] + 1}; } return new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE, 0}; } }
333
Largest BST Subtree
Medium
<p>Given the root of a binary tree, find the largest <span data-keyword="subtree">subtree</span>, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes.</p> <p>A <strong>Binary Search Tree (BST)</strong> is a tree in which all the nodes follow the below-mentioned properties:</p> <ul> <li>The left subtree values are less than the value of their parent (root) node&#39;s value.</li> <li>The right subtree values are greater than the value of their parent (root) node&#39;s value.</li> </ul> <p><strong>Note:</strong> A subtree must include all of its descendants.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0333.Largest%20BST%20Subtree/images/tmp.jpg" style="width: 571px; height: 302px;" /></strong></p> <pre> <strong>Input:</strong> root = [10,5,15,1,8,null,7] <strong>Output:</strong> 3 <strong>Explanation: </strong>The Largest BST Subtree in this case is the highlighted one. The return value is the subtree&#39;s size, which is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [4,2,7,2,3,5,null,2,null,null,null,null,null,1] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Can you figure out ways to solve it with <code>O(n)</code> time complexity?</p>
Tree; Depth-First Search; Binary Search Tree; Dynamic Programming; 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 largestBSTSubtree(self, root: Optional[TreeNode]) -> int: def dfs(root): if root is None: return inf, -inf, 0 lmi, lmx, ln = dfs(root.left) rmi, rmx, rn = dfs(root.right) nonlocal ans if lmx < root.val < rmi: ans = max(ans, ln + rn + 1) return min(lmi, root.val), max(rmx, root.val), ln + rn + 1 return -inf, inf, 0 ans = 0 dfs(root) return ans
334
Increasing Triplet Subsequence
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code><em> if there exists a triple of indices </em><code>(i, j, k)</code><em> such that </em><code>i &lt; j &lt; k</code><em> and </em><code>nums[i] &lt; nums[j] &lt; nums[k]</code>. If no such indices exists, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> Any triplet where i &lt; j &lt; k is valid. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,3,2,1] <strong>Output:</strong> false <strong>Explanation:</strong> No triplet exists. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,5,0,4,6] <strong>Output:</strong> true <strong>Explanation:</strong> The triplet (3, 4, 5) is valid because nums[3] == 0 &lt; nums[4] == 4 &lt; nums[5] == 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you implement a solution that runs in <code>O(n)</code> time complexity and <code>O(1)</code> space complexity?
Greedy; Array
C++
class Solution { public: bool increasingTriplet(vector<int>& nums) { int mi = INT_MAX, mid = INT_MAX; for (int num : nums) { if (num > mid) return true; if (num <= mi) mi = num; else mid = num; } return false; } };
334
Increasing Triplet Subsequence
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code><em> if there exists a triple of indices </em><code>(i, j, k)</code><em> such that </em><code>i &lt; j &lt; k</code><em> and </em><code>nums[i] &lt; nums[j] &lt; nums[k]</code>. If no such indices exists, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> Any triplet where i &lt; j &lt; k is valid. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,3,2,1] <strong>Output:</strong> false <strong>Explanation:</strong> No triplet exists. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,5,0,4,6] <strong>Output:</strong> true <strong>Explanation:</strong> The triplet (3, 4, 5) is valid because nums[3] == 0 &lt; nums[4] == 4 &lt; nums[5] == 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you implement a solution that runs in <code>O(n)</code> time complexity and <code>O(1)</code> space complexity?
Greedy; Array
Go
func increasingTriplet(nums []int) bool { min, mid := math.MaxInt32, math.MaxInt32 for _, num := range nums { if num > mid { return true } if num <= min { min = num } else { mid = num } } return false }
334
Increasing Triplet Subsequence
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code><em> if there exists a triple of indices </em><code>(i, j, k)</code><em> such that </em><code>i &lt; j &lt; k</code><em> and </em><code>nums[i] &lt; nums[j] &lt; nums[k]</code>. If no such indices exists, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> Any triplet where i &lt; j &lt; k is valid. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,3,2,1] <strong>Output:</strong> false <strong>Explanation:</strong> No triplet exists. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,5,0,4,6] <strong>Output:</strong> true <strong>Explanation:</strong> The triplet (3, 4, 5) is valid because nums[3] == 0 &lt; nums[4] == 4 &lt; nums[5] == 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you implement a solution that runs in <code>O(n)</code> time complexity and <code>O(1)</code> space complexity?
Greedy; Array
Java
class Solution { public boolean increasingTriplet(int[] nums) { int n = nums.length; int[] lmi = new int[n]; int[] rmx = new int[n]; lmi[0] = Integer.MAX_VALUE; rmx[n - 1] = Integer.MIN_VALUE; for (int i = 1; i < n; ++i) { lmi[i] = Math.min(lmi[i - 1], nums[i - 1]); } for (int i = n - 2; i >= 0; --i) { rmx[i] = Math.max(rmx[i + 1], nums[i + 1]); } for (int i = 0; i < n; ++i) { if (lmi[i] < nums[i] && nums[i] < rmx[i]) { return true; } } return false; } }
334
Increasing Triplet Subsequence
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code><em> if there exists a triple of indices </em><code>(i, j, k)</code><em> such that </em><code>i &lt; j &lt; k</code><em> and </em><code>nums[i] &lt; nums[j] &lt; nums[k]</code>. If no such indices exists, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> Any triplet where i &lt; j &lt; k is valid. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,3,2,1] <strong>Output:</strong> false <strong>Explanation:</strong> No triplet exists. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,5,0,4,6] <strong>Output:</strong> true <strong>Explanation:</strong> The triplet (3, 4, 5) is valid because nums[3] == 0 &lt; nums[4] == 4 &lt; nums[5] == 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you implement a solution that runs in <code>O(n)</code> time complexity and <code>O(1)</code> space complexity?
Greedy; Array
Python
class Solution: def increasingTriplet(self, nums: List[int]) -> bool: mi, mid = inf, inf for num in nums: if num > mid: return True if num <= mi: mi = num else: mid = num return False
334
Increasing Triplet Subsequence
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code><em> if there exists a triple of indices </em><code>(i, j, k)</code><em> such that </em><code>i &lt; j &lt; k</code><em> and </em><code>nums[i] &lt; nums[j] &lt; nums[k]</code>. If no such indices exists, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> Any triplet where i &lt; j &lt; k is valid. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,3,2,1] <strong>Output:</strong> false <strong>Explanation:</strong> No triplet exists. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,5,0,4,6] <strong>Output:</strong> true <strong>Explanation:</strong> The triplet (3, 4, 5) is valid because nums[3] == 0 &lt; nums[4] == 4 &lt; nums[5] == 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you implement a solution that runs in <code>O(n)</code> time complexity and <code>O(1)</code> space complexity?
Greedy; Array
Rust
impl Solution { pub fn increasing_triplet(nums: Vec<i32>) -> bool { let n = nums.len(); if n < 3 { return false; } let mut min = i32::MAX; let mut mid = i32::MAX; for num in nums.into_iter() { if num <= min { min = num; } else if num <= mid { mid = num; } else { return true; } } false } }
334
Increasing Triplet Subsequence
Medium
<p>Given an integer array <code>nums</code>, return <code>true</code><em> if there exists a triple of indices </em><code>(i, j, k)</code><em> such that </em><code>i &lt; j &lt; k</code><em> and </em><code>nums[i] &lt; nums[j] &lt; nums[k]</code>. If no such indices exists, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> Any triplet where i &lt; j &lt; k is valid. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,3,2,1] <strong>Output:</strong> false <strong>Explanation:</strong> No triplet exists. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,5,0,4,6] <strong>Output:</strong> true <strong>Explanation:</strong> The triplet (3, 4, 5) is valid because nums[3] == 0 &lt; nums[4] == 4 &lt; nums[5] == 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you implement a solution that runs in <code>O(n)</code> time complexity and <code>O(1)</code> space complexity?
Greedy; Array
TypeScript
function increasingTriplet(nums: number[]): boolean { let n = nums.length; if (n < 3) return false; let min = nums[0], mid = Number.MAX_SAFE_INTEGER; for (let num of nums) { if (num <= min) { min = num; } else if (num <= mid) { mid = num; } else if (num > mid) { return true; } } return false; }
335
Self Crossing
Hard
<p>You are given an array of integers <code>distance</code>.</p> <p>You start at the point <code>(0, 0)</code> on an <strong>X-Y plane,</strong> and you move <code>distance[0]</code> meters to the north, then <code>distance[1]</code> meters to the west, <code>distance[2]</code> meters to the south, <code>distance[3]</code> meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.</p> <p>Return <code>true</code> <em>if your path crosses itself or </em><code>false</code><em> if it does not</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/0300-0399/0335.Self%20Crossing/images/11.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [2,1,1,2] <strong>Output:</strong> true <strong>Explanation:</strong> The path crosses itself at the point (0, 1). </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0335.Self%20Crossing/images/22.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [1,2,3,4] <strong>Output:</strong> false <strong>Explanation:</strong> The path does not cross itself at any point. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0335.Self%20Crossing/images/33.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [1,1,1,2,1] <strong>Output:</strong> true <strong>Explanation:</strong> The path crosses itself at the point (0, 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;distance.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;=&nbsp;distance[i] &lt;= 10<sup>5</sup></code></li> </ul>
Geometry; Array; Math
C++
class Solution { public: bool isSelfCrossing(vector<int>& distance) { vector<int> d = distance; for (int i = 3; i < d.size(); ++i) { if (d[i] >= d[i - 2] && d[i - 1] <= d[i - 3]) return true; if (i >= 4 && d[i - 1] == d[i - 3] && d[i] + d[i - 4] >= d[i - 2]) return true; if (i >= 5 && d[i - 2] >= d[i - 4] && d[i - 1] <= d[i - 3] && d[i] >= d[i - 2] - d[i - 4] && d[i - 1] + d[i - 5] >= d[i - 3]) return true; } return false; } };
335
Self Crossing
Hard
<p>You are given an array of integers <code>distance</code>.</p> <p>You start at the point <code>(0, 0)</code> on an <strong>X-Y plane,</strong> and you move <code>distance[0]</code> meters to the north, then <code>distance[1]</code> meters to the west, <code>distance[2]</code> meters to the south, <code>distance[3]</code> meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.</p> <p>Return <code>true</code> <em>if your path crosses itself or </em><code>false</code><em> if it does not</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/0300-0399/0335.Self%20Crossing/images/11.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [2,1,1,2] <strong>Output:</strong> true <strong>Explanation:</strong> The path crosses itself at the point (0, 1). </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0335.Self%20Crossing/images/22.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [1,2,3,4] <strong>Output:</strong> false <strong>Explanation:</strong> The path does not cross itself at any point. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0335.Self%20Crossing/images/33.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [1,1,1,2,1] <strong>Output:</strong> true <strong>Explanation:</strong> The path crosses itself at the point (0, 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;distance.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;=&nbsp;distance[i] &lt;= 10<sup>5</sup></code></li> </ul>
Geometry; Array; Math
C#
public class Solution { public bool IsSelfCrossing(int[] x) { for (var i = 3; i < x.Length; ++i) { if (x[i] >= x[i - 2] && x[i - 1] <= x[i - 3]) return true; if (i > 3 && x[i] + x[i - 4] >= x[i - 2]) { if (x[i - 1] == x[i - 3]) return true; if (i > 4 && x[i - 2] >= x[i - 4] && x[i - 1] <= x[i - 3] && x[i - 1] + x[i - 5] >= x[i - 3]) return true; } } return false; } }
335
Self Crossing
Hard
<p>You are given an array of integers <code>distance</code>.</p> <p>You start at the point <code>(0, 0)</code> on an <strong>X-Y plane,</strong> and you move <code>distance[0]</code> meters to the north, then <code>distance[1]</code> meters to the west, <code>distance[2]</code> meters to the south, <code>distance[3]</code> meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.</p> <p>Return <code>true</code> <em>if your path crosses itself or </em><code>false</code><em> if it does not</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/0300-0399/0335.Self%20Crossing/images/11.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [2,1,1,2] <strong>Output:</strong> true <strong>Explanation:</strong> The path crosses itself at the point (0, 1). </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0335.Self%20Crossing/images/22.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [1,2,3,4] <strong>Output:</strong> false <strong>Explanation:</strong> The path does not cross itself at any point. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0335.Self%20Crossing/images/33.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [1,1,1,2,1] <strong>Output:</strong> true <strong>Explanation:</strong> The path crosses itself at the point (0, 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;distance.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;=&nbsp;distance[i] &lt;= 10<sup>5</sup></code></li> </ul>
Geometry; Array; Math
Go
func isSelfCrossing(distance []int) bool { d := distance for i := 3; i < len(d); i++ { if d[i] >= d[i-2] && d[i-1] <= d[i-3] { return true } if i >= 4 && d[i-1] == d[i-3] && d[i]+d[i-4] >= d[i-2] { return true } if i >= 5 && d[i-2] >= d[i-4] && d[i-1] <= d[i-3] && d[i] >= d[i-2]-d[i-4] && d[i-1]+d[i-5] >= d[i-3] { return true } } return false }
335
Self Crossing
Hard
<p>You are given an array of integers <code>distance</code>.</p> <p>You start at the point <code>(0, 0)</code> on an <strong>X-Y plane,</strong> and you move <code>distance[0]</code> meters to the north, then <code>distance[1]</code> meters to the west, <code>distance[2]</code> meters to the south, <code>distance[3]</code> meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.</p> <p>Return <code>true</code> <em>if your path crosses itself or </em><code>false</code><em> if it does not</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/0300-0399/0335.Self%20Crossing/images/11.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [2,1,1,2] <strong>Output:</strong> true <strong>Explanation:</strong> The path crosses itself at the point (0, 1). </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0335.Self%20Crossing/images/22.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [1,2,3,4] <strong>Output:</strong> false <strong>Explanation:</strong> The path does not cross itself at any point. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0335.Self%20Crossing/images/33.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [1,1,1,2,1] <strong>Output:</strong> true <strong>Explanation:</strong> The path crosses itself at the point (0, 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;distance.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;=&nbsp;distance[i] &lt;= 10<sup>5</sup></code></li> </ul>
Geometry; Array; Math
Java
class Solution { public boolean isSelfCrossing(int[] distance) { int[] d = distance; for (int i = 3; i < d.length; ++i) { if (d[i] >= d[i - 2] && d[i - 1] <= d[i - 3]) { return true; } if (i >= 4 && d[i - 1] == d[i - 3] && d[i] + d[i - 4] >= d[i - 2]) { return true; } if (i >= 5 && d[i - 2] >= d[i - 4] && d[i - 1] <= d[i - 3] && d[i] >= d[i - 2] - d[i - 4] && d[i - 1] + d[i - 5] >= d[i - 3]) { return true; } } return false; } }
335
Self Crossing
Hard
<p>You are given an array of integers <code>distance</code>.</p> <p>You start at the point <code>(0, 0)</code> on an <strong>X-Y plane,</strong> and you move <code>distance[0]</code> meters to the north, then <code>distance[1]</code> meters to the west, <code>distance[2]</code> meters to the south, <code>distance[3]</code> meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.</p> <p>Return <code>true</code> <em>if your path crosses itself or </em><code>false</code><em> if it does not</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/0300-0399/0335.Self%20Crossing/images/11.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [2,1,1,2] <strong>Output:</strong> true <strong>Explanation:</strong> The path crosses itself at the point (0, 1). </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0335.Self%20Crossing/images/22.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [1,2,3,4] <strong>Output:</strong> false <strong>Explanation:</strong> The path does not cross itself at any point. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0335.Self%20Crossing/images/33.jpg" style="width: 400px; height: 413px;" /> <pre> <strong>Input:</strong> distance = [1,1,1,2,1] <strong>Output:</strong> true <strong>Explanation:</strong> The path crosses itself at the point (0, 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;distance.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;=&nbsp;distance[i] &lt;= 10<sup>5</sup></code></li> </ul>
Geometry; Array; Math
Python
class Solution: def isSelfCrossing(self, distance: List[int]) -> bool: d = distance for i in range(3, len(d)): if d[i] >= d[i - 2] and d[i - 1] <= d[i - 3]: return True if i >= 4 and d[i - 1] == d[i - 3] and d[i] + d[i - 4] >= d[i - 2]: return True if ( i >= 5 and d[i - 2] >= d[i - 4] and d[i - 1] <= d[i - 3] and d[i] >= d[i - 2] - d[i - 4] and d[i - 1] + d[i - 5] >= d[i - 3] ): return True return False
336
Palindrome Pairs
Hard
<p>You are given a <strong>0-indexed</strong> array of <strong>unique</strong> strings <code>words</code>.</p> <p>A <strong>palindrome pair</strong> is a pair of integers <code>(i, j)</code> such that:</p> <ul> <li><code>0 &lt;= i, j &lt; words.length</code>,</li> <li><code>i != j</code>, and</li> <li><code>words[i] + words[j]</code> (the concatenation of the two strings) is a <span data-keyword="palindrome-string">palindrome</span>.</li> </ul> <p>Return <em>an array of all the <strong>palindrome pairs</strong> of </em><code>words</code>.</p> <p>You must write an algorithm with&nbsp;<code>O(sum of words[i].length)</code>&nbsp;runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;dcba&quot;,&quot;lls&quot;,&quot;s&quot;,&quot;sssll&quot;] <strong>Output:</strong> [[0,1],[1,0],[3,2],[2,4]] <strong>Explanation:</strong> The palindromes are [&quot;abcddcba&quot;,&quot;dcbaabcd&quot;,&quot;slls&quot;,&quot;llssssll&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;bat&quot;,&quot;tab&quot;,&quot;cat&quot;] <strong>Output:</strong> [[0,1],[1,0]] <strong>Explanation:</strong> The palindromes are [&quot;battab&quot;,&quot;tabbat&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;&quot;] <strong>Output:</strong> [[0,1],[1,0]] <strong>Explanation:</strong> The palindromes are [&quot;a&quot;,&quot;a&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 5000</code></li> <li><code>0 &lt;= words[i].length &lt;= 300</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Trie; Array; Hash Table; String
C#
using System.Collections.Generic; using System.Linq; public class Solution { public IList<IList<int>> PalindromePairs(string[] words) { var results = new List<IList<int>>(); var reverseDict = words.Select((w, i) => new {Word = w, Index = i}).ToDictionary(w => new string(w.Word.Reverse().ToArray()), w => w.Index); for (var i = 0; i < words.Length; ++i) { var word = words[i]; for (var j = 0; j <= word.Length; ++j) { if (j > 0 && IsPalindrome(word, 0, j - 1)) { var suffix = word.Substring(j); int pairIndex; if (reverseDict.TryGetValue(suffix, out pairIndex) && i != pairIndex) { results.Add(new [] { pairIndex, i}); } } if (IsPalindrome(word, j, word.Length - 1)) { var prefix = word.Substring(0, j); int pairIndex; if (reverseDict.TryGetValue(prefix, out pairIndex) && i != pairIndex) { results.Add(new [] { i, pairIndex}); } } } } return results; } private bool IsPalindrome(string word, int startIndex, int endIndex) { var i = startIndex; var j = endIndex; while (i < j) { if (word[i] != word[j]) return false; ++i; --j; } return true; } }
336
Palindrome Pairs
Hard
<p>You are given a <strong>0-indexed</strong> array of <strong>unique</strong> strings <code>words</code>.</p> <p>A <strong>palindrome pair</strong> is a pair of integers <code>(i, j)</code> such that:</p> <ul> <li><code>0 &lt;= i, j &lt; words.length</code>,</li> <li><code>i != j</code>, and</li> <li><code>words[i] + words[j]</code> (the concatenation of the two strings) is a <span data-keyword="palindrome-string">palindrome</span>.</li> </ul> <p>Return <em>an array of all the <strong>palindrome pairs</strong> of </em><code>words</code>.</p> <p>You must write an algorithm with&nbsp;<code>O(sum of words[i].length)</code>&nbsp;runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;dcba&quot;,&quot;lls&quot;,&quot;s&quot;,&quot;sssll&quot;] <strong>Output:</strong> [[0,1],[1,0],[3,2],[2,4]] <strong>Explanation:</strong> The palindromes are [&quot;abcddcba&quot;,&quot;dcbaabcd&quot;,&quot;slls&quot;,&quot;llssssll&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;bat&quot;,&quot;tab&quot;,&quot;cat&quot;] <strong>Output:</strong> [[0,1],[1,0]] <strong>Explanation:</strong> The palindromes are [&quot;battab&quot;,&quot;tabbat&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;&quot;] <strong>Output:</strong> [[0,1],[1,0]] <strong>Explanation:</strong> The palindromes are [&quot;a&quot;,&quot;a&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 5000</code></li> <li><code>0 &lt;= words[i].length &lt;= 300</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Trie; Array; Hash Table; String
Go
func palindromePairs(words []string) [][]int { base := 131 mod := int(1e9) + 7 mul := make([]int, 310) mul[0] = 1 for i := 1; i < len(mul); i++ { mul[i] = (mul[i-1] * base) % mod } n := len(words) prefix := make([]int, n) suffix := make([]int, n) for i, word := range words { m := len(word) for j, c := range word { t := int(c-'a') + 1 s := int(word[m-j-1]-'a') + 1 prefix[i] = (prefix[i]*base)%mod + t suffix[i] = (suffix[i]*base)%mod + s } } check := func(i, j, n, m int) bool { t := ((prefix[i]*mul[n])%mod + prefix[j]) % mod s := ((suffix[j]*mul[m])%mod + suffix[i]) % mod return t == s } var ans [][]int for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { if check(i, j, len(words[j]), len(words[i])) { ans = append(ans, []int{i, j}) } if check(j, i, len(words[i]), len(words[j])) { ans = append(ans, []int{j, i}) } } } return ans }
336
Palindrome Pairs
Hard
<p>You are given a <strong>0-indexed</strong> array of <strong>unique</strong> strings <code>words</code>.</p> <p>A <strong>palindrome pair</strong> is a pair of integers <code>(i, j)</code> such that:</p> <ul> <li><code>0 &lt;= i, j &lt; words.length</code>,</li> <li><code>i != j</code>, and</li> <li><code>words[i] + words[j]</code> (the concatenation of the two strings) is a <span data-keyword="palindrome-string">palindrome</span>.</li> </ul> <p>Return <em>an array of all the <strong>palindrome pairs</strong> of </em><code>words</code>.</p> <p>You must write an algorithm with&nbsp;<code>O(sum of words[i].length)</code>&nbsp;runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;dcba&quot;,&quot;lls&quot;,&quot;s&quot;,&quot;sssll&quot;] <strong>Output:</strong> [[0,1],[1,0],[3,2],[2,4]] <strong>Explanation:</strong> The palindromes are [&quot;abcddcba&quot;,&quot;dcbaabcd&quot;,&quot;slls&quot;,&quot;llssssll&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;bat&quot;,&quot;tab&quot;,&quot;cat&quot;] <strong>Output:</strong> [[0,1],[1,0]] <strong>Explanation:</strong> The palindromes are [&quot;battab&quot;,&quot;tabbat&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;&quot;] <strong>Output:</strong> [[0,1],[1,0]] <strong>Explanation:</strong> The palindromes are [&quot;a&quot;,&quot;a&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 5000</code></li> <li><code>0 &lt;= words[i].length &lt;= 300</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Trie; Array; Hash Table; String
Java
class Solution { private static final int BASE = 131; private static final long[] MUL = new long[310]; private static final int MOD = (int) 1e9 + 7; static { MUL[0] = 1; for (int i = 1; i < MUL.length; ++i) { MUL[i] = (MUL[i - 1] * BASE) % MOD; } } public List<List<Integer>> palindromePairs(String[] words) { int n = words.length; long[] prefix = new long[n]; long[] suffix = new long[n]; for (int i = 0; i < n; ++i) { String word = words[i]; int m = word.length(); for (int j = 0; j < m; ++j) { int t = word.charAt(j) - 'a' + 1; int s = word.charAt(m - j - 1) - 'a' + 1; prefix[i] = (prefix[i] * BASE) % MOD + t; suffix[i] = (suffix[i] * BASE) % MOD + s; } } List<List<Integer>> ans = new ArrayList<>(); for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (check(i, j, words[j].length(), words[i].length(), prefix, suffix)) { ans.add(Arrays.asList(i, j)); } if (check(j, i, words[i].length(), words[j].length(), prefix, suffix)) { ans.add(Arrays.asList(j, i)); } } } return ans; } private boolean check(int i, int j, int n, int m, long[] prefix, long[] suffix) { long t = ((prefix[i] * MUL[n]) % MOD + prefix[j]) % MOD; long s = ((suffix[j] * MUL[m]) % MOD + suffix[i]) % MOD; return t == s; } }
336
Palindrome Pairs
Hard
<p>You are given a <strong>0-indexed</strong> array of <strong>unique</strong> strings <code>words</code>.</p> <p>A <strong>palindrome pair</strong> is a pair of integers <code>(i, j)</code> such that:</p> <ul> <li><code>0 &lt;= i, j &lt; words.length</code>,</li> <li><code>i != j</code>, and</li> <li><code>words[i] + words[j]</code> (the concatenation of the two strings) is a <span data-keyword="palindrome-string">palindrome</span>.</li> </ul> <p>Return <em>an array of all the <strong>palindrome pairs</strong> of </em><code>words</code>.</p> <p>You must write an algorithm with&nbsp;<code>O(sum of words[i].length)</code>&nbsp;runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;dcba&quot;,&quot;lls&quot;,&quot;s&quot;,&quot;sssll&quot;] <strong>Output:</strong> [[0,1],[1,0],[3,2],[2,4]] <strong>Explanation:</strong> The palindromes are [&quot;abcddcba&quot;,&quot;dcbaabcd&quot;,&quot;slls&quot;,&quot;llssssll&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;bat&quot;,&quot;tab&quot;,&quot;cat&quot;] <strong>Output:</strong> [[0,1],[1,0]] <strong>Explanation:</strong> The palindromes are [&quot;battab&quot;,&quot;tabbat&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;&quot;] <strong>Output:</strong> [[0,1],[1,0]] <strong>Explanation:</strong> The palindromes are [&quot;a&quot;,&quot;a&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 5000</code></li> <li><code>0 &lt;= words[i].length &lt;= 300</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Trie; Array; Hash Table; String
Python
class Solution: def palindromePairs(self, words: List[str]) -> List[List[int]]: d = {w: i for i, w in enumerate(words)} ans = [] for i, w in enumerate(words): for j in range(len(w) + 1): a, b = w[:j], w[j:] ra, rb = a[::-1], b[::-1] if ra in d and d[ra] != i and b == rb: ans.append([i, d[ra]]) if j and rb in d and d[rb] != i and a == ra: ans.append([d[rb], i]) return ans
337
House Robber III
Medium
<p>The thief has found himself a new place for his thievery again. There is only one entrance to this area, called <code>root</code>.</p> <p>Besides the <code>root</code>, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if <strong>two directly-linked houses were broken into on the same night</strong>.</p> <p>Given the <code>root</code> of the binary tree, return <em>the maximum amount of money the thief can rob <strong>without alerting the police</strong></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/0300-0399/0337.House%20Robber%20III/images/rob1-tree.jpg" style="width: 277px; height: 293px;" /> <pre> <strong>Input:</strong> root = [3,2,3,null,3,null,1] <strong>Output:</strong> 7 <strong>Explanation:</strong> Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0337.House%20Robber%20III/images/rob2-tree.jpg" style="width: 357px; height: 293px;" /> <pre> <strong>Input:</strong> root = [3,4,5,1,3,null,1] <strong>Output:</strong> 9 <strong>Explanation:</strong> Maximum amount of money the thief can rob = 4 + 5 = 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; 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 rob(TreeNode* root) { function<pair<int, int>(TreeNode*)> dfs = [&](TreeNode* root) -> pair<int, int> { if (!root) { return make_pair(0, 0); } auto [la, lb] = dfs(root->left); auto [ra, rb] = dfs(root->right); return make_pair(root->val + lb + rb, max(la, lb) + max(ra, rb)); }; auto [a, b] = dfs(root); return max(a, b); } };
337
House Robber III
Medium
<p>The thief has found himself a new place for his thievery again. There is only one entrance to this area, called <code>root</code>.</p> <p>Besides the <code>root</code>, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if <strong>two directly-linked houses were broken into on the same night</strong>.</p> <p>Given the <code>root</code> of the binary tree, return <em>the maximum amount of money the thief can rob <strong>without alerting the police</strong></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/0300-0399/0337.House%20Robber%20III/images/rob1-tree.jpg" style="width: 277px; height: 293px;" /> <pre> <strong>Input:</strong> root = [3,2,3,null,3,null,1] <strong>Output:</strong> 7 <strong>Explanation:</strong> Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0337.House%20Robber%20III/images/rob2-tree.jpg" style="width: 357px; height: 293px;" /> <pre> <strong>Input:</strong> root = [3,4,5,1,3,null,1] <strong>Output:</strong> 9 <strong>Explanation:</strong> Maximum amount of money the thief can rob = 4 + 5 = 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func rob(root *TreeNode) int { var dfs func(*TreeNode) (int, int) dfs = func(root *TreeNode) (int, int) { if root == nil { return 0, 0 } la, lb := dfs(root.Left) ra, rb := dfs(root.Right) return root.Val + lb + rb, max(la, lb) + max(ra, rb) } a, b := dfs(root) return max(a, b) }
337
House Robber III
Medium
<p>The thief has found himself a new place for his thievery again. There is only one entrance to this area, called <code>root</code>.</p> <p>Besides the <code>root</code>, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if <strong>two directly-linked houses were broken into on the same night</strong>.</p> <p>Given the <code>root</code> of the binary tree, return <em>the maximum amount of money the thief can rob <strong>without alerting the police</strong></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/0300-0399/0337.House%20Robber%20III/images/rob1-tree.jpg" style="width: 277px; height: 293px;" /> <pre> <strong>Input:</strong> root = [3,2,3,null,3,null,1] <strong>Output:</strong> 7 <strong>Explanation:</strong> Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0337.House%20Robber%20III/images/rob2-tree.jpg" style="width: 357px; height: 293px;" /> <pre> <strong>Input:</strong> root = [3,4,5,1,3,null,1] <strong>Output:</strong> 9 <strong>Explanation:</strong> Maximum amount of money the thief can rob = 4 + 5 = 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; 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 rob(TreeNode root) { int[] ans = dfs(root); return Math.max(ans[0], ans[1]); } private int[] dfs(TreeNode root) { if (root == null) { return new int[2]; } int[] l = dfs(root.left); int[] r = dfs(root.right); return new int[] {root.val + l[1] + r[1], Math.max(l[0], l[1]) + Math.max(r[0], r[1])}; } }
337
House Robber III
Medium
<p>The thief has found himself a new place for his thievery again. There is only one entrance to this area, called <code>root</code>.</p> <p>Besides the <code>root</code>, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if <strong>two directly-linked houses were broken into on the same night</strong>.</p> <p>Given the <code>root</code> of the binary tree, return <em>the maximum amount of money the thief can rob <strong>without alerting the police</strong></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/0300-0399/0337.House%20Robber%20III/images/rob1-tree.jpg" style="width: 277px; height: 293px;" /> <pre> <strong>Input:</strong> root = [3,2,3,null,3,null,1] <strong>Output:</strong> 7 <strong>Explanation:</strong> Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0337.House%20Robber%20III/images/rob2-tree.jpg" style="width: 357px; height: 293px;" /> <pre> <strong>Input:</strong> root = [3,4,5,1,3,null,1] <strong>Output:</strong> 9 <strong>Explanation:</strong> Maximum amount of money the thief can rob = 4 + 5 = 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; 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 rob(self, root: Optional[TreeNode]) -> int: def dfs(root: Optional[TreeNode]) -> (int, int): if root is None: return 0, 0 la, lb = dfs(root.left) ra, rb = dfs(root.right) return root.val + lb + rb, max(la, lb) + max(ra, rb) return max(dfs(root))
337
House Robber III
Medium
<p>The thief has found himself a new place for his thievery again. There is only one entrance to this area, called <code>root</code>.</p> <p>Besides the <code>root</code>, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if <strong>two directly-linked houses were broken into on the same night</strong>.</p> <p>Given the <code>root</code> of the binary tree, return <em>the maximum amount of money the thief can rob <strong>without alerting the police</strong></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/0300-0399/0337.House%20Robber%20III/images/rob1-tree.jpg" style="width: 277px; height: 293px;" /> <pre> <strong>Input:</strong> root = [3,2,3,null,3,null,1] <strong>Output:</strong> 7 <strong>Explanation:</strong> Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0337.House%20Robber%20III/images/rob2-tree.jpg" style="width: 357px; height: 293px;" /> <pre> <strong>Input:</strong> root = [3,4,5,1,3,null,1] <strong>Output:</strong> 9 <strong>Explanation:</strong> Maximum amount of money the thief can rob = 4 + 5 = 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; 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 rob(root: TreeNode | null): number { const dfs = (root: TreeNode | null): [number, number] => { if (!root) { return [0, 0]; } const [la, lb] = dfs(root.left); const [ra, rb] = dfs(root.right); return [root.val + lb + rb, Math.max(la, lb) + Math.max(ra, rb)]; }; return Math.max(...dfs(root)); }
338
Counting Bits
Easy
<p>Given an integer <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n + 1</code><em> such that for each </em><code>i</code><em> </em>(<code>0 &lt;= i &lt;= n</code>)<em>, </em><code>ans[i]</code><em> is the <strong>number of </strong></em><code>1</code><em><strong>&#39;s</strong> in the binary representation of </em><code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [0,1,1] <strong>Explanation:</strong> 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> [0,1,1,2,1,2] <strong>Explanation:</strong> 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 3 --&gt; 11 4 --&gt; 100 5 --&gt; 101 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>It is very easy to come up with a solution with a runtime of <code>O(n log n)</code>. Can you do it in linear time <code>O(n)</code> and possibly in a single pass?</li> <li>Can you do it without using any built-in function (i.e., like <code>__builtin_popcount</code> in C++)?</li> </ul>
Bit Manipulation; Dynamic Programming
C++
class Solution { public: vector<int> countBits(int n) { vector<int> ans(n + 1); for (int i = 0; i <= n; ++i) { ans[i] = __builtin_popcount(i); } return ans; } };
338
Counting Bits
Easy
<p>Given an integer <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n + 1</code><em> such that for each </em><code>i</code><em> </em>(<code>0 &lt;= i &lt;= n</code>)<em>, </em><code>ans[i]</code><em> is the <strong>number of </strong></em><code>1</code><em><strong>&#39;s</strong> in the binary representation of </em><code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [0,1,1] <strong>Explanation:</strong> 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> [0,1,1,2,1,2] <strong>Explanation:</strong> 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 3 --&gt; 11 4 --&gt; 100 5 --&gt; 101 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>It is very easy to come up with a solution with a runtime of <code>O(n log n)</code>. Can you do it in linear time <code>O(n)</code> and possibly in a single pass?</li> <li>Can you do it without using any built-in function (i.e., like <code>__builtin_popcount</code> in C++)?</li> </ul>
Bit Manipulation; Dynamic Programming
Go
func countBits(n int) []int { ans := make([]int, n+1) for i := 0; i <= n; i++ { ans[i] = bits.OnesCount(uint(i)) } return ans }
338
Counting Bits
Easy
<p>Given an integer <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n + 1</code><em> such that for each </em><code>i</code><em> </em>(<code>0 &lt;= i &lt;= n</code>)<em>, </em><code>ans[i]</code><em> is the <strong>number of </strong></em><code>1</code><em><strong>&#39;s</strong> in the binary representation of </em><code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [0,1,1] <strong>Explanation:</strong> 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> [0,1,1,2,1,2] <strong>Explanation:</strong> 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 3 --&gt; 11 4 --&gt; 100 5 --&gt; 101 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>It is very easy to come up with a solution with a runtime of <code>O(n log n)</code>. Can you do it in linear time <code>O(n)</code> and possibly in a single pass?</li> <li>Can you do it without using any built-in function (i.e., like <code>__builtin_popcount</code> in C++)?</li> </ul>
Bit Manipulation; Dynamic Programming
Java
class Solution { public int[] countBits(int n) { int[] ans = new int[n + 1]; for (int i = 0; i <= n; ++i) { ans[i] = Integer.bitCount(i); } return ans; } }
338
Counting Bits
Easy
<p>Given an integer <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n + 1</code><em> such that for each </em><code>i</code><em> </em>(<code>0 &lt;= i &lt;= n</code>)<em>, </em><code>ans[i]</code><em> is the <strong>number of </strong></em><code>1</code><em><strong>&#39;s</strong> in the binary representation of </em><code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [0,1,1] <strong>Explanation:</strong> 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> [0,1,1,2,1,2] <strong>Explanation:</strong> 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 3 --&gt; 11 4 --&gt; 100 5 --&gt; 101 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>It is very easy to come up with a solution with a runtime of <code>O(n log n)</code>. Can you do it in linear time <code>O(n)</code> and possibly in a single pass?</li> <li>Can you do it without using any built-in function (i.e., like <code>__builtin_popcount</code> in C++)?</li> </ul>
Bit Manipulation; Dynamic Programming
Python
class Solution: def countBits(self, n: int) -> List[int]: return [i.bit_count() for i in range(n + 1)]
338
Counting Bits
Easy
<p>Given an integer <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n + 1</code><em> such that for each </em><code>i</code><em> </em>(<code>0 &lt;= i &lt;= n</code>)<em>, </em><code>ans[i]</code><em> is the <strong>number of </strong></em><code>1</code><em><strong>&#39;s</strong> in the binary representation of </em><code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [0,1,1] <strong>Explanation:</strong> 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> [0,1,1,2,1,2] <strong>Explanation:</strong> 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 3 --&gt; 11 4 --&gt; 100 5 --&gt; 101 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>It is very easy to come up with a solution with a runtime of <code>O(n log n)</code>. Can you do it in linear time <code>O(n)</code> and possibly in a single pass?</li> <li>Can you do it without using any built-in function (i.e., like <code>__builtin_popcount</code> in C++)?</li> </ul>
Bit Manipulation; Dynamic Programming
TypeScript
function countBits(n: number): number[] { const ans: number[] = Array(n + 1).fill(0); for (let i = 0; i <= n; ++i) { ans[i] = bitCount(i); } return ans; } function bitCount(n: number): number { let count = 0; while (n) { n &= n - 1; ++count; } return count; }
339
Nested List Weight Sum
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>The <strong>depth</strong> of an integer is the number of lists that it is inside of. For example, the nested list <code>[1,[2,2],[[3],2],1]</code> has each integer&#39;s value set to its <strong>depth</strong>.</p> <p>Return <em>the sum of each integer in </em><code>nestedList</code><em> multiplied by its <strong>depth</strong></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/0300-0399/0339.Nested%20List%20Weight%20Sum/images/nestedlistweightsumex1.png" style="width: 405px; height: 99px;" /> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> 10 <strong>Explanation:</strong> Four 1&#39;s at depth 2, one 2 at depth 1. 1*2 + 1*2 + 2*1 + 1*2 + 1*2 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0339.Nested%20List%20Weight%20Sum/images/nestedlistweightsumex2.png" style="width: 315px; height: 106px;" /> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> 27 <strong>Explanation:</strong> One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3. 1*1 + 4*2 + 6*3 = 27.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nestedList = [0] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 50</code></li> <li>The values of the integers in the nested list is in the range <code>[-100, 100]</code>.</li> <li>The maximum <strong>depth</strong> of any integer is less than or equal to <code>50</code>.</li> </ul>
Depth-First Search; Breadth-First Search
Java
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * // Constructor initializes an empty nested list. * public NestedInteger(); * * // Constructor initializes a single integer. * public NestedInteger(int value); * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // Set this NestedInteger to hold a single integer. * public void setInteger(int value); * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * public void add(NestedInteger ni); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return empty list if this NestedInteger holds a single integer * public List<NestedInteger> getList(); * } */ class Solution { public int depthSum(List<NestedInteger> nestedList) { return dfs(nestedList, 1); } private int dfs(List<NestedInteger> nestedList, int depth) { int depthSum = 0; for (NestedInteger item : nestedList) { if (item.isInteger()) { depthSum += item.getInteger() * depth; } else { depthSum += dfs(item.getList(), depth + 1); } } return depthSum; } }
339
Nested List Weight Sum
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>The <strong>depth</strong> of an integer is the number of lists that it is inside of. For example, the nested list <code>[1,[2,2],[[3],2],1]</code> has each integer&#39;s value set to its <strong>depth</strong>.</p> <p>Return <em>the sum of each integer in </em><code>nestedList</code><em> multiplied by its <strong>depth</strong></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/0300-0399/0339.Nested%20List%20Weight%20Sum/images/nestedlistweightsumex1.png" style="width: 405px; height: 99px;" /> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> 10 <strong>Explanation:</strong> Four 1&#39;s at depth 2, one 2 at depth 1. 1*2 + 1*2 + 2*1 + 1*2 + 1*2 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0339.Nested%20List%20Weight%20Sum/images/nestedlistweightsumex2.png" style="width: 315px; height: 106px;" /> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> 27 <strong>Explanation:</strong> One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3. 1*1 + 4*2 + 6*3 = 27.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nestedList = [0] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 50</code></li> <li>The values of the integers in the nested list is in the range <code>[-100, 100]</code>.</li> <li>The maximum <strong>depth</strong> of any integer is less than or equal to <code>50</code>.</li> </ul>
Depth-First Search; Breadth-First Search
JavaScript
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * function NestedInteger() { * * Return true if this NestedInteger holds a single integer, rather than a nested list. * @return {boolean} * this.isInteger = function() { * ... * }; * * Return the single integer that this NestedInteger holds, if it holds a single integer * Return null if this NestedInteger holds a nested list * @return {integer} * this.getInteger = function() { * ... * }; * * Set this NestedInteger to hold a single integer equal to value. * @return {void} * this.setInteger = function(value) { * ... * }; * * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. * @return {void} * this.add = function(elem) { * ... * }; * * Return the nested list that this NestedInteger holds, if it holds a nested list * Return null if this NestedInteger holds a single integer * @return {NestedInteger[]} * this.getList = function() { * ... * }; * }; */ /** * @param {NestedInteger[]} nestedList * @return {number} */ var depthSum = function (nestedList) { const dfs = (nestedList, depth) => { let depthSum = 0; for (const item of nestedList) { if (item.isInteger()) { depthSum += item.getInteger() * depth; } else { depthSum += dfs(item.getList(), depth + 1); } } return depthSum; }; return dfs(nestedList, 1); };
339
Nested List Weight Sum
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>The <strong>depth</strong> of an integer is the number of lists that it is inside of. For example, the nested list <code>[1,[2,2],[[3],2],1]</code> has each integer&#39;s value set to its <strong>depth</strong>.</p> <p>Return <em>the sum of each integer in </em><code>nestedList</code><em> multiplied by its <strong>depth</strong></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/0300-0399/0339.Nested%20List%20Weight%20Sum/images/nestedlistweightsumex1.png" style="width: 405px; height: 99px;" /> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> 10 <strong>Explanation:</strong> Four 1&#39;s at depth 2, one 2 at depth 1. 1*2 + 1*2 + 2*1 + 1*2 + 1*2 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0339.Nested%20List%20Weight%20Sum/images/nestedlistweightsumex2.png" style="width: 315px; height: 106px;" /> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> 27 <strong>Explanation:</strong> One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3. 1*1 + 4*2 + 6*3 = 27.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nestedList = [0] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 50</code></li> <li>The values of the integers in the nested list is in the range <code>[-100, 100]</code>.</li> <li>The maximum <strong>depth</strong> of any integer is less than or equal to <code>50</code>.</li> </ul>
Depth-First Search; Breadth-First Search
Python
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ # class NestedInteger: # def __init__(self, value=None): # """ # If value is not specified, initializes an empty list. # Otherwise initializes a single integer equal to value. # """ # # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def add(self, elem): # """ # Set this NestedInteger to hold a nested list and adds a nested integer elem to it. # :rtype void # """ # # def setInteger(self, value): # """ # Set this NestedInteger to hold a single integer equal to value. # :rtype void # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class Solution: def depthSum(self, nestedList: List[NestedInteger]) -> int: def dfs(nestedList, depth): depth_sum = 0 for item in nestedList: if item.isInteger(): depth_sum += item.getInteger() * depth else: depth_sum += dfs(item.getList(), depth + 1) return depth_sum return dfs(nestedList, 1)
340
Longest Substring with At Most K Distinct Characters
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the length of the longest </em><span data-keyword="substring-nonempty"><em>substring</em></span><em> of</em> <code>s</code> <em>that contains at most</em> <code>k</code> <em><strong>distinct</strong> characters</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;eceba&quot;, k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The substring is &quot;ece&quot; with length 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The substring is &quot;aa&quot; with length 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= k &lt;= 50</code></li> </ul>
Hash Table; String; Sliding Window
C++
class Solution { public: int lengthOfLongestSubstringKDistinct(string s, int k) { unordered_map<char, int> cnt; int l = 0; for (char& c : s) { ++cnt[c]; if (cnt.size() > k) { if (--cnt[s[l]] == 0) { cnt.erase(s[l]); } ++l; } } return s.size() - l; } };
340
Longest Substring with At Most K Distinct Characters
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the length of the longest </em><span data-keyword="substring-nonempty"><em>substring</em></span><em> of</em> <code>s</code> <em>that contains at most</em> <code>k</code> <em><strong>distinct</strong> characters</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;eceba&quot;, k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The substring is &quot;ece&quot; with length 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The substring is &quot;aa&quot; with length 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= k &lt;= 50</code></li> </ul>
Hash Table; String; Sliding Window
Go
func lengthOfLongestSubstringKDistinct(s string, k int) int { cnt := map[byte]int{} l := 0 for _, c := range s { cnt[byte(c)]++ if len(cnt) > k { cnt[s[l]]-- if cnt[s[l]] == 0 { delete(cnt, s[l]) } l++ } } return len(s) - l }
340
Longest Substring with At Most K Distinct Characters
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the length of the longest </em><span data-keyword="substring-nonempty"><em>substring</em></span><em> of</em> <code>s</code> <em>that contains at most</em> <code>k</code> <em><strong>distinct</strong> characters</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;eceba&quot;, k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The substring is &quot;ece&quot; with length 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The substring is &quot;aa&quot; with length 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= k &lt;= 50</code></li> </ul>
Hash Table; String; Sliding Window
Java
class Solution { public int lengthOfLongestSubstringKDistinct(String s, int k) { Map<Character, Integer> cnt = new HashMap<>(); int l = 0; char[] cs = s.toCharArray(); for (char c : cs) { cnt.merge(c, 1, Integer::sum); if (cnt.size() > k) { if (cnt.merge(cs[l], -1, Integer::sum) == 0) { cnt.remove(cs[l]); } ++l; } } return cs.length - l; } }
340
Longest Substring with At Most K Distinct Characters
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the length of the longest </em><span data-keyword="substring-nonempty"><em>substring</em></span><em> of</em> <code>s</code> <em>that contains at most</em> <code>k</code> <em><strong>distinct</strong> characters</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;eceba&quot;, k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The substring is &quot;ece&quot; with length 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The substring is &quot;aa&quot; with length 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= k &lt;= 50</code></li> </ul>
Hash Table; String; Sliding Window
Python
class Solution: def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int: l = 0 cnt = Counter() for c in s: cnt[c] += 1 if len(cnt) > k: cnt[s[l]] -= 1 if cnt[s[l]] == 0: del cnt[s[l]] l += 1 return len(s) - l
340
Longest Substring with At Most K Distinct Characters
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the length of the longest </em><span data-keyword="substring-nonempty"><em>substring</em></span><em> of</em> <code>s</code> <em>that contains at most</em> <code>k</code> <em><strong>distinct</strong> characters</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;eceba&quot;, k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The substring is &quot;ece&quot; with length 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The substring is &quot;aa&quot; with length 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= k &lt;= 50</code></li> </ul>
Hash Table; String; Sliding Window
TypeScript
function lengthOfLongestSubstringKDistinct(s: string, k: number): number { const cnt: Map<string, number> = new Map(); let l = 0; for (const c of s) { cnt.set(c, (cnt.get(c) ?? 0) + 1); if (cnt.size > k) { cnt.set(s[l], cnt.get(s[l])! - 1); if (cnt.get(s[l]) === 0) { cnt.delete(s[l]); } l++; } } return s.length - l; }
341
Flatten Nested List Iterator
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.</p> <p>Implement the <code>NestedIterator</code> class:</p> <ul> <li><code>NestedIterator(List&lt;NestedInteger&gt; nestedList)</code> Initializes the iterator with the nested list <code>nestedList</code>.</li> <li><code>int next()</code> Returns the next integer in the nested list.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there are still some integers in the nested list and <code>false</code> otherwise.</li> </ul> <p>Your code will be tested with the following pseudocode:</p> <pre> initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res </pre> <p>If <code>res</code> matches the expected flattened list, then your code will be judged as correct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> [1,1,2,1,1] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> [1,4,6] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 500</code></li> <li>The values of the integers in the nested list is in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li> </ul>
Stack; Tree; Depth-First Search; Design; Queue; Iterator
C++
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * public: * // Return true if this NestedInteger holds a single integer, rather than a nested list. * bool isInteger() const; * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * int getInteger() const; * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The result is undefined if this NestedInteger holds a single integer * const vector<NestedInteger> &getList() const; * }; */ class NestedIterator { public: NestedIterator(vector<NestedInteger>& nestedList) { auto dfs = [&](this auto&& dfs, vector<NestedInteger>& ls) -> void { for (auto& x : ls) { if (x.isInteger()) { nums.push_back(x.getInteger()); } else { dfs(x.getList()); } } }; dfs(nestedList); } int next() { return nums[++i]; } bool hasNext() { return i + 1 < nums.size(); } private: vector<int> nums; int i = -1; }; /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i(nestedList); * while (i.hasNext()) cout << i.next(); */
341
Flatten Nested List Iterator
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.</p> <p>Implement the <code>NestedIterator</code> class:</p> <ul> <li><code>NestedIterator(List&lt;NestedInteger&gt; nestedList)</code> Initializes the iterator with the nested list <code>nestedList</code>.</li> <li><code>int next()</code> Returns the next integer in the nested list.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there are still some integers in the nested list and <code>false</code> otherwise.</li> </ul> <p>Your code will be tested with the following pseudocode:</p> <pre> initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res </pre> <p>If <code>res</code> matches the expected flattened list, then your code will be judged as correct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> [1,1,2,1,1] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> [1,4,6] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 500</code></li> <li>The values of the integers in the nested list is in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li> </ul>
Stack; Tree; Depth-First Search; Design; Queue; Iterator
Go
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * type NestedInteger struct { * } * * // Return true if this NestedInteger holds a single integer, rather than a nested list. * func (this NestedInteger) IsInteger() bool {} * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * // So before calling this method, you should have a check * func (this NestedInteger) GetInteger() int {} * * // Set this NestedInteger to hold a single integer. * func (n *NestedInteger) SetInteger(value int) {} * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * func (this *NestedInteger) Add(elem NestedInteger) {} * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The list length is zero if this NestedInteger holds a single integer * // You can access NestedInteger's List element directly if you want to modify it * func (this NestedInteger) GetList() []*NestedInteger {} */ type NestedIterator struct { nums []int i int } func Constructor(nestedList []*NestedInteger) *NestedIterator { var dfs func([]*NestedInteger) nums := []int{} i := -1 dfs = func(ls []*NestedInteger) { for _, x := range ls { if x.IsInteger() { nums = append(nums, x.GetInteger()) } else { dfs(x.GetList()) } } } dfs(nestedList) return &NestedIterator{nums, i} } func (this *NestedIterator) Next() int { this.i++ return this.nums[this.i] } func (this *NestedIterator) HasNext() bool { return this.i+1 < len(this.nums) }
341
Flatten Nested List Iterator
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.</p> <p>Implement the <code>NestedIterator</code> class:</p> <ul> <li><code>NestedIterator(List&lt;NestedInteger&gt; nestedList)</code> Initializes the iterator with the nested list <code>nestedList</code>.</li> <li><code>int next()</code> Returns the next integer in the nested list.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there are still some integers in the nested list and <code>false</code> otherwise.</li> </ul> <p>Your code will be tested with the following pseudocode:</p> <pre> initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res </pre> <p>If <code>res</code> matches the expected flattened list, then your code will be judged as correct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> [1,1,2,1,1] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> [1,4,6] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 500</code></li> <li>The values of the integers in the nested list is in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li> </ul>
Stack; Tree; Depth-First Search; Design; Queue; Iterator
Java
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return empty list if this NestedInteger holds a single integer * public List<NestedInteger> getList(); * } */ public class NestedIterator implements Iterator<Integer> { private List<Integer> nums = new ArrayList<>(); private int i = -1; public NestedIterator(List<NestedInteger> nestedList) { dfs(nestedList); } @Override public Integer next() { return nums.get(++i); } @Override public boolean hasNext() { return i + 1 < nums.size(); } private void dfs(List<NestedInteger> ls) { for (var x : ls) { if (x.isInteger()) { nums.add(x.getInteger()); } else { dfs(x.getList()); } } } } /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i = new NestedIterator(nestedList); * while (i.hasNext()) v[f()] = i.next(); */
341
Flatten Nested List Iterator
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.</p> <p>Implement the <code>NestedIterator</code> class:</p> <ul> <li><code>NestedIterator(List&lt;NestedInteger&gt; nestedList)</code> Initializes the iterator with the nested list <code>nestedList</code>.</li> <li><code>int next()</code> Returns the next integer in the nested list.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there are still some integers in the nested list and <code>false</code> otherwise.</li> </ul> <p>Your code will be tested with the following pseudocode:</p> <pre> initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res </pre> <p>If <code>res</code> matches the expected flattened list, then your code will be judged as correct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> [1,1,2,1,1] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> [1,4,6] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 500</code></li> <li>The values of the integers in the nested list is in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li> </ul>
Stack; Tree; Depth-First Search; Design; Queue; Iterator
Python
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ # class NestedInteger: # def isInteger(self) -> bool: # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # """ # # def getInteger(self) -> int: # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # """ # # def getList(self) -> [NestedInteger]: # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # """ class NestedIterator: def __init__(self, nestedList: [NestedInteger]): def dfs(ls): for x in ls: if x.isInteger(): self.nums.append(x.getInteger()) else: dfs(x.getList()) self.nums = [] self.i = -1 dfs(nestedList) def next(self) -> int: self.i += 1 return self.nums[self.i] def hasNext(self) -> bool: return self.i + 1 < len(self.nums) # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next())
341
Flatten Nested List Iterator
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.</p> <p>Implement the <code>NestedIterator</code> class:</p> <ul> <li><code>NestedIterator(List&lt;NestedInteger&gt; nestedList)</code> Initializes the iterator with the nested list <code>nestedList</code>.</li> <li><code>int next()</code> Returns the next integer in the nested list.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there are still some integers in the nested list and <code>false</code> otherwise.</li> </ul> <p>Your code will be tested with the following pseudocode:</p> <pre> initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res </pre> <p>If <code>res</code> matches the expected flattened list, then your code will be judged as correct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> [1,1,2,1,1] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> [1,4,6] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 500</code></li> <li>The values of the integers in the nested list is in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li> </ul>
Stack; Tree; Depth-First Search; Design; Queue; Iterator
Rust
// #[derive(Debug, PartialEq, Eq)] // pub enum NestedInteger { // Int(i32), // List(Vec<NestedInteger>) // } struct NestedIterator { nums: Vec<i32>, i: usize, } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl NestedIterator { fn new(nested_list: Vec<NestedInteger>) -> Self { let mut nums = Vec::new(); Self::dfs(&nested_list, &mut nums); NestedIterator { nums, i: 0 } } fn next(&mut self) -> i32 { let result = self.nums[self.i]; self.i += 1; result } fn has_next(&self) -> bool { self.i < self.nums.len() } fn dfs(nested_list: &Vec<NestedInteger>, nums: &mut Vec<i32>) { for ni in nested_list { match ni { NestedInteger::Int(x) => nums.push(*x), NestedInteger::List(list) => Self::dfs(list, nums), } } } }
341
Flatten Nested List Iterator
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.</p> <p>Implement the <code>NestedIterator</code> class:</p> <ul> <li><code>NestedIterator(List&lt;NestedInteger&gt; nestedList)</code> Initializes the iterator with the nested list <code>nestedList</code>.</li> <li><code>int next()</code> Returns the next integer in the nested list.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there are still some integers in the nested list and <code>false</code> otherwise.</li> </ul> <p>Your code will be tested with the following pseudocode:</p> <pre> initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res </pre> <p>If <code>res</code> matches the expected flattened list, then your code will be judged as correct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> [1,1,2,1,1] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> [1,4,6] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 500</code></li> <li>The values of the integers in the nested list is in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li> </ul>
Stack; Tree; Depth-First Search; Design; Queue; Iterator
TypeScript
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * If value is provided, then it holds a single integer * Otherwise it holds an empty nested list * constructor(value?: number) { * ... * }; * * Return true if this NestedInteger holds a single integer, rather than a nested list. * isInteger(): boolean { * ... * }; * * Return the single integer that this NestedInteger holds, if it holds a single integer * Return null if this NestedInteger holds a nested list * getInteger(): number | null { * ... * }; * * Set this NestedInteger to hold a single integer equal to value. * setInteger(value: number) { * ... * }; * * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. * add(elem: NestedInteger) { * ... * }; * * Return the nested list that this NestedInteger holds, * or an empty list if this NestedInteger holds a single integer * getList(): NestedInteger[] { * ... * }; * }; */ class NestedIterator { private nums: number[] = []; private i = -1; constructor(nestedList: NestedInteger[]) { const dfs = (ls: NestedInteger[]) => { for (const x of ls) { if (x.isInteger()) { this.nums.push(x.getInteger()); } else { dfs(x.getList()); } } }; dfs(nestedList); } hasNext(): boolean { return this.i + 1 < this.nums.length; } next(): number { return this.nums[++this.i]; } } /** * Your ParkingSystem object will be instantiated and called as such: * var obj = new NestedIterator(nestedList) * var a: number[] = [] * while (obj.hasNext()) a.push(obj.next()); */
342
Power of Four
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of four. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of four, if there exists an integer <code>x</code> such that <code>n == 4<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 16 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> true </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 isPowerOfFour(int n) { return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; } };
342
Power of Four
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of four. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of four, if there exists an integer <code>x</code> such that <code>n == 4<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 16 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> true </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#
public class Solution { public bool IsPowerOfFour(int n) { return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; } }
342
Power of Four
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of four. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of four, if there exists an integer <code>x</code> such that <code>n == 4<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 16 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> true </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 isPowerOfFour(n int) bool { return n > 0 && (n&(n-1)) == 0 && (n&0xaaaaaaaa) == 0 }
342
Power of Four
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of four. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of four, if there exists an integer <code>x</code> such that <code>n == 4<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 16 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> true </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 isPowerOfFour(int n) { return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; } }
342
Power of Four
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of four. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of four, if there exists an integer <code>x</code> such that <code>n == 4<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 16 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> true </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 isPowerOfFour = function (n) { return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; };
342
Power of Four
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of four. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of four, if there exists an integer <code>x</code> such that <code>n == 4<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 16 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> true </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 isPowerOfFour(self, n: int) -> bool: return n > 0 and (n & (n - 1)) == 0 and (n & 0xAAAAAAAA) == 0
342
Power of Four
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of four. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of four, if there exists an integer <code>x</code> such that <code>n == 4<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 16 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> true </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_four(n: i32) -> bool { n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa_u32 as i32) == 0 } }
342
Power of Four
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of four. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of four, if there exists an integer <code>x</code> such that <code>n == 4<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 16 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> true </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 isPowerOfFour(n: number): boolean { return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; }
343
Integer Break
Medium
<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p> <p>Return <em>the maximum product you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 36 <strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 58</code></li> </ul>
Math; Dynamic Programming
C
#define max(a, b) (((a) > (b)) ? (a) : (b)) int integerBreak(int n) { int* f = (int*) malloc((n + 1) * sizeof(int)); f[1] = 1; for (int i = 2; i <= n; ++i) { f[i] = 0; for (int j = 1; j < i; ++j) { f[i] = max(f[i], max(f[i - j] * j, (i - j) * j)); } } return f[n]; }
343
Integer Break
Medium
<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p> <p>Return <em>the maximum product you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 36 <strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 58</code></li> </ul>
Math; Dynamic Programming
C++
class Solution { public: int integerBreak(int n) { vector<int> f(n + 1); f[1] = 1; for (int i = 2; i <= n; ++i) { for (int j = 1; j < i; ++j) { f[i] = max({f[i], f[i - j] * j, (i - j) * j}); } } return f[n]; } };
343
Integer Break
Medium
<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p> <p>Return <em>the maximum product you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 36 <strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 58</code></li> </ul>
Math; Dynamic Programming
C#
public class Solution { public int IntegerBreak(int n) { int[] f = new int[n + 1]; f[1] = 1; for (int i = 2; i <= n; ++i) { for (int j = 1; j < i; ++j) { f[i] = Math.Max(Math.Max(f[i], f[i - j] * j), (i - j) * j); } } return f[n]; } }