id
int64
1
3.64k
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
84
Largest Rectangle in Histogram
Hard
<p>Given an array of integers <code>heights</code> representing the histogram&#39;s bar height where the width of each bar is <code>1</code>, return <em>the area of the largest rectangle in the histogram</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/0000-0099/0084.Largest%20Rectangle%20in%20Histogram/images/histogram.jpg" style="width: 522px; height: 242px;" /> <pre> <strong>Input:</strong> heights = [2,1,5,6,2,3] <strong>Output:</strong> 10 <strong>Explanation:</strong> The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0084.Largest%20Rectangle%20in%20Histogram/images/histogram-1.jpg" style="width: 202px; height: 362px;" /> <pre> <strong>Input:</strong> heights = [2,4] <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= heights.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= heights[i] &lt;= 10<sup>4</sup></code></li> </ul>
Stack; Array; Monotonic Stack
C#
using System; using System.Collections.Generic; using System.Linq; public class Solution { public int LargestRectangleArea(int[] height) { var stack = new Stack<int>(); var result = 0; var i = 0; while (i < height.Length || stack.Any()) { if (!stack.Any() || (i < height.Length && height[stack.Peek()] < height[i])) { stack.Push(i); ++i; } else { var previousIndex = stack.Pop(); var area = height[previousIndex] * (stack.Any() ? (i - stack.Peek() - 1) : i); result = Math.Max(result, area); } } return result; } }
84
Largest Rectangle in Histogram
Hard
<p>Given an array of integers <code>heights</code> representing the histogram&#39;s bar height where the width of each bar is <code>1</code>, return <em>the area of the largest rectangle in the histogram</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/0000-0099/0084.Largest%20Rectangle%20in%20Histogram/images/histogram.jpg" style="width: 522px; height: 242px;" /> <pre> <strong>Input:</strong> heights = [2,1,5,6,2,3] <strong>Output:</strong> 10 <strong>Explanation:</strong> The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0084.Largest%20Rectangle%20in%20Histogram/images/histogram-1.jpg" style="width: 202px; height: 362px;" /> <pre> <strong>Input:</strong> heights = [2,4] <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= heights.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= heights[i] &lt;= 10<sup>4</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Go
func largestRectangleArea(heights []int) int { res, n := 0, len(heights) var stk []int left, right := make([]int, n), make([]int, n) for i := range right { right[i] = n } for i, h := range heights { for len(stk) > 0 && heights[stk[len(stk)-1]] >= h { right[stk[len(stk)-1]] = i stk = stk[:len(stk)-1] } if len(stk) > 0 { left[i] = stk[len(stk)-1] } else { left[i] = -1 } stk = append(stk, i) } for i, h := range heights { res = max(res, h*(right[i]-left[i]-1)) } return res }
84
Largest Rectangle in Histogram
Hard
<p>Given an array of integers <code>heights</code> representing the histogram&#39;s bar height where the width of each bar is <code>1</code>, return <em>the area of the largest rectangle in the histogram</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/0000-0099/0084.Largest%20Rectangle%20in%20Histogram/images/histogram.jpg" style="width: 522px; height: 242px;" /> <pre> <strong>Input:</strong> heights = [2,1,5,6,2,3] <strong>Output:</strong> 10 <strong>Explanation:</strong> The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0084.Largest%20Rectangle%20in%20Histogram/images/histogram-1.jpg" style="width: 202px; height: 362px;" /> <pre> <strong>Input:</strong> heights = [2,4] <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= heights.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= heights[i] &lt;= 10<sup>4</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Java
class Solution { public int largestRectangleArea(int[] heights) { int res = 0, n = heights.length; Deque<Integer> stk = new ArrayDeque<>(); int[] left = new int[n]; int[] right = new int[n]; Arrays.fill(right, n); for (int i = 0; i < n; ++i) { while (!stk.isEmpty() && heights[stk.peek()] >= heights[i]) { right[stk.pop()] = i; } left[i] = stk.isEmpty() ? -1 : stk.peek(); stk.push(i); } for (int i = 0; i < n; ++i) { res = Math.max(res, heights[i] * (right[i] - left[i] - 1)); } return res; } }
84
Largest Rectangle in Histogram
Hard
<p>Given an array of integers <code>heights</code> representing the histogram&#39;s bar height where the width of each bar is <code>1</code>, return <em>the area of the largest rectangle in the histogram</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/0000-0099/0084.Largest%20Rectangle%20in%20Histogram/images/histogram.jpg" style="width: 522px; height: 242px;" /> <pre> <strong>Input:</strong> heights = [2,1,5,6,2,3] <strong>Output:</strong> 10 <strong>Explanation:</strong> The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0084.Largest%20Rectangle%20in%20Histogram/images/histogram-1.jpg" style="width: 202px; height: 362px;" /> <pre> <strong>Input:</strong> heights = [2,4] <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= heights.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= heights[i] &lt;= 10<sup>4</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Python
class Solution: def largestRectangleArea(self, heights: List[int]) -> int: n = len(heights) stk = [] left = [-1] * n right = [n] * n for i, h in enumerate(heights): while stk and heights[stk[-1]] >= h: right[stk[-1]] = i stk.pop() if stk: left[i] = stk[-1] stk.append(i) return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights))
84
Largest Rectangle in Histogram
Hard
<p>Given an array of integers <code>heights</code> representing the histogram&#39;s bar height where the width of each bar is <code>1</code>, return <em>the area of the largest rectangle in the histogram</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/0000-0099/0084.Largest%20Rectangle%20in%20Histogram/images/histogram.jpg" style="width: 522px; height: 242px;" /> <pre> <strong>Input:</strong> heights = [2,1,5,6,2,3] <strong>Output:</strong> 10 <strong>Explanation:</strong> The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0084.Largest%20Rectangle%20in%20Histogram/images/histogram-1.jpg" style="width: 202px; height: 362px;" /> <pre> <strong>Input:</strong> heights = [2,4] <strong>Output:</strong> 4 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= heights.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= heights[i] &lt;= 10<sup>4</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Rust
impl Solution { #[allow(dead_code)] pub fn largest_rectangle_area(heights: Vec<i32>) -> i32 { let n = heights.len(); let mut left = vec![-1; n]; let mut right = vec![-1; n]; let mut stack: Vec<(usize, i32)> = Vec::new(); let mut ret = -1; // Build left vector for (i, h) in heights.iter().enumerate() { while !stack.is_empty() && stack.last().unwrap().1 >= *h { stack.pop(); } if stack.is_empty() { left[i] = -1; } else { left[i] = stack.last().unwrap().0 as i32; } stack.push((i, *h)); } stack.clear(); // Build right vector for (i, h) in heights.iter().enumerate().rev() { while !stack.is_empty() && stack.last().unwrap().1 >= *h { stack.pop(); } if stack.is_empty() { right[i] = n as i32; } else { right[i] = stack.last().unwrap().0 as i32; } stack.push((i, *h)); } // Calculate the max area for (i, h) in heights.iter().enumerate() { ret = std::cmp::max(ret, (right[i] - left[i] - 1) * *h); } ret } }
85
Maximal Rectangle
Hard
<p>Given a <code>rows x cols</code>&nbsp;binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, find the largest rectangle containing only <code>1</code>&#39;s and return <em>its area</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0085.Maximal%20Rectangle/images/maximal.jpg" style="width: 402px; height: 322px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 6 <strong>Explanation:</strong> The maximal rectangle is shown in the above picture. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;]] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>rows == matrix.length</code></li> <li><code>cols == matrix[i].length</code></li> <li><code>1 &lt;= row, cols &lt;= 200</code></li> <li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Stack; Array; Dynamic Programming; Matrix; Monotonic Stack
C++
class Solution { public: int maximalRectangle(vector<vector<char>>& matrix) { int n = matrix[0].size(); vector<int> heights(n); int ans = 0; for (auto& row : matrix) { for (int j = 0; j < n; ++j) { if (row[j] == '1') ++heights[j]; else heights[j] = 0; } ans = max(ans, largestRectangleArea(heights)); } return ans; } int largestRectangleArea(vector<int>& heights) { int res = 0, n = heights.size(); stack<int> stk; vector<int> left(n, -1); vector<int> right(n, n); for (int i = 0; i < n; ++i) { while (!stk.empty() && heights[stk.top()] >= heights[i]) { right[stk.top()] = i; stk.pop(); } if (!stk.empty()) left[i] = stk.top(); stk.push(i); } for (int i = 0; i < n; ++i) res = max(res, heights[i] * (right[i] - left[i] - 1)); return res; } };
85
Maximal Rectangle
Hard
<p>Given a <code>rows x cols</code>&nbsp;binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, find the largest rectangle containing only <code>1</code>&#39;s and return <em>its area</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0085.Maximal%20Rectangle/images/maximal.jpg" style="width: 402px; height: 322px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 6 <strong>Explanation:</strong> The maximal rectangle is shown in the above picture. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;]] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>rows == matrix.length</code></li> <li><code>cols == matrix[i].length</code></li> <li><code>1 &lt;= row, cols &lt;= 200</code></li> <li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Stack; Array; Dynamic Programming; Matrix; Monotonic Stack
C#
using System; using System.Collections.Generic; using System.Linq; public class Solution { private int MaximalRectangleHistagram(int[] height) { var stack = new Stack<int>(); var result = 0; var i = 0; while (i < height.Length || stack.Any()) { if (!stack.Any() || (i < height.Length && height[stack.Peek()] < height[i])) { stack.Push(i); ++i; } else { var previousIndex = stack.Pop(); var area = height[previousIndex] * (stack.Any() ? (i - stack.Peek() - 1) : i); result = Math.Max(result, area); } } return result; } public int MaximalRectangle(char[][] matrix) { var lenI = matrix.Length; var lenJ = lenI == 0 ? 0 : matrix[0].Length; var height = new int[lenJ]; var result = 0; for (var i = 0; i < lenI; ++i) { for (var j = 0; j < lenJ; ++j) { if (matrix[i][j] == '1') { ++height[j]; } else { height[j] = 0; } } result = Math.Max(result, MaximalRectangleHistagram(height)); } return result; } }
85
Maximal Rectangle
Hard
<p>Given a <code>rows x cols</code>&nbsp;binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, find the largest rectangle containing only <code>1</code>&#39;s and return <em>its area</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0085.Maximal%20Rectangle/images/maximal.jpg" style="width: 402px; height: 322px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 6 <strong>Explanation:</strong> The maximal rectangle is shown in the above picture. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;]] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>rows == matrix.length</code></li> <li><code>cols == matrix[i].length</code></li> <li><code>1 &lt;= row, cols &lt;= 200</code></li> <li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Stack; Array; Dynamic Programming; Matrix; Monotonic Stack
Go
func maximalRectangle(matrix [][]byte) int { n := len(matrix[0]) heights := make([]int, n) ans := 0 for _, row := range matrix { for j, v := range row { if v == '1' { heights[j]++ } else { heights[j] = 0 } } ans = max(ans, largestRectangleArea(heights)) } return ans } func largestRectangleArea(heights []int) int { res, n := 0, len(heights) var stk []int left, right := make([]int, n), make([]int, n) for i := range right { right[i] = n } for i, h := range heights { for len(stk) > 0 && heights[stk[len(stk)-1]] >= h { right[stk[len(stk)-1]] = i stk = stk[:len(stk)-1] } if len(stk) > 0 { left[i] = stk[len(stk)-1] } else { left[i] = -1 } stk = append(stk, i) } for i, h := range heights { res = max(res, h*(right[i]-left[i]-1)) } return res }
85
Maximal Rectangle
Hard
<p>Given a <code>rows x cols</code>&nbsp;binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, find the largest rectangle containing only <code>1</code>&#39;s and return <em>its area</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0085.Maximal%20Rectangle/images/maximal.jpg" style="width: 402px; height: 322px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 6 <strong>Explanation:</strong> The maximal rectangle is shown in the above picture. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;]] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>rows == matrix.length</code></li> <li><code>cols == matrix[i].length</code></li> <li><code>1 &lt;= row, cols &lt;= 200</code></li> <li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Stack; Array; Dynamic Programming; Matrix; Monotonic Stack
Java
class Solution { public int maximalRectangle(char[][] matrix) { int n = matrix[0].length; int[] heights = new int[n]; int ans = 0; for (var row : matrix) { for (int j = 0; j < n; ++j) { if (row[j] == '1') { heights[j] += 1; } else { heights[j] = 0; } } ans = Math.max(ans, largestRectangleArea(heights)); } return ans; } private int largestRectangleArea(int[] heights) { int res = 0, n = heights.length; Deque<Integer> stk = new ArrayDeque<>(); int[] left = new int[n]; int[] right = new int[n]; Arrays.fill(right, n); for (int i = 0; i < n; ++i) { while (!stk.isEmpty() && heights[stk.peek()] >= heights[i]) { right[stk.pop()] = i; } left[i] = stk.isEmpty() ? -1 : stk.peek(); stk.push(i); } for (int i = 0; i < n; ++i) { res = Math.max(res, heights[i] * (right[i] - left[i] - 1)); } return res; } }
85
Maximal Rectangle
Hard
<p>Given a <code>rows x cols</code>&nbsp;binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, find the largest rectangle containing only <code>1</code>&#39;s and return <em>its area</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0085.Maximal%20Rectangle/images/maximal.jpg" style="width: 402px; height: 322px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 6 <strong>Explanation:</strong> The maximal rectangle is shown in the above picture. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;]] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>rows == matrix.length</code></li> <li><code>cols == matrix[i].length</code></li> <li><code>1 &lt;= row, cols &lt;= 200</code></li> <li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Stack; Array; Dynamic Programming; Matrix; Monotonic Stack
Python
class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: heights = [0] * len(matrix[0]) ans = 0 for row in matrix: for j, v in enumerate(row): if v == "1": heights[j] += 1 else: heights[j] = 0 ans = max(ans, self.largestRectangleArea(heights)) return ans def largestRectangleArea(self, heights: List[int]) -> int: n = len(heights) stk = [] left = [-1] * n right = [n] * n for i, h in enumerate(heights): while stk and heights[stk[-1]] >= h: stk.pop() if stk: left[i] = stk[-1] stk.append(i) stk = [] for i in range(n - 1, -1, -1): h = heights[i] while stk and heights[stk[-1]] >= h: stk.pop() if stk: right[i] = stk[-1] stk.append(i) return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights))
85
Maximal Rectangle
Hard
<p>Given a <code>rows x cols</code>&nbsp;binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, find the largest rectangle containing only <code>1</code>&#39;s and return <em>its area</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0085.Maximal%20Rectangle/images/maximal.jpg" style="width: 402px; height: 322px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 6 <strong>Explanation:</strong> The maximal rectangle is shown in the above picture. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;]] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>rows == matrix.length</code></li> <li><code>cols == matrix[i].length</code></li> <li><code>1 &lt;= row, cols &lt;= 200</code></li> <li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Stack; Array; Dynamic Programming; Matrix; Monotonic Stack
Rust
impl Solution { #[allow(dead_code)] pub fn maximal_rectangle(matrix: Vec<Vec<char>>) -> i32 { let n = matrix[0].len(); let mut heights = vec![0; n]; let mut ret = -1; for row in &matrix { Self::array_builder(row, &mut heights); ret = std::cmp::max(ret, Self::largest_rectangle_area(heights.clone())); } ret } /// Helper function, build the heights array according to the input #[allow(dead_code)] fn array_builder(input: &Vec<char>, heights: &mut Vec<i32>) { for (i, &c) in input.iter().enumerate() { heights[i] += match c { '1' => 1, '0' => { heights[i] = 0; 0 } _ => panic!("This is impossible"), }; } } /// Helper function, see: https://leetcode.com/problems/largest-rectangle-in-histogram/ for details #[allow(dead_code)] fn largest_rectangle_area(heights: Vec<i32>) -> i32 { let n = heights.len(); let mut left = vec![-1; n]; let mut right = vec![-1; n]; let mut stack: Vec<(usize, i32)> = Vec::new(); let mut ret = -1; // Build left vector for (i, h) in heights.iter().enumerate() { while !stack.is_empty() && stack.last().unwrap().1 >= *h { stack.pop(); } if stack.is_empty() { left[i] = -1; } else { left[i] = stack.last().unwrap().0 as i32; } stack.push((i, *h)); } stack.clear(); // Build right vector for (i, h) in heights.iter().enumerate().rev() { while !stack.is_empty() && stack.last().unwrap().1 >= *h { stack.pop(); } if stack.is_empty() { right[i] = n as i32; } else { right[i] = stack.last().unwrap().0 as i32; } stack.push((i, *h)); } // Calculate the max area for (i, h) in heights.iter().enumerate() { ret = std::cmp::max(ret, (right[i] - left[i] - 1) * *h); } ret } }
86
Partition List
Medium
<p>Given the <code>head</code> of a linked list and a value <code>x</code>, partition it such that all nodes <strong>less than</strong> <code>x</code> come before nodes <strong>greater than or equal</strong> to <code>x</code>.</p> <p>You should <strong>preserve</strong> the original relative order of the nodes in each of the two partitions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0086.Partition%20List/images/partition.jpg" style="width: 662px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,4,3,2,5,2], x = 3 <strong>Output:</strong> [1,2,2,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [2,1], x = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 200]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-200 &lt;= x &lt;= 200</code></li> </ul>
Linked List; Two Pointers
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* partition(ListNode* head, int x) { ListNode* l = new ListNode(); ListNode* r = new ListNode(); ListNode* tl = l; ListNode* tr = r; for (; head; head = head->next) { if (head->val < x) { tl->next = head; tl = tl->next; } else { tr->next = head; tr = tr->next; } } tr->next = nullptr; tl->next = r->next; return l->next; } };
86
Partition List
Medium
<p>Given the <code>head</code> of a linked list and a value <code>x</code>, partition it such that all nodes <strong>less than</strong> <code>x</code> come before nodes <strong>greater than or equal</strong> to <code>x</code>.</p> <p>You should <strong>preserve</strong> the original relative order of the nodes in each of the two partitions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0086.Partition%20List/images/partition.jpg" style="width: 662px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,4,3,2,5,2], x = 3 <strong>Output:</strong> [1,2,2,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [2,1], x = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 200]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-200 &lt;= x &lt;= 200</code></li> </ul>
Linked List; Two Pointers
C#
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val=0, ListNode next=null) { * this.val = val; * this.next = next; * } * } */ public class Solution { public ListNode Partition(ListNode head, int x) { ListNode l = new ListNode(); ListNode r = new ListNode(); ListNode tl = l, tr = r; for (; head != null; head = head.next) { if (head.val < x) { tl.next = head; tl = tl.next; } else { tr.next = head; tr = tr.next; } } tr.next = null; tl.next = r.next; return l.next; } }
86
Partition List
Medium
<p>Given the <code>head</code> of a linked list and a value <code>x</code>, partition it such that all nodes <strong>less than</strong> <code>x</code> come before nodes <strong>greater than or equal</strong> to <code>x</code>.</p> <p>You should <strong>preserve</strong> the original relative order of the nodes in each of the two partitions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0086.Partition%20List/images/partition.jpg" style="width: 662px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,4,3,2,5,2], x = 3 <strong>Output:</strong> [1,2,2,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [2,1], x = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 200]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-200 &lt;= x &lt;= 200</code></li> </ul>
Linked List; Two Pointers
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func partition(head *ListNode, x int) *ListNode { l, r := &ListNode{}, &ListNode{} tl, tr := l, r for ; head != nil; head = head.Next { if head.Val < x { tl.Next = head tl = tl.Next } else { tr.Next = head tr = tr.Next } } tr.Next = nil tl.Next = r.Next return l.Next }
86
Partition List
Medium
<p>Given the <code>head</code> of a linked list and a value <code>x</code>, partition it such that all nodes <strong>less than</strong> <code>x</code> come before nodes <strong>greater than or equal</strong> to <code>x</code>.</p> <p>You should <strong>preserve</strong> the original relative order of the nodes in each of the two partitions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0086.Partition%20List/images/partition.jpg" style="width: 662px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,4,3,2,5,2], x = 3 <strong>Output:</strong> [1,2,2,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [2,1], x = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 200]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-200 &lt;= x &lt;= 200</code></li> </ul>
Linked List; Two Pointers
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 partition(ListNode head, int x) { ListNode l = new ListNode(); ListNode r = new ListNode(); ListNode tl = l, tr = r; for (; head != null; head = head.next) { if (head.val < x) { tl.next = head; tl = tl.next; } else { tr.next = head; tr = tr.next; } } tr.next = null; tl.next = r.next; return l.next; } }
86
Partition List
Medium
<p>Given the <code>head</code> of a linked list and a value <code>x</code>, partition it such that all nodes <strong>less than</strong> <code>x</code> come before nodes <strong>greater than or equal</strong> to <code>x</code>.</p> <p>You should <strong>preserve</strong> the original relative order of the nodes in each of the two partitions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0086.Partition%20List/images/partition.jpg" style="width: 662px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,4,3,2,5,2], x = 3 <strong>Output:</strong> [1,2,2,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [2,1], x = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 200]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-200 &lt;= x &lt;= 200</code></li> </ul>
Linked List; Two Pointers
JavaScript
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @param {number} x * @return {ListNode} */ var partition = function (head, x) { const [l, r] = [new ListNode(), new ListNode()]; let [tl, tr] = [l, r]; for (; head; head = head.next) { if (head.val < x) { tl.next = head; tl = tl.next; } else { tr.next = head; tr = tr.next; } } tr.next = null; tl.next = r.next; return l.next; };
86
Partition List
Medium
<p>Given the <code>head</code> of a linked list and a value <code>x</code>, partition it such that all nodes <strong>less than</strong> <code>x</code> come before nodes <strong>greater than or equal</strong> to <code>x</code>.</p> <p>You should <strong>preserve</strong> the original relative order of the nodes in each of the two partitions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0086.Partition%20List/images/partition.jpg" style="width: 662px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,4,3,2,5,2], x = 3 <strong>Output:</strong> [1,2,2,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [2,1], x = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 200]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-200 &lt;= x &lt;= 200</code></li> </ul>
Linked List; Two Pointers
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]: l = ListNode() r = ListNode() tl, tr = l, r while head: if head.val < x: tl.next = head tl = tl.next else: tr.next = head tr = tr.next head = head.next tr.next = None tl.next = r.next return l.next
86
Partition List
Medium
<p>Given the <code>head</code> of a linked list and a value <code>x</code>, partition it such that all nodes <strong>less than</strong> <code>x</code> come before nodes <strong>greater than or equal</strong> to <code>x</code>.</p> <p>You should <strong>preserve</strong> the original relative order of the nodes in each of the two partitions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0086.Partition%20List/images/partition.jpg" style="width: 662px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,4,3,2,5,2], x = 3 <strong>Output:</strong> [1,2,2,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [2,1], x = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 200]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-200 &lt;= x &lt;= 200</code></li> </ul>
Linked List; Two Pointers
Rust
// Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] // pub struct ListNode { // pub val: i32, // pub next: Option<Box<ListNode>> // } // // impl ListNode { // #[inline] // fn new(val: i32) -> Self { // ListNode { // next: None, // val // } // } // } impl Solution { pub fn partition(head: Option<Box<ListNode>>, x: i32) -> Option<Box<ListNode>> { let mut l = ListNode::new(0); let mut r = ListNode::new(0); let mut tl = &mut l; let mut tr = &mut r; let mut current = head; while let Some(mut node) = current { current = node.next.take(); if node.val < x { tl.next = Some(node); tl = tl.next.as_mut().unwrap(); } else { tr.next = Some(node); tr = tr.next.as_mut().unwrap(); } } tr.next = None; tl.next = r.next; l.next } }
86
Partition List
Medium
<p>Given the <code>head</code> of a linked list and a value <code>x</code>, partition it such that all nodes <strong>less than</strong> <code>x</code> come before nodes <strong>greater than or equal</strong> to <code>x</code>.</p> <p>You should <strong>preserve</strong> the original relative order of the nodes in each of the two partitions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0086.Partition%20List/images/partition.jpg" style="width: 662px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,4,3,2,5,2], x = 3 <strong>Output:</strong> [1,2,2,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [2,1], x = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is in the range <code>[0, 200]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li><code>-200 &lt;= x &lt;= 200</code></li> </ul>
Linked List; Two Pointers
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 partition(head: ListNode | null, x: number): ListNode | null { const [l, r] = [new ListNode(), new ListNode()]; let [tl, tr] = [l, r]; for (; head; head = head.next) { if (head.val < x) { tl.next = head; tl = tl.next; } else { tr.next = head; tr = tr.next; } } tr.next = null; tl.next = r.next; return l.next; }
87
Scramble String
Hard
<p>We can scramble a string s to get a string t using the following algorithm:</p> <ol> <li>If the length of the string is 1, stop.</li> <li>If the length of the string is &gt; 1, do the following: <ul> <li>Split the string into two non-empty substrings at a random index, i.e., if the string is <code>s</code>, divide it to <code>x</code> and <code>y</code> where <code>s = x + y</code>.</li> <li><strong>Randomly</strong>&nbsp;decide to swap the two substrings or to keep them in the same order. i.e., after this step, <code>s</code> may become <code>s = x + y</code> or <code>s = y + x</code>.</li> <li>Apply step 1 recursively on each of the two substrings <code>x</code> and <code>y</code>.</li> </ul> </li> </ol> <p>Given two strings <code>s1</code> and <code>s2</code> of <strong>the same length</strong>, return <code>true</code> if <code>s2</code> is a scrambled string of <code>s1</code>, otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;great&quot;, s2 = &quot;rgeat&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible scenario applied on s1 is: &quot;great&quot; --&gt; &quot;gr/eat&quot; // divide at random index. &quot;gr/eat&quot; --&gt; &quot;gr/eat&quot; // random decision is not to swap the two substrings and keep them in order. &quot;gr/eat&quot; --&gt; &quot;g/r / e/at&quot; // apply the same algorithm recursively on both substrings. divide at random index each of them. &quot;g/r / e/at&quot; --&gt; &quot;r/g / e/at&quot; // random decision was to swap the first substring and to keep the second substring in the same order. &quot;r/g / e/at&quot; --&gt; &quot;r/g / e/ a/t&quot; // again apply the algorithm recursively, divide &quot;at&quot; to &quot;a/t&quot;. &quot;r/g / e/ a/t&quot; --&gt; &quot;r/g / e/ a/t&quot; // random decision is to keep both substrings in the same order. The algorithm stops now, and the result string is &quot;rgeat&quot; which is s2. As one possible scenario led s1 to be scrambled to s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcde&quot;, s2 = &quot;caebd&quot; <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;a&quot;, s2 = &quot;a&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>s1.length == s2.length</code></li> <li><code>1 &lt;= s1.length &lt;= 30</code></li> <li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li> </ul>
String; Dynamic Programming
C++
class Solution { public: bool isScramble(string s1, string s2) { int n = s1.size(); int f[n][n][n + 1]; memset(f, -1, sizeof(f)); function<bool(int, int, int)> dfs = [&](int i, int j, int k) -> int { if (f[i][j][k] != -1) { return f[i][j][k] == 1; } if (k == 1) { return s1[i] == s2[j]; } for (int h = 1; h < k; ++h) { if (dfs(i, j, h) && dfs(i + h, j + h, k - h)) { return f[i][j][k] = true; } if (dfs(i + h, j, k - h) && dfs(i, j + k - h, h)) { return f[i][j][k] = true; } } return f[i][j][k] = false; }; return dfs(0, 0, n); } };
87
Scramble String
Hard
<p>We can scramble a string s to get a string t using the following algorithm:</p> <ol> <li>If the length of the string is 1, stop.</li> <li>If the length of the string is &gt; 1, do the following: <ul> <li>Split the string into two non-empty substrings at a random index, i.e., if the string is <code>s</code>, divide it to <code>x</code> and <code>y</code> where <code>s = x + y</code>.</li> <li><strong>Randomly</strong>&nbsp;decide to swap the two substrings or to keep them in the same order. i.e., after this step, <code>s</code> may become <code>s = x + y</code> or <code>s = y + x</code>.</li> <li>Apply step 1 recursively on each of the two substrings <code>x</code> and <code>y</code>.</li> </ul> </li> </ol> <p>Given two strings <code>s1</code> and <code>s2</code> of <strong>the same length</strong>, return <code>true</code> if <code>s2</code> is a scrambled string of <code>s1</code>, otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;great&quot;, s2 = &quot;rgeat&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible scenario applied on s1 is: &quot;great&quot; --&gt; &quot;gr/eat&quot; // divide at random index. &quot;gr/eat&quot; --&gt; &quot;gr/eat&quot; // random decision is not to swap the two substrings and keep them in order. &quot;gr/eat&quot; --&gt; &quot;g/r / e/at&quot; // apply the same algorithm recursively on both substrings. divide at random index each of them. &quot;g/r / e/at&quot; --&gt; &quot;r/g / e/at&quot; // random decision was to swap the first substring and to keep the second substring in the same order. &quot;r/g / e/at&quot; --&gt; &quot;r/g / e/ a/t&quot; // again apply the algorithm recursively, divide &quot;at&quot; to &quot;a/t&quot;. &quot;r/g / e/ a/t&quot; --&gt; &quot;r/g / e/ a/t&quot; // random decision is to keep both substrings in the same order. The algorithm stops now, and the result string is &quot;rgeat&quot; which is s2. As one possible scenario led s1 to be scrambled to s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcde&quot;, s2 = &quot;caebd&quot; <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;a&quot;, s2 = &quot;a&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>s1.length == s2.length</code></li> <li><code>1 &lt;= s1.length &lt;= 30</code></li> <li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li> </ul>
String; Dynamic Programming
C#
public class Solution { private string s1; private string s2; private int[,,] f; public bool IsScramble(string s1, string s2) { int n = s1.Length; this.s1 = s1; this.s2 = s2; f = new int[n, n, n + 1]; return dfs(0, 0, n); } private bool dfs(int i, int j, int k) { if (f[i, j, k] != 0) { return f[i, j, k] == 1; } if (k == 1) { return s1[i] == s2[j]; } for (int h = 1; h < k; ++h) { if (dfs(i, j, h) && dfs(i + h, j + h, k - h)) { f[i, j, k] = 1; return true; } if (dfs(i, j + k - h, h) && dfs(i + h, j, k - h)) { f[i, j, k] = 1; return true; } } f[i, j, k] = -1; return false; } }
87
Scramble String
Hard
<p>We can scramble a string s to get a string t using the following algorithm:</p> <ol> <li>If the length of the string is 1, stop.</li> <li>If the length of the string is &gt; 1, do the following: <ul> <li>Split the string into two non-empty substrings at a random index, i.e., if the string is <code>s</code>, divide it to <code>x</code> and <code>y</code> where <code>s = x + y</code>.</li> <li><strong>Randomly</strong>&nbsp;decide to swap the two substrings or to keep them in the same order. i.e., after this step, <code>s</code> may become <code>s = x + y</code> or <code>s = y + x</code>.</li> <li>Apply step 1 recursively on each of the two substrings <code>x</code> and <code>y</code>.</li> </ul> </li> </ol> <p>Given two strings <code>s1</code> and <code>s2</code> of <strong>the same length</strong>, return <code>true</code> if <code>s2</code> is a scrambled string of <code>s1</code>, otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;great&quot;, s2 = &quot;rgeat&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible scenario applied on s1 is: &quot;great&quot; --&gt; &quot;gr/eat&quot; // divide at random index. &quot;gr/eat&quot; --&gt; &quot;gr/eat&quot; // random decision is not to swap the two substrings and keep them in order. &quot;gr/eat&quot; --&gt; &quot;g/r / e/at&quot; // apply the same algorithm recursively on both substrings. divide at random index each of them. &quot;g/r / e/at&quot; --&gt; &quot;r/g / e/at&quot; // random decision was to swap the first substring and to keep the second substring in the same order. &quot;r/g / e/at&quot; --&gt; &quot;r/g / e/ a/t&quot; // again apply the algorithm recursively, divide &quot;at&quot; to &quot;a/t&quot;. &quot;r/g / e/ a/t&quot; --&gt; &quot;r/g / e/ a/t&quot; // random decision is to keep both substrings in the same order. The algorithm stops now, and the result string is &quot;rgeat&quot; which is s2. As one possible scenario led s1 to be scrambled to s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcde&quot;, s2 = &quot;caebd&quot; <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;a&quot;, s2 = &quot;a&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>s1.length == s2.length</code></li> <li><code>1 &lt;= s1.length &lt;= 30</code></li> <li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li> </ul>
String; Dynamic Programming
Go
func isScramble(s1 string, s2 string) bool { n := len(s1) f := make([][][]int, n) for i := range f { f[i] = make([][]int, n) for j := range f[i] { f[i][j] = make([]int, n+1) } } var dfs func(i, j, k int) bool dfs = func(i, j, k int) bool { if k == 1 { return s1[i] == s2[j] } if f[i][j][k] != 0 { return f[i][j][k] == 1 } f[i][j][k] = 2 for h := 1; h < k; h++ { if (dfs(i, j, h) && dfs(i+h, j+h, k-h)) || (dfs(i+h, j, k-h) && dfs(i, j+k-h, h)) { f[i][j][k] = 1 return true } } return false } return dfs(0, 0, n) }
87
Scramble String
Hard
<p>We can scramble a string s to get a string t using the following algorithm:</p> <ol> <li>If the length of the string is 1, stop.</li> <li>If the length of the string is &gt; 1, do the following: <ul> <li>Split the string into two non-empty substrings at a random index, i.e., if the string is <code>s</code>, divide it to <code>x</code> and <code>y</code> where <code>s = x + y</code>.</li> <li><strong>Randomly</strong>&nbsp;decide to swap the two substrings or to keep them in the same order. i.e., after this step, <code>s</code> may become <code>s = x + y</code> or <code>s = y + x</code>.</li> <li>Apply step 1 recursively on each of the two substrings <code>x</code> and <code>y</code>.</li> </ul> </li> </ol> <p>Given two strings <code>s1</code> and <code>s2</code> of <strong>the same length</strong>, return <code>true</code> if <code>s2</code> is a scrambled string of <code>s1</code>, otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;great&quot;, s2 = &quot;rgeat&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible scenario applied on s1 is: &quot;great&quot; --&gt; &quot;gr/eat&quot; // divide at random index. &quot;gr/eat&quot; --&gt; &quot;gr/eat&quot; // random decision is not to swap the two substrings and keep them in order. &quot;gr/eat&quot; --&gt; &quot;g/r / e/at&quot; // apply the same algorithm recursively on both substrings. divide at random index each of them. &quot;g/r / e/at&quot; --&gt; &quot;r/g / e/at&quot; // random decision was to swap the first substring and to keep the second substring in the same order. &quot;r/g / e/at&quot; --&gt; &quot;r/g / e/ a/t&quot; // again apply the algorithm recursively, divide &quot;at&quot; to &quot;a/t&quot;. &quot;r/g / e/ a/t&quot; --&gt; &quot;r/g / e/ a/t&quot; // random decision is to keep both substrings in the same order. The algorithm stops now, and the result string is &quot;rgeat&quot; which is s2. As one possible scenario led s1 to be scrambled to s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcde&quot;, s2 = &quot;caebd&quot; <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;a&quot;, s2 = &quot;a&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>s1.length == s2.length</code></li> <li><code>1 &lt;= s1.length &lt;= 30</code></li> <li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li> </ul>
String; Dynamic Programming
Java
class Solution { private Boolean[][][] f; private String s1; private String s2; public boolean isScramble(String s1, String s2) { int n = s1.length(); this.s1 = s1; this.s2 = s2; f = new Boolean[n][n][n + 1]; return dfs(0, 0, n); } private boolean dfs(int i, int j, int k) { if (f[i][j][k] != null) { return f[i][j][k]; } if (k == 1) { return s1.charAt(i) == s2.charAt(j); } for (int h = 1; h < k; ++h) { if (dfs(i, j, h) && dfs(i + h, j + h, k - h)) { return f[i][j][k] = true; } if (dfs(i + h, j, k - h) && dfs(i, j + k - h, h)) { return f[i][j][k] = true; } } return f[i][j][k] = false; } }
87
Scramble String
Hard
<p>We can scramble a string s to get a string t using the following algorithm:</p> <ol> <li>If the length of the string is 1, stop.</li> <li>If the length of the string is &gt; 1, do the following: <ul> <li>Split the string into two non-empty substrings at a random index, i.e., if the string is <code>s</code>, divide it to <code>x</code> and <code>y</code> where <code>s = x + y</code>.</li> <li><strong>Randomly</strong>&nbsp;decide to swap the two substrings or to keep them in the same order. i.e., after this step, <code>s</code> may become <code>s = x + y</code> or <code>s = y + x</code>.</li> <li>Apply step 1 recursively on each of the two substrings <code>x</code> and <code>y</code>.</li> </ul> </li> </ol> <p>Given two strings <code>s1</code> and <code>s2</code> of <strong>the same length</strong>, return <code>true</code> if <code>s2</code> is a scrambled string of <code>s1</code>, otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;great&quot;, s2 = &quot;rgeat&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible scenario applied on s1 is: &quot;great&quot; --&gt; &quot;gr/eat&quot; // divide at random index. &quot;gr/eat&quot; --&gt; &quot;gr/eat&quot; // random decision is not to swap the two substrings and keep them in order. &quot;gr/eat&quot; --&gt; &quot;g/r / e/at&quot; // apply the same algorithm recursively on both substrings. divide at random index each of them. &quot;g/r / e/at&quot; --&gt; &quot;r/g / e/at&quot; // random decision was to swap the first substring and to keep the second substring in the same order. &quot;r/g / e/at&quot; --&gt; &quot;r/g / e/ a/t&quot; // again apply the algorithm recursively, divide &quot;at&quot; to &quot;a/t&quot;. &quot;r/g / e/ a/t&quot; --&gt; &quot;r/g / e/ a/t&quot; // random decision is to keep both substrings in the same order. The algorithm stops now, and the result string is &quot;rgeat&quot; which is s2. As one possible scenario led s1 to be scrambled to s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcde&quot;, s2 = &quot;caebd&quot; <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;a&quot;, s2 = &quot;a&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>s1.length == s2.length</code></li> <li><code>1 &lt;= s1.length &lt;= 30</code></li> <li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li> </ul>
String; Dynamic Programming
Python
class Solution: def isScramble(self, s1: str, s2: str) -> bool: @cache def dfs(i: int, j: int, k: int) -> bool: if k == 1: return s1[i] == s2[j] for h in range(1, k): if dfs(i, j, h) and dfs(i + h, j + h, k - h): return True if dfs(i + h, j, k - h) and dfs(i, j + k - h, h): return True return False return dfs(0, 0, len(s1))
87
Scramble String
Hard
<p>We can scramble a string s to get a string t using the following algorithm:</p> <ol> <li>If the length of the string is 1, stop.</li> <li>If the length of the string is &gt; 1, do the following: <ul> <li>Split the string into two non-empty substrings at a random index, i.e., if the string is <code>s</code>, divide it to <code>x</code> and <code>y</code> where <code>s = x + y</code>.</li> <li><strong>Randomly</strong>&nbsp;decide to swap the two substrings or to keep them in the same order. i.e., after this step, <code>s</code> may become <code>s = x + y</code> or <code>s = y + x</code>.</li> <li>Apply step 1 recursively on each of the two substrings <code>x</code> and <code>y</code>.</li> </ul> </li> </ol> <p>Given two strings <code>s1</code> and <code>s2</code> of <strong>the same length</strong>, return <code>true</code> if <code>s2</code> is a scrambled string of <code>s1</code>, otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;great&quot;, s2 = &quot;rgeat&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible scenario applied on s1 is: &quot;great&quot; --&gt; &quot;gr/eat&quot; // divide at random index. &quot;gr/eat&quot; --&gt; &quot;gr/eat&quot; // random decision is not to swap the two substrings and keep them in order. &quot;gr/eat&quot; --&gt; &quot;g/r / e/at&quot; // apply the same algorithm recursively on both substrings. divide at random index each of them. &quot;g/r / e/at&quot; --&gt; &quot;r/g / e/at&quot; // random decision was to swap the first substring and to keep the second substring in the same order. &quot;r/g / e/at&quot; --&gt; &quot;r/g / e/ a/t&quot; // again apply the algorithm recursively, divide &quot;at&quot; to &quot;a/t&quot;. &quot;r/g / e/ a/t&quot; --&gt; &quot;r/g / e/ a/t&quot; // random decision is to keep both substrings in the same order. The algorithm stops now, and the result string is &quot;rgeat&quot; which is s2. As one possible scenario led s1 to be scrambled to s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcde&quot;, s2 = &quot;caebd&quot; <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;a&quot;, s2 = &quot;a&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>s1.length == s2.length</code></li> <li><code>1 &lt;= s1.length &lt;= 30</code></li> <li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li> </ul>
String; Dynamic Programming
TypeScript
function isScramble(s1: string, s2: string): boolean { const n = s1.length; const f = new Array(n) .fill(0) .map(() => new Array(n).fill(0).map(() => new Array(n + 1).fill(-1))); const dfs = (i: number, j: number, k: number): boolean => { if (f[i][j][k] !== -1) { return f[i][j][k] === 1; } if (k === 1) { return s1[i] === s2[j]; } for (let h = 1; h < k; ++h) { if (dfs(i, j, h) && dfs(i + h, j + h, k - h)) { return Boolean((f[i][j][k] = 1)); } if (dfs(i + h, j, k - h) && dfs(i, j + k - h, h)) { return Boolean((f[i][j][k] = 1)); } } return Boolean((f[i][j][k] = 0)); }; return dfs(0, 0, n); }
88
Merge Sorted Array
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in <strong>non-decreasing order</strong>, and two integers <code>m</code> and <code>n</code>, representing the number of elements in <code>nums1</code> and <code>nums2</code> respectively.</p> <p><strong>Merge</strong> <code>nums1</code> and <code>nums2</code> into a single array sorted in <strong>non-decreasing order</strong>.</p> <p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array </em><code>nums1</code>. To accommodate this, <code>nums1</code> has a length of <code>m + n</code>, where the first <code>m</code> elements denote the elements that should be merged, and the last <code>n</code> elements are set to <code>0</code> and should be ignored. <code>nums2</code> has a length of <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 <strong>Output:</strong> [1,2,2,3,5,6] <strong>Explanation:</strong> The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [<u>1</u>,<u>2</u>,2,<u>3</u>,5,6] with the underlined elements coming from nums1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1], m = 1, nums2 = [], n = 0 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [1] and []. The result of the merge is [1]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], m = 0, nums2 = [1], n = 1 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m + n</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m, n &lt;= 200</code></li> <li><code>1 &lt;= m + n &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[j] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up: </strong>Can you come up with an algorithm that runs in <code>O(m + n)</code> time?</p>
Array; Two Pointers; Sorting
C++
class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { for (int i = m - 1, j = n - 1, k = m + n - 1; ~j; --k) { nums1[k] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; } } };
88
Merge Sorted Array
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in <strong>non-decreasing order</strong>, and two integers <code>m</code> and <code>n</code>, representing the number of elements in <code>nums1</code> and <code>nums2</code> respectively.</p> <p><strong>Merge</strong> <code>nums1</code> and <code>nums2</code> into a single array sorted in <strong>non-decreasing order</strong>.</p> <p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array </em><code>nums1</code>. To accommodate this, <code>nums1</code> has a length of <code>m + n</code>, where the first <code>m</code> elements denote the elements that should be merged, and the last <code>n</code> elements are set to <code>0</code> and should be ignored. <code>nums2</code> has a length of <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 <strong>Output:</strong> [1,2,2,3,5,6] <strong>Explanation:</strong> The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [<u>1</u>,<u>2</u>,2,<u>3</u>,5,6] with the underlined elements coming from nums1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1], m = 1, nums2 = [], n = 0 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [1] and []. The result of the merge is [1]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], m = 0, nums2 = [1], n = 1 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m + n</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m, n &lt;= 200</code></li> <li><code>1 &lt;= m + n &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[j] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up: </strong>Can you come up with an algorithm that runs in <code>O(m + n)</code> time?</p>
Array; Two Pointers; Sorting
Go
func merge(nums1 []int, m int, nums2 []int, n int) { for i, j, k := m-1, n-1, m+n-1; j >= 0; k-- { if i >= 0 && nums1[i] > nums2[j] { nums1[k] = nums1[i] i-- } else { nums1[k] = nums2[j] j-- } } }
88
Merge Sorted Array
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in <strong>non-decreasing order</strong>, and two integers <code>m</code> and <code>n</code>, representing the number of elements in <code>nums1</code> and <code>nums2</code> respectively.</p> <p><strong>Merge</strong> <code>nums1</code> and <code>nums2</code> into a single array sorted in <strong>non-decreasing order</strong>.</p> <p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array </em><code>nums1</code>. To accommodate this, <code>nums1</code> has a length of <code>m + n</code>, where the first <code>m</code> elements denote the elements that should be merged, and the last <code>n</code> elements are set to <code>0</code> and should be ignored. <code>nums2</code> has a length of <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 <strong>Output:</strong> [1,2,2,3,5,6] <strong>Explanation:</strong> The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [<u>1</u>,<u>2</u>,2,<u>3</u>,5,6] with the underlined elements coming from nums1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1], m = 1, nums2 = [], n = 0 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [1] and []. The result of the merge is [1]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], m = 0, nums2 = [1], n = 1 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m + n</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m, n &lt;= 200</code></li> <li><code>1 &lt;= m + n &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[j] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up: </strong>Can you come up with an algorithm that runs in <code>O(m + n)</code> time?</p>
Array; Two Pointers; Sorting
Java
class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { for (int i = m - 1, j = n - 1, k = m + n - 1; j >= 0; --k) { nums1[k] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; } } }
88
Merge Sorted Array
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in <strong>non-decreasing order</strong>, and two integers <code>m</code> and <code>n</code>, representing the number of elements in <code>nums1</code> and <code>nums2</code> respectively.</p> <p><strong>Merge</strong> <code>nums1</code> and <code>nums2</code> into a single array sorted in <strong>non-decreasing order</strong>.</p> <p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array </em><code>nums1</code>. To accommodate this, <code>nums1</code> has a length of <code>m + n</code>, where the first <code>m</code> elements denote the elements that should be merged, and the last <code>n</code> elements are set to <code>0</code> and should be ignored. <code>nums2</code> has a length of <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 <strong>Output:</strong> [1,2,2,3,5,6] <strong>Explanation:</strong> The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [<u>1</u>,<u>2</u>,2,<u>3</u>,5,6] with the underlined elements coming from nums1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1], m = 1, nums2 = [], n = 0 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [1] and []. The result of the merge is [1]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], m = 0, nums2 = [1], n = 1 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m + n</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m, n &lt;= 200</code></li> <li><code>1 &lt;= m + n &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[j] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up: </strong>Can you come up with an algorithm that runs in <code>O(m + n)</code> time?</p>
Array; Two Pointers; Sorting
JavaScript
/** * @param {number[]} nums1 * @param {number} m * @param {number[]} nums2 * @param {number} n * @return {void} Do not return anything, modify nums1 in-place instead. */ var merge = function (nums1, m, nums2, n) { for (let i = m - 1, j = n - 1, k = m + n - 1; j >= 0; --k) { nums1[k] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; } };
88
Merge Sorted Array
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in <strong>non-decreasing order</strong>, and two integers <code>m</code> and <code>n</code>, representing the number of elements in <code>nums1</code> and <code>nums2</code> respectively.</p> <p><strong>Merge</strong> <code>nums1</code> and <code>nums2</code> into a single array sorted in <strong>non-decreasing order</strong>.</p> <p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array </em><code>nums1</code>. To accommodate this, <code>nums1</code> has a length of <code>m + n</code>, where the first <code>m</code> elements denote the elements that should be merged, and the last <code>n</code> elements are set to <code>0</code> and should be ignored. <code>nums2</code> has a length of <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 <strong>Output:</strong> [1,2,2,3,5,6] <strong>Explanation:</strong> The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [<u>1</u>,<u>2</u>,2,<u>3</u>,5,6] with the underlined elements coming from nums1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1], m = 1, nums2 = [], n = 0 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [1] and []. The result of the merge is [1]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], m = 0, nums2 = [1], n = 1 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m + n</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m, n &lt;= 200</code></li> <li><code>1 &lt;= m + n &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[j] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up: </strong>Can you come up with an algorithm that runs in <code>O(m + n)</code> time?</p>
Array; Two Pointers; Sorting
PHP
class Solution { /** * @param Integer[] $nums1 * @param Integer $m * @param Integer[] $nums2 * @param Integer $n * @return NULL */ function merge(&$nums1, $m, $nums2, $n) { while (count($nums1) > $m) { array_pop($nums1); } for ($i = 0; $i < $n; $i++) { array_push($nums1, $nums2[$i]); } asort($nums1); } }
88
Merge Sorted Array
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in <strong>non-decreasing order</strong>, and two integers <code>m</code> and <code>n</code>, representing the number of elements in <code>nums1</code> and <code>nums2</code> respectively.</p> <p><strong>Merge</strong> <code>nums1</code> and <code>nums2</code> into a single array sorted in <strong>non-decreasing order</strong>.</p> <p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array </em><code>nums1</code>. To accommodate this, <code>nums1</code> has a length of <code>m + n</code>, where the first <code>m</code> elements denote the elements that should be merged, and the last <code>n</code> elements are set to <code>0</code> and should be ignored. <code>nums2</code> has a length of <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 <strong>Output:</strong> [1,2,2,3,5,6] <strong>Explanation:</strong> The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [<u>1</u>,<u>2</u>,2,<u>3</u>,5,6] with the underlined elements coming from nums1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1], m = 1, nums2 = [], n = 0 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [1] and []. The result of the merge is [1]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], m = 0, nums2 = [1], n = 1 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m + n</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m, n &lt;= 200</code></li> <li><code>1 &lt;= m + n &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[j] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up: </strong>Can you come up with an algorithm that runs in <code>O(m + n)</code> time?</p>
Array; Two Pointers; Sorting
Python
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: k = m + n - 1 i, j = m - 1, n - 1 while j >= 0: if i >= 0 and nums1[i] > nums2[j]: nums1[k] = nums1[i] i -= 1 else: nums1[k] = nums2[j] j -= 1 k -= 1
88
Merge Sorted Array
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in <strong>non-decreasing order</strong>, and two integers <code>m</code> and <code>n</code>, representing the number of elements in <code>nums1</code> and <code>nums2</code> respectively.</p> <p><strong>Merge</strong> <code>nums1</code> and <code>nums2</code> into a single array sorted in <strong>non-decreasing order</strong>.</p> <p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array </em><code>nums1</code>. To accommodate this, <code>nums1</code> has a length of <code>m + n</code>, where the first <code>m</code> elements denote the elements that should be merged, and the last <code>n</code> elements are set to <code>0</code> and should be ignored. <code>nums2</code> has a length of <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 <strong>Output:</strong> [1,2,2,3,5,6] <strong>Explanation:</strong> The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [<u>1</u>,<u>2</u>,2,<u>3</u>,5,6] with the underlined elements coming from nums1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1], m = 1, nums2 = [], n = 0 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [1] and []. The result of the merge is [1]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], m = 0, nums2 = [1], n = 1 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m + n</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m, n &lt;= 200</code></li> <li><code>1 &lt;= m + n &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[j] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up: </strong>Can you come up with an algorithm that runs in <code>O(m + n)</code> time?</p>
Array; Two Pointers; Sorting
Rust
impl Solution { pub fn merge(nums1: &mut Vec<i32>, m: i32, nums2: &mut Vec<i32>, n: i32) { let mut k = (m + n - 1) as usize; let mut i = (m - 1) as isize; let mut j = (n - 1) as isize; while j >= 0 { if i >= 0 && nums1[i as usize] > nums2[j as usize] { nums1[k] = nums1[i as usize]; i -= 1; } else { nums1[k] = nums2[j as usize]; j -= 1; } k -= 1; } } }
88
Merge Sorted Array
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in <strong>non-decreasing order</strong>, and two integers <code>m</code> and <code>n</code>, representing the number of elements in <code>nums1</code> and <code>nums2</code> respectively.</p> <p><strong>Merge</strong> <code>nums1</code> and <code>nums2</code> into a single array sorted in <strong>non-decreasing order</strong>.</p> <p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array </em><code>nums1</code>. To accommodate this, <code>nums1</code> has a length of <code>m + n</code>, where the first <code>m</code> elements denote the elements that should be merged, and the last <code>n</code> elements are set to <code>0</code> and should be ignored. <code>nums2</code> has a length of <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 <strong>Output:</strong> [1,2,2,3,5,6] <strong>Explanation:</strong> The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [<u>1</u>,<u>2</u>,2,<u>3</u>,5,6] with the underlined elements coming from nums1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1], m = 1, nums2 = [], n = 0 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [1] and []. The result of the merge is [1]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], m = 0, nums2 = [1], n = 1 <strong>Output:</strong> [1] <strong>Explanation:</strong> The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m + n</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m, n &lt;= 200</code></li> <li><code>1 &lt;= m + n &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[j] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up: </strong>Can you come up with an algorithm that runs in <code>O(m + n)</code> time?</p>
Array; Two Pointers; Sorting
TypeScript
/** Do not return anything, modify nums1 in-place instead. */ function merge(nums1: number[], m: number, nums2: number[], n: number): void { for (let i = m - 1, j = n - 1, k = m + n - 1; j >= 0; --k) { nums1[k] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; } }
89
Gray Code
Medium
<p>An <strong>n-bit gray code sequence</strong> is a sequence of <code>2<sup>n</sup></code> integers where:</p> <ul> <li>Every integer is in the <strong>inclusive</strong> range <code>[0, 2<sup>n</sup> - 1]</code>,</li> <li>The first integer is <code>0</code>,</li> <li>An integer appears <strong>no more than once</strong> in the sequence,</li> <li>The binary representation of every pair of <strong>adjacent</strong> integers differs by <strong>exactly one bit</strong>, and</li> <li>The binary representation of the <strong>first</strong> and <strong>last</strong> integers differs by <strong>exactly one bit</strong>.</li> </ul> <p>Given an integer <code>n</code>, return <em>any valid <strong>n-bit gray code sequence</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [0,1,3,2] <strong>Explanation:</strong> The binary representation of [0,1,3,2] is [00,01,11,10]. - 0<u>0</u> and 0<u>1</u> differ by one bit - <u>0</u>1 and <u>1</u>1 differ by one bit - 1<u>1</u> and 1<u>0</u> differ by one bit - <u>1</u>0 and <u>0</u>0 differ by one bit [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01]. - <u>0</u>0 and <u>1</u>0 differ by one bit - 1<u>0</u> and 1<u>1</u> differ by one bit - <u>1</u>1 and <u>0</u>1 differ by one bit - 0<u>1</u> and 0<u>0</u> differ by one bit </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 16</code></li> </ul>
Bit Manipulation; Math; Backtracking
C++
class Solution { public: vector<int> grayCode(int n) { vector<int> ans; for (int i = 0; i < 1 << n; ++i) { ans.push_back(i ^ (i >> 1)); } return ans; } };
89
Gray Code
Medium
<p>An <strong>n-bit gray code sequence</strong> is a sequence of <code>2<sup>n</sup></code> integers where:</p> <ul> <li>Every integer is in the <strong>inclusive</strong> range <code>[0, 2<sup>n</sup> - 1]</code>,</li> <li>The first integer is <code>0</code>,</li> <li>An integer appears <strong>no more than once</strong> in the sequence,</li> <li>The binary representation of every pair of <strong>adjacent</strong> integers differs by <strong>exactly one bit</strong>, and</li> <li>The binary representation of the <strong>first</strong> and <strong>last</strong> integers differs by <strong>exactly one bit</strong>.</li> </ul> <p>Given an integer <code>n</code>, return <em>any valid <strong>n-bit gray code sequence</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [0,1,3,2] <strong>Explanation:</strong> The binary representation of [0,1,3,2] is [00,01,11,10]. - 0<u>0</u> and 0<u>1</u> differ by one bit - <u>0</u>1 and <u>1</u>1 differ by one bit - 1<u>1</u> and 1<u>0</u> differ by one bit - <u>1</u>0 and <u>0</u>0 differ by one bit [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01]. - <u>0</u>0 and <u>1</u>0 differ by one bit - 1<u>0</u> and 1<u>1</u> differ by one bit - <u>1</u>1 and <u>0</u>1 differ by one bit - 0<u>1</u> and 0<u>0</u> differ by one bit </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 16</code></li> </ul>
Bit Manipulation; Math; Backtracking
Go
func grayCode(n int) (ans []int) { for i := 0; i < 1<<n; i++ { ans = append(ans, i^(i>>1)) } return }
89
Gray Code
Medium
<p>An <strong>n-bit gray code sequence</strong> is a sequence of <code>2<sup>n</sup></code> integers where:</p> <ul> <li>Every integer is in the <strong>inclusive</strong> range <code>[0, 2<sup>n</sup> - 1]</code>,</li> <li>The first integer is <code>0</code>,</li> <li>An integer appears <strong>no more than once</strong> in the sequence,</li> <li>The binary representation of every pair of <strong>adjacent</strong> integers differs by <strong>exactly one bit</strong>, and</li> <li>The binary representation of the <strong>first</strong> and <strong>last</strong> integers differs by <strong>exactly one bit</strong>.</li> </ul> <p>Given an integer <code>n</code>, return <em>any valid <strong>n-bit gray code sequence</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [0,1,3,2] <strong>Explanation:</strong> The binary representation of [0,1,3,2] is [00,01,11,10]. - 0<u>0</u> and 0<u>1</u> differ by one bit - <u>0</u>1 and <u>1</u>1 differ by one bit - 1<u>1</u> and 1<u>0</u> differ by one bit - <u>1</u>0 and <u>0</u>0 differ by one bit [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01]. - <u>0</u>0 and <u>1</u>0 differ by one bit - 1<u>0</u> and 1<u>1</u> differ by one bit - <u>1</u>1 and <u>0</u>1 differ by one bit - 0<u>1</u> and 0<u>0</u> differ by one bit </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 16</code></li> </ul>
Bit Manipulation; Math; Backtracking
Java
class Solution { public List<Integer> grayCode(int n) { List<Integer> ans = new ArrayList<>(); for (int i = 0; i < 1 << n; ++i) { ans.add(i ^ (i >> 1)); } return ans; } }
89
Gray Code
Medium
<p>An <strong>n-bit gray code sequence</strong> is a sequence of <code>2<sup>n</sup></code> integers where:</p> <ul> <li>Every integer is in the <strong>inclusive</strong> range <code>[0, 2<sup>n</sup> - 1]</code>,</li> <li>The first integer is <code>0</code>,</li> <li>An integer appears <strong>no more than once</strong> in the sequence,</li> <li>The binary representation of every pair of <strong>adjacent</strong> integers differs by <strong>exactly one bit</strong>, and</li> <li>The binary representation of the <strong>first</strong> and <strong>last</strong> integers differs by <strong>exactly one bit</strong>.</li> </ul> <p>Given an integer <code>n</code>, return <em>any valid <strong>n-bit gray code sequence</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [0,1,3,2] <strong>Explanation:</strong> The binary representation of [0,1,3,2] is [00,01,11,10]. - 0<u>0</u> and 0<u>1</u> differ by one bit - <u>0</u>1 and <u>1</u>1 differ by one bit - 1<u>1</u> and 1<u>0</u> differ by one bit - <u>1</u>0 and <u>0</u>0 differ by one bit [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01]. - <u>0</u>0 and <u>1</u>0 differ by one bit - 1<u>0</u> and 1<u>1</u> differ by one bit - <u>1</u>1 and <u>0</u>1 differ by one bit - 0<u>1</u> and 0<u>0</u> differ by one bit </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 16</code></li> </ul>
Bit Manipulation; Math; Backtracking
JavaScript
/** * @param {number} n * @return {number[]} */ var grayCode = function (n) { const ans = []; for (let i = 0; i < 1 << n; ++i) { ans.push(i ^ (i >> 1)); } return ans; };
89
Gray Code
Medium
<p>An <strong>n-bit gray code sequence</strong> is a sequence of <code>2<sup>n</sup></code> integers where:</p> <ul> <li>Every integer is in the <strong>inclusive</strong> range <code>[0, 2<sup>n</sup> - 1]</code>,</li> <li>The first integer is <code>0</code>,</li> <li>An integer appears <strong>no more than once</strong> in the sequence,</li> <li>The binary representation of every pair of <strong>adjacent</strong> integers differs by <strong>exactly one bit</strong>, and</li> <li>The binary representation of the <strong>first</strong> and <strong>last</strong> integers differs by <strong>exactly one bit</strong>.</li> </ul> <p>Given an integer <code>n</code>, return <em>any valid <strong>n-bit gray code sequence</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [0,1,3,2] <strong>Explanation:</strong> The binary representation of [0,1,3,2] is [00,01,11,10]. - 0<u>0</u> and 0<u>1</u> differ by one bit - <u>0</u>1 and <u>1</u>1 differ by one bit - 1<u>1</u> and 1<u>0</u> differ by one bit - <u>1</u>0 and <u>0</u>0 differ by one bit [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01]. - <u>0</u>0 and <u>1</u>0 differ by one bit - 1<u>0</u> and 1<u>1</u> differ by one bit - <u>1</u>1 and <u>0</u>1 differ by one bit - 0<u>1</u> and 0<u>0</u> differ by one bit </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 16</code></li> </ul>
Bit Manipulation; Math; Backtracking
Python
class Solution: def grayCode(self, n: int) -> List[int]: return [i ^ (i >> 1) for i in range(1 << n)]
90
Subsets II
Medium
<p>Given an integer array <code>nums</code> that may contain duplicates, return <em>all possible</em> <span data-keyword="subset"><em>subsets</em></span><em> (the power set)</em>.</p> <p>The solution set <strong>must not</strong> contain duplicate subsets. Return the solution in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2] <strong>Output:</strong> [[],[1],[1,2],[1,2,2],[2],[2,2]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [[],[0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Bit Manipulation; Array; Backtracking
C++
class Solution { public: vector<vector<int>> subsetsWithDup(vector<int>& nums) { ranges::sort(nums); vector<vector<int>> ans; vector<int> t; int n = nums.size(); auto dfs = [&](this auto&& dfs, int i) { if (i >= n) { ans.push_back(t); return; } t.push_back(nums[i]); dfs(i + 1); t.pop_back(); while (i + 1 < n && nums[i + 1] == nums[i]) { ++i; } dfs(i + 1); }; dfs(0); return ans; } };
90
Subsets II
Medium
<p>Given an integer array <code>nums</code> that may contain duplicates, return <em>all possible</em> <span data-keyword="subset"><em>subsets</em></span><em> (the power set)</em>.</p> <p>The solution set <strong>must not</strong> contain duplicate subsets. Return the solution in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2] <strong>Output:</strong> [[],[1],[1,2],[1,2,2],[2],[2,2]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [[],[0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Bit Manipulation; Array; Backtracking
C#
public class Solution { private IList<IList<int>> ans = new List<IList<int>>(); private IList<int> t = new List<int>(); private int[] nums; public IList<IList<int>> SubsetsWithDup(int[] nums) { Array.Sort(nums); this.nums = nums; Dfs(0); return ans; } private void Dfs(int i) { if (i >= nums.Length) { ans.Add(new List<int>(t)); return; } t.Add(nums[i]); Dfs(i + 1); t.RemoveAt(t.Count - 1); while (i + 1 < nums.Length && nums[i + 1] == nums[i]) { ++i; } Dfs(i + 1); } }
90
Subsets II
Medium
<p>Given an integer array <code>nums</code> that may contain duplicates, return <em>all possible</em> <span data-keyword="subset"><em>subsets</em></span><em> (the power set)</em>.</p> <p>The solution set <strong>must not</strong> contain duplicate subsets. Return the solution in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2] <strong>Output:</strong> [[],[1],[1,2],[1,2,2],[2],[2,2]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [[],[0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Bit Manipulation; Array; Backtracking
Go
func subsetsWithDup(nums []int) (ans [][]int) { slices.Sort(nums) n := len(nums) t := []int{} var dfs func(int) dfs = func(i int) { if i >= n { ans = append(ans, slices.Clone(t)) return } t = append(t, nums[i]) dfs(i + 1) t = t[:len(t)-1] for i+1 < n && nums[i+1] == nums[i] { i++ } dfs(i + 1) } dfs(0) return }
90
Subsets II
Medium
<p>Given an integer array <code>nums</code> that may contain duplicates, return <em>all possible</em> <span data-keyword="subset"><em>subsets</em></span><em> (the power set)</em>.</p> <p>The solution set <strong>must not</strong> contain duplicate subsets. Return the solution in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2] <strong>Output:</strong> [[],[1],[1,2],[1,2,2],[2],[2,2]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [[],[0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Bit Manipulation; Array; Backtracking
Java
class Solution { private List<List<Integer>> ans = new ArrayList<>(); private List<Integer> t = new ArrayList<>(); private int[] nums; public List<List<Integer>> subsetsWithDup(int[] nums) { Arrays.sort(nums); this.nums = nums; dfs(0); return ans; } private void dfs(int i) { if (i >= nums.length) { ans.add(new ArrayList<>(t)); return; } t.add(nums[i]); dfs(i + 1); int x = t.remove(t.size() - 1); while (i + 1 < nums.length && nums[i + 1] == x) { ++i; } dfs(i + 1); } }
90
Subsets II
Medium
<p>Given an integer array <code>nums</code> that may contain duplicates, return <em>all possible</em> <span data-keyword="subset"><em>subsets</em></span><em> (the power set)</em>.</p> <p>The solution set <strong>must not</strong> contain duplicate subsets. Return the solution in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2] <strong>Output:</strong> [[],[1],[1,2],[1,2,2],[2],[2,2]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [[],[0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Bit Manipulation; Array; Backtracking
JavaScript
/** * @param {number[]} nums * @return {number[][]} */ var subsetsWithDup = function (nums) { nums.sort((a, b) => a - b); const n = nums.length; const t = []; const ans = []; const dfs = i => { if (i >= n) { ans.push([...t]); return; } t.push(nums[i]); dfs(i + 1); t.pop(); while (i + 1 < n && nums[i] === nums[i + 1]) { i++; } dfs(i + 1); }; dfs(0); return ans; };
90
Subsets II
Medium
<p>Given an integer array <code>nums</code> that may contain duplicates, return <em>all possible</em> <span data-keyword="subset"><em>subsets</em></span><em> (the power set)</em>.</p> <p>The solution set <strong>must not</strong> contain duplicate subsets. Return the solution in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2] <strong>Output:</strong> [[],[1],[1,2],[1,2,2],[2],[2,2]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [[],[0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Bit Manipulation; Array; Backtracking
Python
class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: def dfs(i: int): if i == len(nums): ans.append(t[:]) return t.append(nums[i]) dfs(i + 1) x = t.pop() while i + 1 < len(nums) and nums[i + 1] == x: i += 1 dfs(i + 1) nums.sort() ans = [] t = [] dfs(0) return ans
90
Subsets II
Medium
<p>Given an integer array <code>nums</code> that may contain duplicates, return <em>all possible</em> <span data-keyword="subset"><em>subsets</em></span><em> (the power set)</em>.</p> <p>The solution set <strong>must not</strong> contain duplicate subsets. Return the solution in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2] <strong>Output:</strong> [[],[1],[1,2],[1,2,2],[2],[2,2]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [[],[0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Bit Manipulation; Array; Backtracking
Rust
impl Solution { pub fn subsets_with_dup(nums: Vec<i32>) -> Vec<Vec<i32>> { let mut nums = nums; nums.sort(); let mut ans = Vec::new(); let mut t = Vec::new(); fn dfs(i: usize, nums: &Vec<i32>, t: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) { if i >= nums.len() { ans.push(t.clone()); return; } t.push(nums[i]); dfs(i + 1, nums, t, ans); t.pop(); let mut i = i; while i + 1 < nums.len() && nums[i + 1] == nums[i] { i += 1; } dfs(i + 1, nums, t, ans); } dfs(0, &nums, &mut t, &mut ans); ans } }
90
Subsets II
Medium
<p>Given an integer array <code>nums</code> that may contain duplicates, return <em>all possible</em> <span data-keyword="subset"><em>subsets</em></span><em> (the power set)</em>.</p> <p>The solution set <strong>must not</strong> contain duplicate subsets. Return the solution in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [1,2,2] <strong>Output:</strong> [[],[1],[1,2],[1,2,2],[2],[2,2]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [[],[0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> </ul>
Bit Manipulation; Array; Backtracking
TypeScript
function subsetsWithDup(nums: number[]): number[][] { nums.sort((a, b) => a - b); const n = nums.length; const t: number[] = []; const ans: number[][] = []; const dfs = (i: number): void => { if (i >= n) { ans.push([...t]); return; } t.push(nums[i]); dfs(i + 1); t.pop(); while (i + 1 < n && nums[i] === nums[i + 1]) { i++; } dfs(i + 1); }; dfs(0); return ans; }
91
Decode Ways
Medium
<p>You have intercepted a secret message encoded as a string of numbers. The message is <strong>decoded</strong> via the following mapping:</p> <p><code>&quot;1&quot; -&gt; &#39;A&#39;<br /> &quot;2&quot; -&gt; &#39;B&#39;<br /> ...<br /> &quot;25&quot; -&gt; &#39;Y&#39;<br /> &quot;26&quot; -&gt; &#39;Z&#39;</code></p> <p>However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes (<code>&quot;2&quot;</code> and <code>&quot;5&quot;</code> vs <code>&quot;25&quot;</code>).</p> <p>For example, <code>&quot;11106&quot;</code> can be decoded into:</p> <ul> <li><code>&quot;AAJF&quot;</code> with the grouping <code>(1, 1, 10, 6)</code></li> <li><code>&quot;KJF&quot;</code> with the grouping <code>(11, 10, 6)</code></li> <li>The grouping <code>(1, 11, 06)</code> is invalid because <code>&quot;06&quot;</code> is not a valid code (only <code>&quot;6&quot;</code> is valid).</li> </ul> <p>Note: there may be strings that are impossible to decode.<br /> <br /> Given a string s containing only digits, return the <strong>number of ways</strong> to <strong>decode</strong> it. If the entire string cannot be decoded in any valid way, return <code>0</code>.</p> <p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;12&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>&quot;12&quot; could be decoded as &quot;AB&quot; (1 2) or &quot;L&quot; (12).</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;226&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>&quot;226&quot; could be decoded as &quot;BZ&quot; (2 26), &quot;VF&quot; (22 6), or &quot;BBF&quot; (2 2 6).</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;06&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>&quot;06&quot; cannot be mapped to &quot;F&quot; because of the leading zero (&quot;6&quot; is different from &quot;06&quot;). In this case, the string is not a valid encoding, so return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only digits and may contain leading zero(s).</li> </ul>
String; Dynamic Programming
C++
class Solution { public: int numDecodings(string s) { int n = s.size(); int f[n + 1]; memset(f, 0, sizeof(f)); f[0] = 1; for (int i = 1; i <= n; ++i) { if (s[i - 1] != '0') { f[i] = f[i - 1]; } if (i > 1 && (s[i - 2] == '1' || s[i - 2] == '2' && s[i - 1] <= '6')) { f[i] += f[i - 2]; } } return f[n]; } };
91
Decode Ways
Medium
<p>You have intercepted a secret message encoded as a string of numbers. The message is <strong>decoded</strong> via the following mapping:</p> <p><code>&quot;1&quot; -&gt; &#39;A&#39;<br /> &quot;2&quot; -&gt; &#39;B&#39;<br /> ...<br /> &quot;25&quot; -&gt; &#39;Y&#39;<br /> &quot;26&quot; -&gt; &#39;Z&#39;</code></p> <p>However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes (<code>&quot;2&quot;</code> and <code>&quot;5&quot;</code> vs <code>&quot;25&quot;</code>).</p> <p>For example, <code>&quot;11106&quot;</code> can be decoded into:</p> <ul> <li><code>&quot;AAJF&quot;</code> with the grouping <code>(1, 1, 10, 6)</code></li> <li><code>&quot;KJF&quot;</code> with the grouping <code>(11, 10, 6)</code></li> <li>The grouping <code>(1, 11, 06)</code> is invalid because <code>&quot;06&quot;</code> is not a valid code (only <code>&quot;6&quot;</code> is valid).</li> </ul> <p>Note: there may be strings that are impossible to decode.<br /> <br /> Given a string s containing only digits, return the <strong>number of ways</strong> to <strong>decode</strong> it. If the entire string cannot be decoded in any valid way, return <code>0</code>.</p> <p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;12&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>&quot;12&quot; could be decoded as &quot;AB&quot; (1 2) or &quot;L&quot; (12).</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;226&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>&quot;226&quot; could be decoded as &quot;BZ&quot; (2 26), &quot;VF&quot; (22 6), or &quot;BBF&quot; (2 2 6).</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;06&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>&quot;06&quot; cannot be mapped to &quot;F&quot; because of the leading zero (&quot;6&quot; is different from &quot;06&quot;). In this case, the string is not a valid encoding, so return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only digits and may contain leading zero(s).</li> </ul>
String; Dynamic Programming
C#
public class Solution { public int NumDecodings(string s) { int n = s.Length; int[] f = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; ++i) { if (s[i - 1] != '0') { f[i] = f[i - 1]; } if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) { f[i] += f[i - 2]; } } return f[n]; } }
91
Decode Ways
Medium
<p>You have intercepted a secret message encoded as a string of numbers. The message is <strong>decoded</strong> via the following mapping:</p> <p><code>&quot;1&quot; -&gt; &#39;A&#39;<br /> &quot;2&quot; -&gt; &#39;B&#39;<br /> ...<br /> &quot;25&quot; -&gt; &#39;Y&#39;<br /> &quot;26&quot; -&gt; &#39;Z&#39;</code></p> <p>However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes (<code>&quot;2&quot;</code> and <code>&quot;5&quot;</code> vs <code>&quot;25&quot;</code>).</p> <p>For example, <code>&quot;11106&quot;</code> can be decoded into:</p> <ul> <li><code>&quot;AAJF&quot;</code> with the grouping <code>(1, 1, 10, 6)</code></li> <li><code>&quot;KJF&quot;</code> with the grouping <code>(11, 10, 6)</code></li> <li>The grouping <code>(1, 11, 06)</code> is invalid because <code>&quot;06&quot;</code> is not a valid code (only <code>&quot;6&quot;</code> is valid).</li> </ul> <p>Note: there may be strings that are impossible to decode.<br /> <br /> Given a string s containing only digits, return the <strong>number of ways</strong> to <strong>decode</strong> it. If the entire string cannot be decoded in any valid way, return <code>0</code>.</p> <p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;12&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>&quot;12&quot; could be decoded as &quot;AB&quot; (1 2) or &quot;L&quot; (12).</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;226&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>&quot;226&quot; could be decoded as &quot;BZ&quot; (2 26), &quot;VF&quot; (22 6), or &quot;BBF&quot; (2 2 6).</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;06&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>&quot;06&quot; cannot be mapped to &quot;F&quot; because of the leading zero (&quot;6&quot; is different from &quot;06&quot;). In this case, the string is not a valid encoding, so return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only digits and may contain leading zero(s).</li> </ul>
String; Dynamic Programming
Go
func numDecodings(s string) int { n := len(s) f := make([]int, n+1) f[0] = 1 for i := 1; i <= n; i++ { if s[i-1] != '0' { f[i] = f[i-1] } if i > 1 && (s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <= '6')) { f[i] += f[i-2] } } return f[n] }
91
Decode Ways
Medium
<p>You have intercepted a secret message encoded as a string of numbers. The message is <strong>decoded</strong> via the following mapping:</p> <p><code>&quot;1&quot; -&gt; &#39;A&#39;<br /> &quot;2&quot; -&gt; &#39;B&#39;<br /> ...<br /> &quot;25&quot; -&gt; &#39;Y&#39;<br /> &quot;26&quot; -&gt; &#39;Z&#39;</code></p> <p>However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes (<code>&quot;2&quot;</code> and <code>&quot;5&quot;</code> vs <code>&quot;25&quot;</code>).</p> <p>For example, <code>&quot;11106&quot;</code> can be decoded into:</p> <ul> <li><code>&quot;AAJF&quot;</code> with the grouping <code>(1, 1, 10, 6)</code></li> <li><code>&quot;KJF&quot;</code> with the grouping <code>(11, 10, 6)</code></li> <li>The grouping <code>(1, 11, 06)</code> is invalid because <code>&quot;06&quot;</code> is not a valid code (only <code>&quot;6&quot;</code> is valid).</li> </ul> <p>Note: there may be strings that are impossible to decode.<br /> <br /> Given a string s containing only digits, return the <strong>number of ways</strong> to <strong>decode</strong> it. If the entire string cannot be decoded in any valid way, return <code>0</code>.</p> <p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;12&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>&quot;12&quot; could be decoded as &quot;AB&quot; (1 2) or &quot;L&quot; (12).</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;226&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>&quot;226&quot; could be decoded as &quot;BZ&quot; (2 26), &quot;VF&quot; (22 6), or &quot;BBF&quot; (2 2 6).</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;06&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>&quot;06&quot; cannot be mapped to &quot;F&quot; because of the leading zero (&quot;6&quot; is different from &quot;06&quot;). In this case, the string is not a valid encoding, so return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only digits and may contain leading zero(s).</li> </ul>
String; Dynamic Programming
Java
class Solution { public int numDecodings(String s) { int n = s.length(); int[] f = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; ++i) { if (s.charAt(i - 1) != '0') { f[i] = f[i - 1]; } if (i > 1 && s.charAt(i - 2) != '0' && Integer.valueOf(s.substring(i - 2, i)) <= 26) { f[i] += f[i - 2]; } } return f[n]; } }
91
Decode Ways
Medium
<p>You have intercepted a secret message encoded as a string of numbers. The message is <strong>decoded</strong> via the following mapping:</p> <p><code>&quot;1&quot; -&gt; &#39;A&#39;<br /> &quot;2&quot; -&gt; &#39;B&#39;<br /> ...<br /> &quot;25&quot; -&gt; &#39;Y&#39;<br /> &quot;26&quot; -&gt; &#39;Z&#39;</code></p> <p>However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes (<code>&quot;2&quot;</code> and <code>&quot;5&quot;</code> vs <code>&quot;25&quot;</code>).</p> <p>For example, <code>&quot;11106&quot;</code> can be decoded into:</p> <ul> <li><code>&quot;AAJF&quot;</code> with the grouping <code>(1, 1, 10, 6)</code></li> <li><code>&quot;KJF&quot;</code> with the grouping <code>(11, 10, 6)</code></li> <li>The grouping <code>(1, 11, 06)</code> is invalid because <code>&quot;06&quot;</code> is not a valid code (only <code>&quot;6&quot;</code> is valid).</li> </ul> <p>Note: there may be strings that are impossible to decode.<br /> <br /> Given a string s containing only digits, return the <strong>number of ways</strong> to <strong>decode</strong> it. If the entire string cannot be decoded in any valid way, return <code>0</code>.</p> <p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;12&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>&quot;12&quot; could be decoded as &quot;AB&quot; (1 2) or &quot;L&quot; (12).</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;226&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>&quot;226&quot; could be decoded as &quot;BZ&quot; (2 26), &quot;VF&quot; (22 6), or &quot;BBF&quot; (2 2 6).</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;06&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>&quot;06&quot; cannot be mapped to &quot;F&quot; because of the leading zero (&quot;6&quot; is different from &quot;06&quot;). In this case, the string is not a valid encoding, so return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only digits and may contain leading zero(s).</li> </ul>
String; Dynamic Programming
Python
class Solution: def numDecodings(self, s: str) -> int: n = len(s) f = [1] + [0] * n for i, c in enumerate(s, 1): if c != "0": f[i] = f[i - 1] if i > 1 and s[i - 2] != "0" and int(s[i - 2 : i]) <= 26: f[i] += f[i - 2] return f[n]
91
Decode Ways
Medium
<p>You have intercepted a secret message encoded as a string of numbers. The message is <strong>decoded</strong> via the following mapping:</p> <p><code>&quot;1&quot; -&gt; &#39;A&#39;<br /> &quot;2&quot; -&gt; &#39;B&#39;<br /> ...<br /> &quot;25&quot; -&gt; &#39;Y&#39;<br /> &quot;26&quot; -&gt; &#39;Z&#39;</code></p> <p>However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes (<code>&quot;2&quot;</code> and <code>&quot;5&quot;</code> vs <code>&quot;25&quot;</code>).</p> <p>For example, <code>&quot;11106&quot;</code> can be decoded into:</p> <ul> <li><code>&quot;AAJF&quot;</code> with the grouping <code>(1, 1, 10, 6)</code></li> <li><code>&quot;KJF&quot;</code> with the grouping <code>(11, 10, 6)</code></li> <li>The grouping <code>(1, 11, 06)</code> is invalid because <code>&quot;06&quot;</code> is not a valid code (only <code>&quot;6&quot;</code> is valid).</li> </ul> <p>Note: there may be strings that are impossible to decode.<br /> <br /> Given a string s containing only digits, return the <strong>number of ways</strong> to <strong>decode</strong> it. If the entire string cannot be decoded in any valid way, return <code>0</code>.</p> <p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;12&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>&quot;12&quot; could be decoded as &quot;AB&quot; (1 2) or &quot;L&quot; (12).</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;226&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>&quot;226&quot; could be decoded as &quot;BZ&quot; (2 26), &quot;VF&quot; (22 6), or &quot;BBF&quot; (2 2 6).</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;06&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>&quot;06&quot; cannot be mapped to &quot;F&quot; because of the leading zero (&quot;6&quot; is different from &quot;06&quot;). In this case, the string is not a valid encoding, so return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only digits and may contain leading zero(s).</li> </ul>
String; Dynamic Programming
TypeScript
function numDecodings(s: string): number { const n = s.length; const f: number[] = new Array(n + 1).fill(0); f[0] = 1; for (let i = 1; i <= n; ++i) { if (s[i - 1] !== '0') { f[i] = f[i - 1]; } if (i > 1 && (s[i - 2] === '1' || (s[i - 2] === '2' && s[i - 1] <= '6'))) { f[i] += f[i - 2]; } } return f[n]; }
92
Reverse Linked List II
Medium
<p>Given the <code>head</code> of a singly linked list and two integers <code>left</code> and <code>right</code> where <code>left &lt;= right</code>, reverse the nodes of the list from position <code>left</code> to position <code>right</code>, and return <em>the reversed list</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/0000-0099/0092.Reverse%20Linked%20List%20II/images/rev2ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], left = 2, right = 4 <strong>Output:</strong> [1,4,3,2,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [5], left = 1, right = 1 <strong>Output:</strong> [5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>-500 &lt;= Node.val &lt;= 500</code></li> <li><code>1 &lt;= left &lt;= right &lt;= n</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in one pass?
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* reverseBetween(ListNode* head, int left, int right) { if (!head->next || left == right) { return head; } ListNode* dummy = new ListNode(0, head); ListNode* pre = dummy; for (int i = 0; i < left - 1; ++i) { pre = pre->next; } ListNode *p = pre, *q = pre->next; ListNode* cur = q; for (int i = 0; i < right - left + 1; ++i) { ListNode* t = cur->next; cur->next = pre; pre = cur; cur = t; } p->next = pre; q->next = cur; return dummy->next; } };
92
Reverse Linked List II
Medium
<p>Given the <code>head</code> of a singly linked list and two integers <code>left</code> and <code>right</code> where <code>left &lt;= right</code>, reverse the nodes of the list from position <code>left</code> to position <code>right</code>, and return <em>the reversed list</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/0000-0099/0092.Reverse%20Linked%20List%20II/images/rev2ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], left = 2, right = 4 <strong>Output:</strong> [1,4,3,2,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [5], left = 1, right = 1 <strong>Output:</strong> [5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>-500 &lt;= Node.val &lt;= 500</code></li> <li><code>1 &lt;= left &lt;= right &lt;= n</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in one pass?
Linked List
C#
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val=0, ListNode next=null) { * this.val = val; * this.next = next; * } * } */ public class Solution { public ListNode ReverseBetween(ListNode head, int left, int right) { if (head.next == null || left == right) { return head; } ListNode dummy = new ListNode(0, head); ListNode pre = dummy; for (int i = 0; i < left - 1; ++i) { pre = pre.next; } ListNode p = pre; ListNode q = pre.next; ListNode cur = q; for (int i = 0; i < right - left + 1; ++i) { ListNode t = cur.next; cur.next = pre; pre = cur; cur = t; } p.next = pre; q.next = cur; return dummy.next; } }
92
Reverse Linked List II
Medium
<p>Given the <code>head</code> of a singly linked list and two integers <code>left</code> and <code>right</code> where <code>left &lt;= right</code>, reverse the nodes of the list from position <code>left</code> to position <code>right</code>, and return <em>the reversed list</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/0000-0099/0092.Reverse%20Linked%20List%20II/images/rev2ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], left = 2, right = 4 <strong>Output:</strong> [1,4,3,2,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [5], left = 1, right = 1 <strong>Output:</strong> [5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>-500 &lt;= Node.val &lt;= 500</code></li> <li><code>1 &lt;= left &lt;= right &lt;= n</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in one pass?
Linked List
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseBetween(head *ListNode, left int, right int) *ListNode { if head.Next == nil || left == right { return head } dummy := &ListNode{0, head} pre := dummy for i := 0; i < left-1; i++ { pre = pre.Next } p, q := pre, pre.Next cur := q for i := 0; i < right-left+1; i++ { t := cur.Next cur.Next = pre pre = cur cur = t } p.Next = pre q.Next = cur return dummy.Next }
92
Reverse Linked List II
Medium
<p>Given the <code>head</code> of a singly linked list and two integers <code>left</code> and <code>right</code> where <code>left &lt;= right</code>, reverse the nodes of the list from position <code>left</code> to position <code>right</code>, and return <em>the reversed list</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/0000-0099/0092.Reverse%20Linked%20List%20II/images/rev2ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], left = 2, right = 4 <strong>Output:</strong> [1,4,3,2,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [5], left = 1, right = 1 <strong>Output:</strong> [5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>-500 &lt;= Node.val &lt;= 500</code></li> <li><code>1 &lt;= left &lt;= right &lt;= n</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in one pass?
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 reverseBetween(ListNode head, int left, int right) { if (head.next == null || left == right) { return head; } ListNode dummy = new ListNode(0, head); ListNode pre = dummy; for (int i = 0; i < left - 1; ++i) { pre = pre.next; } ListNode p = pre; ListNode q = pre.next; ListNode cur = q; for (int i = 0; i < right - left + 1; ++i) { ListNode t = cur.next; cur.next = pre; pre = cur; cur = t; } p.next = pre; q.next = cur; return dummy.next; } }
92
Reverse Linked List II
Medium
<p>Given the <code>head</code> of a singly linked list and two integers <code>left</code> and <code>right</code> where <code>left &lt;= right</code>, reverse the nodes of the list from position <code>left</code> to position <code>right</code>, and return <em>the reversed list</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/0000-0099/0092.Reverse%20Linked%20List%20II/images/rev2ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], left = 2, right = 4 <strong>Output:</strong> [1,4,3,2,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [5], left = 1, right = 1 <strong>Output:</strong> [5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>-500 &lt;= Node.val &lt;= 500</code></li> <li><code>1 &lt;= left &lt;= right &lt;= n</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in one pass?
Linked List
JavaScript
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @param {number} left * @param {number} right * @return {ListNode} */ var reverseBetween = function (head, left, right) { if (!head.next || left == right) { return head; } const dummy = new ListNode(0, head); let pre = dummy; for (let i = 0; i < left - 1; ++i) { pre = pre.next; } const p = pre; const q = pre.next; let cur = q; for (let i = 0; i < right - left + 1; ++i) { const t = cur.next; cur.next = pre; pre = cur; cur = t; } p.next = pre; q.next = cur; return dummy.next; };
92
Reverse Linked List II
Medium
<p>Given the <code>head</code> of a singly linked list and two integers <code>left</code> and <code>right</code> where <code>left &lt;= right</code>, reverse the nodes of the list from position <code>left</code> to position <code>right</code>, and return <em>the reversed list</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/0000-0099/0092.Reverse%20Linked%20List%20II/images/rev2ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], left = 2, right = 4 <strong>Output:</strong> [1,4,3,2,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [5], left = 1, right = 1 <strong>Output:</strong> [5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>-500 &lt;= Node.val &lt;= 500</code></li> <li><code>1 &lt;= left &lt;= right &lt;= n</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in one pass?
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 reverseBetween( self, head: Optional[ListNode], left: int, right: int ) -> Optional[ListNode]: if head.next is None or left == right: return head dummy = ListNode(0, head) pre = dummy for _ in range(left - 1): pre = pre.next p, q = pre, pre.next cur = q for _ in range(right - left + 1): t = cur.next cur.next = pre pre, cur = cur, t p.next = pre q.next = cur return dummy.next
92
Reverse Linked List II
Medium
<p>Given the <code>head</code> of a singly linked list and two integers <code>left</code> and <code>right</code> where <code>left &lt;= right</code>, reverse the nodes of the list from position <code>left</code> to position <code>right</code>, and return <em>the reversed list</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/0000-0099/0092.Reverse%20Linked%20List%20II/images/rev2ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], left = 2, right = 4 <strong>Output:</strong> [1,4,3,2,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [5], left = 1, right = 1 <strong>Output:</strong> [5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>-500 &lt;= Node.val &lt;= 500</code></li> <li><code>1 &lt;= left &lt;= right &lt;= n</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in one pass?
Linked List
Rust
// Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] // pub struct ListNode { // pub val: i32, // pub next: Option<Box<ListNode>> // } // // impl ListNode { // #[inline] // fn new(val: i32) -> Self { // ListNode { // next: None, // val // } // } // } impl Solution { pub fn reverse_between( head: Option<Box<ListNode>>, left: i32, right: i32, ) -> Option<Box<ListNode>> { let mut dummy = Some(Box::new(ListNode { val: 0, next: head })); let mut pre = &mut dummy; for _ in 1..left { pre = &mut pre.as_mut().unwrap().next; } let mut cur = pre.as_mut().unwrap().next.take(); for _ in 0..right - left + 1 { let mut next = cur.as_mut().unwrap().next.take(); cur.as_mut().unwrap().next = pre.as_mut().unwrap().next.take(); pre.as_mut().unwrap().next = cur.take(); cur = next; } for _ in 0..right - left + 1 { pre = &mut pre.as_mut().unwrap().next; } pre.as_mut().unwrap().next = cur; dummy.unwrap().next } }
92
Reverse Linked List II
Medium
<p>Given the <code>head</code> of a singly linked list and two integers <code>left</code> and <code>right</code> where <code>left &lt;= right</code>, reverse the nodes of the list from position <code>left</code> to position <code>right</code>, and return <em>the reversed list</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/0000-0099/0092.Reverse%20Linked%20List%20II/images/rev2ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], left = 2, right = 4 <strong>Output:</strong> [1,4,3,2,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [5], left = 1, right = 1 <strong>Output:</strong> [5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>-500 &lt;= Node.val &lt;= 500</code></li> <li><code>1 &lt;= left &lt;= right &lt;= n</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do it in one pass?
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 reverseBetween(head: ListNode | null, left: number, right: number): ListNode | null { const n = right - left; if (n === 0) { return head; } const dummy = new ListNode(0, head); let pre = null; let cur = dummy; for (let i = 0; i < left; i++) { pre = cur; cur = cur.next; } const h = pre; pre = null; for (let i = 0; i <= n; i++) { const next = cur.next; cur.next = pre; pre = cur; cur = next; } h.next.next = cur; h.next = pre; return dummy.next; }
93
Restore IP Addresses
Medium
<p>A <strong>valid IP address</strong> consists of exactly four integers separated by single dots. Each integer is between <code>0</code> and <code>255</code> (<strong>inclusive</strong>) and cannot have leading zeros.</p> <ul> <li>For example, <code>&quot;0.1.2.201&quot;</code> and <code>&quot;192.168.1.1&quot;</code> are <strong>valid</strong> IP addresses, but <code>&quot;0.011.255.245&quot;</code>, <code>&quot;192.168.1.312&quot;</code> and <code>&quot;192.168@1.1&quot;</code> are <strong>invalid</strong> IP addresses.</li> </ul> <p>Given a string <code>s</code> containing only digits, return <em>all possible valid IP addresses that can be formed by inserting dots into </em><code>s</code>. You are <strong>not</strong> allowed to reorder or remove any digits in <code>s</code>. You may return the valid IP addresses in <strong>any</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;25525511135&quot; <strong>Output:</strong> [&quot;255.255.11.135&quot;,&quot;255.255.111.35&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0000&quot; <strong>Output:</strong> [&quot;0.0.0.0&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;101023&quot; <strong>Output:</strong> [&quot;1.0.10.23&quot;,&quot;1.0.102.3&quot;,&quot;10.1.0.23&quot;,&quot;10.10.2.3&quot;,&quot;101.0.2.3&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 20</code></li> <li><code>s</code> consists of digits only.</li> </ul>
String; Backtracking
C++
class Solution { public: vector<string> restoreIpAddresses(string s) { int n = s.size(); vector<string> ans; vector<string> t; function<void(int)> dfs = [&](int i) { if (i >= n && t.size() == 4) { ans.push_back(t[0] + "." + t[1] + "." + t[2] + "." + t[3]); return; } if (i >= n || t.size() >= 4) { return; } int x = 0; for (int j = i; j < min(n, i + 3); ++j) { x = x * 10 + s[j] - '0'; if (x > 255 || (j > i && s[i] == '0')) { break; } t.push_back(s.substr(i, j - i + 1)); dfs(j + 1); t.pop_back(); } }; dfs(0); return ans; } };
93
Restore IP Addresses
Medium
<p>A <strong>valid IP address</strong> consists of exactly four integers separated by single dots. Each integer is between <code>0</code> and <code>255</code> (<strong>inclusive</strong>) and cannot have leading zeros.</p> <ul> <li>For example, <code>&quot;0.1.2.201&quot;</code> and <code>&quot;192.168.1.1&quot;</code> are <strong>valid</strong> IP addresses, but <code>&quot;0.011.255.245&quot;</code>, <code>&quot;192.168.1.312&quot;</code> and <code>&quot;192.168@1.1&quot;</code> are <strong>invalid</strong> IP addresses.</li> </ul> <p>Given a string <code>s</code> containing only digits, return <em>all possible valid IP addresses that can be formed by inserting dots into </em><code>s</code>. You are <strong>not</strong> allowed to reorder or remove any digits in <code>s</code>. You may return the valid IP addresses in <strong>any</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;25525511135&quot; <strong>Output:</strong> [&quot;255.255.11.135&quot;,&quot;255.255.111.35&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0000&quot; <strong>Output:</strong> [&quot;0.0.0.0&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;101023&quot; <strong>Output:</strong> [&quot;1.0.10.23&quot;,&quot;1.0.102.3&quot;,&quot;10.1.0.23&quot;,&quot;10.10.2.3&quot;,&quot;101.0.2.3&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 20</code></li> <li><code>s</code> consists of digits only.</li> </ul>
String; Backtracking
C#
public class Solution { private IList<string> ans = new List<string>(); private IList<string> t = new List<string>(); private int n; private string s; public IList<string> RestoreIpAddresses(string s) { n = s.Length; this.s = s; dfs(0); return ans; } private void dfs(int i) { if (i >= n && t.Count == 4) { ans.Add(string.Join(".", t)); return; } if (i >= n || t.Count == 4) { return; } int x = 0; for (int j = i; j < i + 3 && j < n; ++j) { x = x * 10 + (s[j] - '0'); if (x > 255 || (j > i && s[i] == '0')) { break; } t.Add(x.ToString()); dfs(j + 1); t.RemoveAt(t.Count - 1); } } }
93
Restore IP Addresses
Medium
<p>A <strong>valid IP address</strong> consists of exactly four integers separated by single dots. Each integer is between <code>0</code> and <code>255</code> (<strong>inclusive</strong>) and cannot have leading zeros.</p> <ul> <li>For example, <code>&quot;0.1.2.201&quot;</code> and <code>&quot;192.168.1.1&quot;</code> are <strong>valid</strong> IP addresses, but <code>&quot;0.011.255.245&quot;</code>, <code>&quot;192.168.1.312&quot;</code> and <code>&quot;192.168@1.1&quot;</code> are <strong>invalid</strong> IP addresses.</li> </ul> <p>Given a string <code>s</code> containing only digits, return <em>all possible valid IP addresses that can be formed by inserting dots into </em><code>s</code>. You are <strong>not</strong> allowed to reorder or remove any digits in <code>s</code>. You may return the valid IP addresses in <strong>any</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;25525511135&quot; <strong>Output:</strong> [&quot;255.255.11.135&quot;,&quot;255.255.111.35&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0000&quot; <strong>Output:</strong> [&quot;0.0.0.0&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;101023&quot; <strong>Output:</strong> [&quot;1.0.10.23&quot;,&quot;1.0.102.3&quot;,&quot;10.1.0.23&quot;,&quot;10.10.2.3&quot;,&quot;101.0.2.3&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 20</code></li> <li><code>s</code> consists of digits only.</li> </ul>
String; Backtracking
Go
func restoreIpAddresses(s string) (ans []string) { n := len(s) t := []string{} var dfs func(int) dfs = func(i int) { if i >= n && len(t) == 4 { ans = append(ans, strings.Join(t, ".")) return } if i >= n || len(t) == 4 { return } x := 0 for j := i; j < i+3 && j < n; j++ { x = x*10 + int(s[j]-'0') if x > 255 || (j > i && s[i] == '0') { break } t = append(t, s[i:j+1]) dfs(j + 1) t = t[:len(t)-1] } } dfs(0) return }
93
Restore IP Addresses
Medium
<p>A <strong>valid IP address</strong> consists of exactly four integers separated by single dots. Each integer is between <code>0</code> and <code>255</code> (<strong>inclusive</strong>) and cannot have leading zeros.</p> <ul> <li>For example, <code>&quot;0.1.2.201&quot;</code> and <code>&quot;192.168.1.1&quot;</code> are <strong>valid</strong> IP addresses, but <code>&quot;0.011.255.245&quot;</code>, <code>&quot;192.168.1.312&quot;</code> and <code>&quot;192.168@1.1&quot;</code> are <strong>invalid</strong> IP addresses.</li> </ul> <p>Given a string <code>s</code> containing only digits, return <em>all possible valid IP addresses that can be formed by inserting dots into </em><code>s</code>. You are <strong>not</strong> allowed to reorder or remove any digits in <code>s</code>. You may return the valid IP addresses in <strong>any</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;25525511135&quot; <strong>Output:</strong> [&quot;255.255.11.135&quot;,&quot;255.255.111.35&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0000&quot; <strong>Output:</strong> [&quot;0.0.0.0&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;101023&quot; <strong>Output:</strong> [&quot;1.0.10.23&quot;,&quot;1.0.102.3&quot;,&quot;10.1.0.23&quot;,&quot;10.10.2.3&quot;,&quot;101.0.2.3&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 20</code></li> <li><code>s</code> consists of digits only.</li> </ul>
String; Backtracking
Java
class Solution { private int n; private String s; private List<String> ans = new ArrayList<>(); private List<String> t = new ArrayList<>(); public List<String> restoreIpAddresses(String s) { n = s.length(); this.s = s; dfs(0); return ans; } private void dfs(int i) { if (i >= n && t.size() == 4) { ans.add(String.join(".", t)); return; } if (i >= n || t.size() >= 4) { return; } int x = 0; for (int j = i; j < Math.min(i + 3, n); ++j) { x = x * 10 + s.charAt(j) - '0'; if (x > 255 || (s.charAt(i) == '0' && i != j)) { break; } t.add(s.substring(i, j + 1)); dfs(j + 1); t.remove(t.size() - 1); } } }
93
Restore IP Addresses
Medium
<p>A <strong>valid IP address</strong> consists of exactly four integers separated by single dots. Each integer is between <code>0</code> and <code>255</code> (<strong>inclusive</strong>) and cannot have leading zeros.</p> <ul> <li>For example, <code>&quot;0.1.2.201&quot;</code> and <code>&quot;192.168.1.1&quot;</code> are <strong>valid</strong> IP addresses, but <code>&quot;0.011.255.245&quot;</code>, <code>&quot;192.168.1.312&quot;</code> and <code>&quot;192.168@1.1&quot;</code> are <strong>invalid</strong> IP addresses.</li> </ul> <p>Given a string <code>s</code> containing only digits, return <em>all possible valid IP addresses that can be formed by inserting dots into </em><code>s</code>. You are <strong>not</strong> allowed to reorder or remove any digits in <code>s</code>. You may return the valid IP addresses in <strong>any</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;25525511135&quot; <strong>Output:</strong> [&quot;255.255.11.135&quot;,&quot;255.255.111.35&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0000&quot; <strong>Output:</strong> [&quot;0.0.0.0&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;101023&quot; <strong>Output:</strong> [&quot;1.0.10.23&quot;,&quot;1.0.102.3&quot;,&quot;10.1.0.23&quot;,&quot;10.10.2.3&quot;,&quot;101.0.2.3&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 20</code></li> <li><code>s</code> consists of digits only.</li> </ul>
String; Backtracking
Python
class Solution: def restoreIpAddresses(self, s: str) -> List[str]: def check(i: int, j: int) -> int: if s[i] == "0" and i != j: return False return 0 <= int(s[i : j + 1]) <= 255 def dfs(i: int): if i >= n and len(t) == 4: ans.append(".".join(t)) return if i >= n or len(t) >= 4: return for j in range(i, min(i + 3, n)): if check(i, j): t.append(s[i : j + 1]) dfs(j + 1) t.pop() n = len(s) ans = [] t = [] dfs(0) return ans
93
Restore IP Addresses
Medium
<p>A <strong>valid IP address</strong> consists of exactly four integers separated by single dots. Each integer is between <code>0</code> and <code>255</code> (<strong>inclusive</strong>) and cannot have leading zeros.</p> <ul> <li>For example, <code>&quot;0.1.2.201&quot;</code> and <code>&quot;192.168.1.1&quot;</code> are <strong>valid</strong> IP addresses, but <code>&quot;0.011.255.245&quot;</code>, <code>&quot;192.168.1.312&quot;</code> and <code>&quot;192.168@1.1&quot;</code> are <strong>invalid</strong> IP addresses.</li> </ul> <p>Given a string <code>s</code> containing only digits, return <em>all possible valid IP addresses that can be formed by inserting dots into </em><code>s</code>. You are <strong>not</strong> allowed to reorder or remove any digits in <code>s</code>. You may return the valid IP addresses in <strong>any</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;25525511135&quot; <strong>Output:</strong> [&quot;255.255.11.135&quot;,&quot;255.255.111.35&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0000&quot; <strong>Output:</strong> [&quot;0.0.0.0&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;101023&quot; <strong>Output:</strong> [&quot;1.0.10.23&quot;,&quot;1.0.102.3&quot;,&quot;10.1.0.23&quot;,&quot;10.10.2.3&quot;,&quot;101.0.2.3&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 20</code></li> <li><code>s</code> consists of digits only.</li> </ul>
String; Backtracking
TypeScript
function restoreIpAddresses(s: string): string[] { const n = s.length; const ans: string[] = []; const t: string[] = []; const dfs = (i: number): void => { if (i >= n && t.length === 4) { ans.push(t.join('.')); return; } if (i >= n || t.length === 4) { return; } let x = 0; for (let j = i; j < i + 3 && j < n; ++j) { x = x * 10 + s[j].charCodeAt(0) - '0'.charCodeAt(0); if (x > 255 || (j > i && s[i] === '0')) { break; } t.push(x.toString()); dfs(j + 1); t.pop(); } }; dfs(0); return ans; }
94
Binary Tree Inorder Traversal
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the inorder traversal of its nodes&#39; values</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/screenshot-2024-08-29-202743.png" style="width: 200px; height: 264px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,2,6,5,7,1,3,9,8]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/tree_2.png" style="width: 350px; height: 286px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?
Stack; Tree; Depth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> ans; function<void(TreeNode*)> dfs = [&](TreeNode* root) { if (!root) { return; } dfs(root->left); ans.push_back(root->val); dfs(root->right); }; dfs(root); return ans; } };
94
Binary Tree Inorder Traversal
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the inorder traversal of its nodes&#39; values</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/screenshot-2024-08-29-202743.png" style="width: 200px; height: 264px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,2,6,5,7,1,3,9,8]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/tree_2.png" style="width: 350px; height: 286px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?
Stack; Tree; Depth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func inorderTraversal(root *TreeNode) (ans []int) { var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) ans = append(ans, root.Val) dfs(root.Right) } dfs(root) return }
94
Binary Tree Inorder Traversal
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the inorder traversal of its nodes&#39; values</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/screenshot-2024-08-29-202743.png" style="width: 200px; height: 264px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,2,6,5,7,1,3,9,8]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/tree_2.png" style="width: 350px; height: 286px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?
Stack; Tree; Depth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private List<Integer> ans = new ArrayList<>(); public List<Integer> inorderTraversal(TreeNode root) { dfs(root); return ans; } private void dfs(TreeNode root) { if (root == null) { return; } dfs(root.left); ans.add(root.val); dfs(root.right); } }
94
Binary Tree Inorder Traversal
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the inorder traversal of its nodes&#39; values</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/screenshot-2024-08-29-202743.png" style="width: 200px; height: 264px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,2,6,5,7,1,3,9,8]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/tree_2.png" style="width: 350px; height: 286px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?
Stack; Tree; Depth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number[]} */ var inorderTraversal = function (root) { const ans = []; const dfs = root => { if (!root) { return; } dfs(root.left); ans.push(root.val); dfs(root.right); }; dfs(root); return ans; };
94
Binary Tree Inorder Traversal
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the inorder traversal of its nodes&#39; values</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/screenshot-2024-08-29-202743.png" style="width: 200px; height: 264px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,2,6,5,7,1,3,9,8]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/tree_2.png" style="width: 350px; height: 286px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?
Stack; Tree; Depth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: def dfs(root): if root is None: return dfs(root.left) ans.append(root.val) dfs(root.right) ans = [] dfs(root) return ans
94
Binary Tree Inorder Traversal
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the inorder traversal of its nodes&#39; values</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/screenshot-2024-08-29-202743.png" style="width: 200px; height: 264px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,2,6,5,7,1,3,9,8]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/tree_2.png" style="width: 350px; height: 286px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?
Stack; Tree; Depth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { fn dfs(root: &Option<Rc<RefCell<TreeNode>>>, ans: &mut Vec<i32>) { if root.is_none() { return; } let node = root.as_ref().unwrap().borrow(); Self::dfs(&node.left, ans); ans.push(node.val); Self::dfs(&node.right, ans); } pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> { let mut ans = vec![]; Self::dfs(&root, &mut ans); ans } }
94
Binary Tree Inorder Traversal
Easy
<p>Given the <code>root</code> of a binary tree, return <em>the inorder traversal of its nodes&#39; values</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,null,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/screenshot-2024-08-29-202743.png" style="width: 200px; height: 264px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,2,6,5,7,1,3,9,8]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/tree_2.png" style="width: 350px; height: 286px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?
Stack; Tree; Depth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function inorderTraversal(root: TreeNode | null): number[] { const ans: number[] = []; const dfs = (root: TreeNode | null) => { if (!root) { return; } dfs(root.left); ans.push(root.val); dfs(root.right); }; dfs(root); return ans; }
95
Unique Binary Search Trees II
Medium
<p>Given an integer <code>n</code>, return <em>all the structurally unique <strong>BST&#39;</strong>s (binary search trees), which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>. Return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0095.Unique%20Binary%20Search%20Trees%20II/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
Tree; Binary Search Tree; Dynamic Programming; Backtracking; 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: vector<TreeNode*> generateTrees(int n) { function<vector<TreeNode*>(int, int)> dfs = [&](int i, int j) { if (i > j) { return vector<TreeNode*>{nullptr}; } vector<TreeNode*> ans; for (int v = i; v <= j; ++v) { auto left = dfs(i, v - 1); auto right = dfs(v + 1, j); for (auto l : left) { for (auto r : right) { ans.push_back(new TreeNode(v, l, r)); } } } return ans; }; return dfs(1, n); } };
95
Unique Binary Search Trees II
Medium
<p>Given an integer <code>n</code>, return <em>all the structurally unique <strong>BST&#39;</strong>s (binary search trees), which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>. Return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0095.Unique%20Binary%20Search%20Trees%20II/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
Tree; Binary Search Tree; Dynamic Programming; Backtracking; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func generateTrees(n int) []*TreeNode { var dfs func(int, int) []*TreeNode dfs = func(i, j int) []*TreeNode { if i > j { return []*TreeNode{nil} } ans := []*TreeNode{} for v := i; v <= j; v++ { left := dfs(i, v-1) right := dfs(v+1, j) for _, l := range left { for _, r := range right { ans = append(ans, &TreeNode{v, l, r}) } } } return ans } return dfs(1, n) }
95
Unique Binary Search Trees II
Medium
<p>Given an integer <code>n</code>, return <em>all the structurally unique <strong>BST&#39;</strong>s (binary search trees), which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>. Return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0095.Unique%20Binary%20Search%20Trees%20II/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
Tree; Binary Search Tree; Dynamic Programming; Backtracking; 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 List<TreeNode> generateTrees(int n) { return dfs(1, n); } private List<TreeNode> dfs(int i, int j) { List<TreeNode> ans = new ArrayList<>(); if (i > j) { ans.add(null); return ans; } for (int v = i; v <= j; ++v) { var left = dfs(i, v - 1); var right = dfs(v + 1, j); for (var l : left) { for (var r : right) { ans.add(new TreeNode(v, l, r)); } } } return ans; } }
95
Unique Binary Search Trees II
Medium
<p>Given an integer <code>n</code>, return <em>all the structurally unique <strong>BST&#39;</strong>s (binary search trees), which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>. Return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0095.Unique%20Binary%20Search%20Trees%20II/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
Tree; Binary Search Tree; Dynamic Programming; Backtracking; 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 generateTrees(self, n: int) -> List[Optional[TreeNode]]: def dfs(i: int, j: int) -> List[Optional[TreeNode]]: if i > j: return [None] ans = [] for v in range(i, j + 1): left = dfs(i, v - 1) right = dfs(v + 1, j) for l in left: for r in right: ans.append(TreeNode(v, l, r)) return ans return dfs(1, n)
95
Unique Binary Search Trees II
Medium
<p>Given an integer <code>n</code>, return <em>all the structurally unique <strong>BST&#39;</strong>s (binary search trees), which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>. Return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0095.Unique%20Binary%20Search%20Trees%20II/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
Tree; Binary Search Tree; Dynamic Programming; Backtracking; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn generate_trees(n: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> { Self::dfs(1, n) } fn dfs(i: i32, j: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> { let mut ans = Vec::new(); if i > j { ans.push(None); return ans; } for v in i..=j { let left = Self::dfs(i, v - 1); let right = Self::dfs(v + 1, j); for l in &left { for r in &right { ans.push(Some(Rc::new(RefCell::new(TreeNode { val: v, left: l.clone(), right: r.clone(), })))); } } } ans } }
95
Unique Binary Search Trees II
Medium
<p>Given an integer <code>n</code>, return <em>all the structurally unique <strong>BST&#39;</strong>s (binary search trees), which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>. Return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0095.Unique%20Binary%20Search%20Trees%20II/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
Tree; Binary Search Tree; Dynamic Programming; Backtracking; 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 generateTrees(n: number): Array<TreeNode | null> { const dfs = (i: number, j: number): Array<TreeNode | null> => { if (i > j) { return [null]; } const ans: Array<TreeNode | null> = []; for (let v = i; v <= j; ++v) { const left = dfs(i, v - 1); const right = dfs(v + 1, j); for (const l of left) { for (const r of right) { ans.push(new TreeNode(v, l, r)); } } } return ans; }; return dfs(1, n); }
96
Unique Binary Search Trees
Medium
<p>Given an integer <code>n</code>, return <em>the number of structurally unique <strong>BST&#39;</strong>s (binary search trees) which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0096.Unique%20Binary%20Search%20Trees/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 19</code></li> </ul>
Tree; Binary Search Tree; Math; Dynamic Programming; Binary Tree
C++
class Solution { public: int numTrees(int n) { vector<int> f(n + 1); f[0] = 1; for (int i = 1; i <= n; ++i) { for (int j = 0; j < i; ++j) { f[i] += f[j] * f[i - j - 1]; } } return f[n]; } };
96
Unique Binary Search Trees
Medium
<p>Given an integer <code>n</code>, return <em>the number of structurally unique <strong>BST&#39;</strong>s (binary search trees) which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0096.Unique%20Binary%20Search%20Trees/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 19</code></li> </ul>
Tree; Binary Search Tree; Math; Dynamic Programming; Binary Tree
C#
public class Solution { public int NumTrees(int n) { int[] f = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; ++i) { for (int j = 0; j < i; ++j) { f[i] += f[j] * f[i - j - 1]; } } return f[n]; } }
96
Unique Binary Search Trees
Medium
<p>Given an integer <code>n</code>, return <em>the number of structurally unique <strong>BST&#39;</strong>s (binary search trees) which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0096.Unique%20Binary%20Search%20Trees/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 19</code></li> </ul>
Tree; Binary Search Tree; Math; Dynamic Programming; Binary Tree
Go
func numTrees(n int) int { f := make([]int, n+1) f[0] = 1 for i := 1; i <= n; i++ { for j := 0; j < i; j++ { f[i] += f[j] * f[i-j-1] } } return f[n] }
96
Unique Binary Search Trees
Medium
<p>Given an integer <code>n</code>, return <em>the number of structurally unique <strong>BST&#39;</strong>s (binary search trees) which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0096.Unique%20Binary%20Search%20Trees/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 19</code></li> </ul>
Tree; Binary Search Tree; Math; Dynamic Programming; Binary Tree
Java
class Solution { public int numTrees(int n) { int[] f = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; ++i) { for (int j = 0; j < i; ++j) { f[i] += f[j] * f[i - j - 1]; } } return f[n]; } }
96
Unique Binary Search Trees
Medium
<p>Given an integer <code>n</code>, return <em>the number of structurally unique <strong>BST&#39;</strong>s (binary search trees) which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0096.Unique%20Binary%20Search%20Trees/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 19</code></li> </ul>
Tree; Binary Search Tree; Math; Dynamic Programming; Binary Tree
Python
class Solution: def numTrees(self, n: int) -> int: f = [1] + [0] * n for i in range(n + 1): for j in range(i): f[i] += f[j] * f[i - j - 1] return f[n]
96
Unique Binary Search Trees
Medium
<p>Given an integer <code>n</code>, return <em>the number of structurally unique <strong>BST&#39;</strong>s (binary search trees) which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0096.Unique%20Binary%20Search%20Trees/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 19</code></li> </ul>
Tree; Binary Search Tree; Math; Dynamic Programming; Binary Tree
Rust
impl Solution { pub fn num_trees(n: i32) -> i32 { let n = n as usize; let mut f = vec![0; n + 1]; f[0] = 1; for i in 1..=n { for j in 0..i { f[i] += f[j] * f[i - j - 1]; } } f[n] as i32 } }
96
Unique Binary Search Trees
Medium
<p>Given an integer <code>n</code>, return <em>the number of structurally unique <strong>BST&#39;</strong>s (binary search trees) which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0096.Unique%20Binary%20Search%20Trees/images/uniquebstn3.jpg" style="width: 600px; height: 148px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 5 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 19</code></li> </ul>
Tree; Binary Search Tree; Math; Dynamic Programming; Binary Tree
TypeScript
function numTrees(n: number): number { const f: number[] = Array(n + 1).fill(0); f[0] = 1; for (let i = 1; i <= n; ++i) { for (let j = 0; j < i; ++j) { f[i] += f[j] * f[i - j - 1]; } } return f[n]; }
97
Interleaving String
Medium
<p>Given strings <code>s1</code>, <code>s2</code>, and <code>s3</code>, find whether <code>s3</code> is formed by an <strong>interleaving</strong> of <code>s1</code> and <code>s2</code>.</p> <p>An <strong>interleaving</strong> of two strings <code>s</code> and <code>t</code> is a configuration where <code>s</code> and <code>t</code> are divided into <code>n</code> and <code>m</code> <span data-keyword="substring-nonempty">substrings</span> respectively, such that:</p> <ul> <li><code>s = s<sub>1</sub> + s<sub>2</sub> + ... + s<sub>n</sub></code></li> <li><code>t = t<sub>1</sub> + t<sub>2</sub> + ... + t<sub>m</sub></code></li> <li><code>|n - m| &lt;= 1</code></li> <li>The <strong>interleaving</strong> is <code>s<sub>1</sub> + t<sub>1</sub> + s<sub>2</sub> + t<sub>2</sub> + s<sub>3</sub> + t<sub>3</sub> + ...</code> or <code>t<sub>1</sub> + s<sub>1</sub> + t<sub>2</sub> + s<sub>2</sub> + t<sub>3</sub> + s<sub>3</sub> + ...</code></li> </ul> <p><strong>Note:</strong> <code>a + b</code> is the concatenation of strings <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0097.Interleaving%20String/images/interleave.jpg" style="width: 561px; height: 203px;" /> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbcbcac&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One way to obtain s3 is: Split s1 into s1 = &quot;aa&quot; + &quot;bc&quot; + &quot;c&quot;, and s2 into s2 = &quot;dbbc&quot; + &quot;a&quot;. Interleaving the two splits, we get &quot;aa&quot; + &quot;dbbc&quot; + &quot;bc&quot; + &quot;a&quot; + &quot;c&quot; = &quot;aadbbcbcac&quot;. Since s3 can be obtained by interleaving s1 and s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbbaccc&quot; <strong>Output:</strong> false <strong>Explanation:</strong> Notice how it is impossible to interleave s2 with any other string to obtain s3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;&quot;, s2 = &quot;&quot;, s3 = &quot;&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s1.length, s2.length &lt;= 100</code></li> <li><code>0 &lt;= s3.length &lt;= 200</code></li> <li><code>s1</code>, <code>s2</code>, and <code>s3</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it using only <code>O(s2.length)</code> additional memory space?</p>
String; Dynamic Programming
C++
class Solution { public: bool isInterleave(string s1, string s2, string s3) { int m = s1.size(), n = s2.size(); if (m + n != s3.size()) { return false; } vector<vector<int>> f(m + 1, vector<int>(n + 1, -1)); function<bool(int, int)> dfs = [&](int i, int j) { if (i >= m && j >= n) { return true; } if (f[i][j] != -1) { return f[i][j] == 1; } f[i][j] = 0; int k = i + j; if (i < m && s1[i] == s3[k] && dfs(i + 1, j)) { f[i][j] = 1; } if (!f[i][j] && j < n && s2[j] == s3[k] && dfs(i, j + 1)) { f[i][j] = 1; } return f[i][j] == 1; }; return dfs(0, 0); } };
97
Interleaving String
Medium
<p>Given strings <code>s1</code>, <code>s2</code>, and <code>s3</code>, find whether <code>s3</code> is formed by an <strong>interleaving</strong> of <code>s1</code> and <code>s2</code>.</p> <p>An <strong>interleaving</strong> of two strings <code>s</code> and <code>t</code> is a configuration where <code>s</code> and <code>t</code> are divided into <code>n</code> and <code>m</code> <span data-keyword="substring-nonempty">substrings</span> respectively, such that:</p> <ul> <li><code>s = s<sub>1</sub> + s<sub>2</sub> + ... + s<sub>n</sub></code></li> <li><code>t = t<sub>1</sub> + t<sub>2</sub> + ... + t<sub>m</sub></code></li> <li><code>|n - m| &lt;= 1</code></li> <li>The <strong>interleaving</strong> is <code>s<sub>1</sub> + t<sub>1</sub> + s<sub>2</sub> + t<sub>2</sub> + s<sub>3</sub> + t<sub>3</sub> + ...</code> or <code>t<sub>1</sub> + s<sub>1</sub> + t<sub>2</sub> + s<sub>2</sub> + t<sub>3</sub> + s<sub>3</sub> + ...</code></li> </ul> <p><strong>Note:</strong> <code>a + b</code> is the concatenation of strings <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0097.Interleaving%20String/images/interleave.jpg" style="width: 561px; height: 203px;" /> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbcbcac&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One way to obtain s3 is: Split s1 into s1 = &quot;aa&quot; + &quot;bc&quot; + &quot;c&quot;, and s2 into s2 = &quot;dbbc&quot; + &quot;a&quot;. Interleaving the two splits, we get &quot;aa&quot; + &quot;dbbc&quot; + &quot;bc&quot; + &quot;a&quot; + &quot;c&quot; = &quot;aadbbcbcac&quot;. Since s3 can be obtained by interleaving s1 and s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbbaccc&quot; <strong>Output:</strong> false <strong>Explanation:</strong> Notice how it is impossible to interleave s2 with any other string to obtain s3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;&quot;, s2 = &quot;&quot;, s3 = &quot;&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s1.length, s2.length &lt;= 100</code></li> <li><code>0 &lt;= s3.length &lt;= 200</code></li> <li><code>s1</code>, <code>s2</code>, and <code>s3</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it using only <code>O(s2.length)</code> additional memory space?</p>
String; Dynamic Programming
C#
public class Solution { private int m; private int n; private string s1; private string s2; private string s3; private int[,] f; public bool IsInterleave(string s1, string s2, string s3) { m = s1.Length; n = s2.Length; if (m + n != s3.Length) { return false; } this.s1 = s1; this.s2 = s2; this.s3 = s3; f = new int[m + 1, n + 1]; return dfs(0, 0); } private bool dfs(int i, int j) { if (i >= m && j >= n) { return true; } if (f[i, j] != 0) { return f[i, j] == 1; } f[i, j] = -1; if (i < m && s1[i] == s3[i + j] && dfs(i + 1, j)) { f[i, j] = 1; } if (f[i, j] == -1 && j < n && s2[j] == s3[i + j] && dfs(i, j + 1)) { f[i, j] = 1; } return f[i, j] == 1; } }
97
Interleaving String
Medium
<p>Given strings <code>s1</code>, <code>s2</code>, and <code>s3</code>, find whether <code>s3</code> is formed by an <strong>interleaving</strong> of <code>s1</code> and <code>s2</code>.</p> <p>An <strong>interleaving</strong> of two strings <code>s</code> and <code>t</code> is a configuration where <code>s</code> and <code>t</code> are divided into <code>n</code> and <code>m</code> <span data-keyword="substring-nonempty">substrings</span> respectively, such that:</p> <ul> <li><code>s = s<sub>1</sub> + s<sub>2</sub> + ... + s<sub>n</sub></code></li> <li><code>t = t<sub>1</sub> + t<sub>2</sub> + ... + t<sub>m</sub></code></li> <li><code>|n - m| &lt;= 1</code></li> <li>The <strong>interleaving</strong> is <code>s<sub>1</sub> + t<sub>1</sub> + s<sub>2</sub> + t<sub>2</sub> + s<sub>3</sub> + t<sub>3</sub> + ...</code> or <code>t<sub>1</sub> + s<sub>1</sub> + t<sub>2</sub> + s<sub>2</sub> + t<sub>3</sub> + s<sub>3</sub> + ...</code></li> </ul> <p><strong>Note:</strong> <code>a + b</code> is the concatenation of strings <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0097.Interleaving%20String/images/interleave.jpg" style="width: 561px; height: 203px;" /> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbcbcac&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One way to obtain s3 is: Split s1 into s1 = &quot;aa&quot; + &quot;bc&quot; + &quot;c&quot;, and s2 into s2 = &quot;dbbc&quot; + &quot;a&quot;. Interleaving the two splits, we get &quot;aa&quot; + &quot;dbbc&quot; + &quot;bc&quot; + &quot;a&quot; + &quot;c&quot; = &quot;aadbbcbcac&quot;. Since s3 can be obtained by interleaving s1 and s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbbaccc&quot; <strong>Output:</strong> false <strong>Explanation:</strong> Notice how it is impossible to interleave s2 with any other string to obtain s3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;&quot;, s2 = &quot;&quot;, s3 = &quot;&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s1.length, s2.length &lt;= 100</code></li> <li><code>0 &lt;= s3.length &lt;= 200</code></li> <li><code>s1</code>, <code>s2</code>, and <code>s3</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it using only <code>O(s2.length)</code> additional memory space?</p>
String; Dynamic Programming
Go
func isInterleave(s1 string, s2 string, s3 string) bool { m, n := len(s1), len(s2) if m+n != len(s3) { return false } f := map[int]bool{} var dfs func(int, int) bool dfs = func(i, j int) bool { if i >= m && j >= n { return true } if v, ok := f[i*200+j]; ok { return v } k := i + j f[i*200+j] = (i < m && s1[i] == s3[k] && dfs(i+1, j)) || (j < n && s2[j] == s3[k] && dfs(i, j+1)) return f[i*200+j] } return dfs(0, 0) }
97
Interleaving String
Medium
<p>Given strings <code>s1</code>, <code>s2</code>, and <code>s3</code>, find whether <code>s3</code> is formed by an <strong>interleaving</strong> of <code>s1</code> and <code>s2</code>.</p> <p>An <strong>interleaving</strong> of two strings <code>s</code> and <code>t</code> is a configuration where <code>s</code> and <code>t</code> are divided into <code>n</code> and <code>m</code> <span data-keyword="substring-nonempty">substrings</span> respectively, such that:</p> <ul> <li><code>s = s<sub>1</sub> + s<sub>2</sub> + ... + s<sub>n</sub></code></li> <li><code>t = t<sub>1</sub> + t<sub>2</sub> + ... + t<sub>m</sub></code></li> <li><code>|n - m| &lt;= 1</code></li> <li>The <strong>interleaving</strong> is <code>s<sub>1</sub> + t<sub>1</sub> + s<sub>2</sub> + t<sub>2</sub> + s<sub>3</sub> + t<sub>3</sub> + ...</code> or <code>t<sub>1</sub> + s<sub>1</sub> + t<sub>2</sub> + s<sub>2</sub> + t<sub>3</sub> + s<sub>3</sub> + ...</code></li> </ul> <p><strong>Note:</strong> <code>a + b</code> is the concatenation of strings <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0097.Interleaving%20String/images/interleave.jpg" style="width: 561px; height: 203px;" /> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbcbcac&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One way to obtain s3 is: Split s1 into s1 = &quot;aa&quot; + &quot;bc&quot; + &quot;c&quot;, and s2 into s2 = &quot;dbbc&quot; + &quot;a&quot;. Interleaving the two splits, we get &quot;aa&quot; + &quot;dbbc&quot; + &quot;bc&quot; + &quot;a&quot; + &quot;c&quot; = &quot;aadbbcbcac&quot;. Since s3 can be obtained by interleaving s1 and s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbbaccc&quot; <strong>Output:</strong> false <strong>Explanation:</strong> Notice how it is impossible to interleave s2 with any other string to obtain s3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;&quot;, s2 = &quot;&quot;, s3 = &quot;&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s1.length, s2.length &lt;= 100</code></li> <li><code>0 &lt;= s3.length &lt;= 200</code></li> <li><code>s1</code>, <code>s2</code>, and <code>s3</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it using only <code>O(s2.length)</code> additional memory space?</p>
String; Dynamic Programming
Java
class Solution { private Map<List<Integer>, Boolean> f = new HashMap<>(); private String s1; private String s2; private String s3; private int m; private int n; public boolean isInterleave(String s1, String s2, String s3) { m = s1.length(); n = s2.length(); if (m + n != s3.length()) { return false; } this.s1 = s1; this.s2 = s2; this.s3 = s3; return dfs(0, 0); } private boolean dfs(int i, int j) { if (i >= m && j >= n) { return true; } var key = List.of(i, j); if (f.containsKey(key)) { return f.get(key); } int k = i + j; boolean ans = false; if (i < m && s1.charAt(i) == s3.charAt(k) && dfs(i + 1, j)) { ans = true; } if (!ans && j < n && s2.charAt(j) == s3.charAt(k) && dfs(i, j + 1)) { ans = true; } f.put(key, ans); return ans; } }
97
Interleaving String
Medium
<p>Given strings <code>s1</code>, <code>s2</code>, and <code>s3</code>, find whether <code>s3</code> is formed by an <strong>interleaving</strong> of <code>s1</code> and <code>s2</code>.</p> <p>An <strong>interleaving</strong> of two strings <code>s</code> and <code>t</code> is a configuration where <code>s</code> and <code>t</code> are divided into <code>n</code> and <code>m</code> <span data-keyword="substring-nonempty">substrings</span> respectively, such that:</p> <ul> <li><code>s = s<sub>1</sub> + s<sub>2</sub> + ... + s<sub>n</sub></code></li> <li><code>t = t<sub>1</sub> + t<sub>2</sub> + ... + t<sub>m</sub></code></li> <li><code>|n - m| &lt;= 1</code></li> <li>The <strong>interleaving</strong> is <code>s<sub>1</sub> + t<sub>1</sub> + s<sub>2</sub> + t<sub>2</sub> + s<sub>3</sub> + t<sub>3</sub> + ...</code> or <code>t<sub>1</sub> + s<sub>1</sub> + t<sub>2</sub> + s<sub>2</sub> + t<sub>3</sub> + s<sub>3</sub> + ...</code></li> </ul> <p><strong>Note:</strong> <code>a + b</code> is the concatenation of strings <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0097.Interleaving%20String/images/interleave.jpg" style="width: 561px; height: 203px;" /> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbcbcac&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One way to obtain s3 is: Split s1 into s1 = &quot;aa&quot; + &quot;bc&quot; + &quot;c&quot;, and s2 into s2 = &quot;dbbc&quot; + &quot;a&quot;. Interleaving the two splits, we get &quot;aa&quot; + &quot;dbbc&quot; + &quot;bc&quot; + &quot;a&quot; + &quot;c&quot; = &quot;aadbbcbcac&quot;. Since s3 can be obtained by interleaving s1 and s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbbaccc&quot; <strong>Output:</strong> false <strong>Explanation:</strong> Notice how it is impossible to interleave s2 with any other string to obtain s3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;&quot;, s2 = &quot;&quot;, s3 = &quot;&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s1.length, s2.length &lt;= 100</code></li> <li><code>0 &lt;= s3.length &lt;= 200</code></li> <li><code>s1</code>, <code>s2</code>, and <code>s3</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it using only <code>O(s2.length)</code> additional memory space?</p>
String; Dynamic Programming
Python
class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: @cache def dfs(i: int, j: int) -> bool: if i >= m and j >= n: return True k = i + j if i < m and s1[i] == s3[k] and dfs(i + 1, j): return True if j < n and s2[j] == s3[k] and dfs(i, j + 1): return True return False m, n = len(s1), len(s2) if m + n != len(s3): return False return dfs(0, 0)
97
Interleaving String
Medium
<p>Given strings <code>s1</code>, <code>s2</code>, and <code>s3</code>, find whether <code>s3</code> is formed by an <strong>interleaving</strong> of <code>s1</code> and <code>s2</code>.</p> <p>An <strong>interleaving</strong> of two strings <code>s</code> and <code>t</code> is a configuration where <code>s</code> and <code>t</code> are divided into <code>n</code> and <code>m</code> <span data-keyword="substring-nonempty">substrings</span> respectively, such that:</p> <ul> <li><code>s = s<sub>1</sub> + s<sub>2</sub> + ... + s<sub>n</sub></code></li> <li><code>t = t<sub>1</sub> + t<sub>2</sub> + ... + t<sub>m</sub></code></li> <li><code>|n - m| &lt;= 1</code></li> <li>The <strong>interleaving</strong> is <code>s<sub>1</sub> + t<sub>1</sub> + s<sub>2</sub> + t<sub>2</sub> + s<sub>3</sub> + t<sub>3</sub> + ...</code> or <code>t<sub>1</sub> + s<sub>1</sub> + t<sub>2</sub> + s<sub>2</sub> + t<sub>3</sub> + s<sub>3</sub> + ...</code></li> </ul> <p><strong>Note:</strong> <code>a + b</code> is the concatenation of strings <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0097.Interleaving%20String/images/interleave.jpg" style="width: 561px; height: 203px;" /> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbcbcac&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One way to obtain s3 is: Split s1 into s1 = &quot;aa&quot; + &quot;bc&quot; + &quot;c&quot;, and s2 into s2 = &quot;dbbc&quot; + &quot;a&quot;. Interleaving the two splits, we get &quot;aa&quot; + &quot;dbbc&quot; + &quot;bc&quot; + &quot;a&quot; + &quot;c&quot; = &quot;aadbbcbcac&quot;. Since s3 can be obtained by interleaving s1 and s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbbaccc&quot; <strong>Output:</strong> false <strong>Explanation:</strong> Notice how it is impossible to interleave s2 with any other string to obtain s3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;&quot;, s2 = &quot;&quot;, s3 = &quot;&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s1.length, s2.length &lt;= 100</code></li> <li><code>0 &lt;= s3.length &lt;= 200</code></li> <li><code>s1</code>, <code>s2</code>, and <code>s3</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it using only <code>O(s2.length)</code> additional memory space?</p>
String; Dynamic Programming
Rust
impl Solution { #[allow(dead_code)] pub fn is_interleave(s1: String, s2: String, s3: String) -> bool { let n = s1.len(); let m = s2.len(); if s1.len() + s2.len() != s3.len() { return false; } let mut record = vec![vec![-1; m + 1]; n + 1]; Self::dfs( &mut record, n, m, 0, 0, &s1.chars().collect(), &s2.chars().collect(), &s3.chars().collect(), ) } #[allow(dead_code)] fn dfs( record: &mut Vec<Vec<i32>>, n: usize, m: usize, i: usize, j: usize, s1: &Vec<char>, s2: &Vec<char>, s3: &Vec<char>, ) -> bool { if i >= n && j >= m { return true; } if record[i][j] != -1 { return record[i][j] == 1; } // Set the initial value record[i][j] = 0; let k = i + j; // Let's try `s1` first if i < n && s1[i] == s3[k] && Self::dfs(record, n, m, i + 1, j, s1, s2, s3) { record[i][j] = 1; } // If the first approach does not succeed, let's then try `s2` if record[i][j] == 0 && j < m && s2[j] == s3[k] && Self::dfs(record, n, m, i, j + 1, s1, s2, s3) { record[i][j] = 1; } record[i][j] == 1 } }
97
Interleaving String
Medium
<p>Given strings <code>s1</code>, <code>s2</code>, and <code>s3</code>, find whether <code>s3</code> is formed by an <strong>interleaving</strong> of <code>s1</code> and <code>s2</code>.</p> <p>An <strong>interleaving</strong> of two strings <code>s</code> and <code>t</code> is a configuration where <code>s</code> and <code>t</code> are divided into <code>n</code> and <code>m</code> <span data-keyword="substring-nonempty">substrings</span> respectively, such that:</p> <ul> <li><code>s = s<sub>1</sub> + s<sub>2</sub> + ... + s<sub>n</sub></code></li> <li><code>t = t<sub>1</sub> + t<sub>2</sub> + ... + t<sub>m</sub></code></li> <li><code>|n - m| &lt;= 1</code></li> <li>The <strong>interleaving</strong> is <code>s<sub>1</sub> + t<sub>1</sub> + s<sub>2</sub> + t<sub>2</sub> + s<sub>3</sub> + t<sub>3</sub> + ...</code> or <code>t<sub>1</sub> + s<sub>1</sub> + t<sub>2</sub> + s<sub>2</sub> + t<sub>3</sub> + s<sub>3</sub> + ...</code></li> </ul> <p><strong>Note:</strong> <code>a + b</code> is the concatenation of strings <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0097.Interleaving%20String/images/interleave.jpg" style="width: 561px; height: 203px;" /> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbcbcac&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One way to obtain s3 is: Split s1 into s1 = &quot;aa&quot; + &quot;bc&quot; + &quot;c&quot;, and s2 into s2 = &quot;dbbc&quot; + &quot;a&quot;. Interleaving the two splits, we get &quot;aa&quot; + &quot;dbbc&quot; + &quot;bc&quot; + &quot;a&quot; + &quot;c&quot; = &quot;aadbbcbcac&quot;. Since s3 can be obtained by interleaving s1 and s2, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbbaccc&quot; <strong>Output:</strong> false <strong>Explanation:</strong> Notice how it is impossible to interleave s2 with any other string to obtain s3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;&quot;, s2 = &quot;&quot;, s3 = &quot;&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s1.length, s2.length &lt;= 100</code></li> <li><code>0 &lt;= s3.length &lt;= 200</code></li> <li><code>s1</code>, <code>s2</code>, and <code>s3</code> consist of lowercase English letters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it using only <code>O(s2.length)</code> additional memory space?</p>
String; Dynamic Programming
TypeScript
function isInterleave(s1: string, s2: string, s3: string): boolean { const m = s1.length; const n = s2.length; if (m + n !== s3.length) { return false; } const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); const dfs = (i: number, j: number): boolean => { if (i >= m && j >= n) { return true; } if (f[i][j]) { return f[i][j] === 1; } f[i][j] = -1; if (i < m && s1[i] === s3[i + j] && dfs(i + 1, j)) { f[i][j] = 1; } if (f[i][j] === -1 && j < n && s2[j] === s3[i + j] && dfs(i, j + 1)) { f[i][j] = 1; } return f[i][j] === 1; }; return dfs(0, 0); }
98
Validate Binary Search Tree
Medium
<p>Given the <code>root</code> of a binary tree, <em>determine if it is a valid binary search tree (BST)</em>.</p> <p>A <strong>valid BST</strong> is defined as follows:</p> <ul> <li>The left <span data-keyword="subtree">subtree</span> of a node contains only nodes with keys&nbsp;<strong>strictly less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>strictly greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree2.jpg" style="width: 422px; height: 292px;" /> <pre> <strong>Input:</strong> root = [5,1,4,null,null,3,6] <strong>Output:</strong> false <strong>Explanation:</strong> The root node&#39;s value is 5 but its right child&#39;s value is 4. </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>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : 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: bool isValidBST(TreeNode* root) { TreeNode* prev = nullptr; function<bool(TreeNode*)> dfs = [&](TreeNode* root) { if (!root) { return true; } if (!dfs(root->left)) { return false; } if (prev && prev->val >= root->val) { return false; } prev = root; return dfs(root->right); }; return dfs(root); } };
98
Validate Binary Search Tree
Medium
<p>Given the <code>root</code> of a binary tree, <em>determine if it is a valid binary search tree (BST)</em>.</p> <p>A <strong>valid BST</strong> is defined as follows:</p> <ul> <li>The left <span data-keyword="subtree">subtree</span> of a node contains only nodes with keys&nbsp;<strong>strictly less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>strictly greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree2.jpg" style="width: 422px; height: 292px;" /> <pre> <strong>Input:</strong> root = [5,1,4,null,null,3,6] <strong>Output:</strong> false <strong>Explanation:</strong> The root node&#39;s value is 5 but its right child&#39;s value is 4. </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>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
C#
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { private TreeNode prev; public bool IsValidBST(TreeNode root) { return dfs(root); } private bool dfs(TreeNode root) { if (root == null) { return true; } if (!dfs(root.left)) { return false; } if (prev != null && prev.val >= root.val) { return false; } prev = root; return dfs(root.right); } }
98
Validate Binary Search Tree
Medium
<p>Given the <code>root</code> of a binary tree, <em>determine if it is a valid binary search tree (BST)</em>.</p> <p>A <strong>valid BST</strong> is defined as follows:</p> <ul> <li>The left <span data-keyword="subtree">subtree</span> of a node contains only nodes with keys&nbsp;<strong>strictly less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>strictly greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree2.jpg" style="width: 422px; height: 292px;" /> <pre> <strong>Input:</strong> root = [5,1,4,null,null,3,6] <strong>Output:</strong> false <strong>Explanation:</strong> The root node&#39;s value is 5 but its right child&#39;s value is 4. </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>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func isValidBST(root *TreeNode) bool { var prev *TreeNode var dfs func(*TreeNode) bool dfs = func(root *TreeNode) bool { if root == nil { return true } if !dfs(root.Left) { return false } if prev != nil && prev.Val >= root.Val { return false } prev = root return dfs(root.Right) } return dfs(root) }
98
Validate Binary Search Tree
Medium
<p>Given the <code>root</code> of a binary tree, <em>determine if it is a valid binary search tree (BST)</em>.</p> <p>A <strong>valid BST</strong> is defined as follows:</p> <ul> <li>The left <span data-keyword="subtree">subtree</span> of a node contains only nodes with keys&nbsp;<strong>strictly less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>strictly greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree2.jpg" style="width: 422px; height: 292px;" /> <pre> <strong>Input:</strong> root = [5,1,4,null,null,3,6] <strong>Output:</strong> false <strong>Explanation:</strong> The root node&#39;s value is 5 but its right child&#39;s value is 4. </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>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * 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 TreeNode prev; public boolean isValidBST(TreeNode root) { return dfs(root); } private boolean dfs(TreeNode root) { if (root == null) { return true; } if (!dfs(root.left)) { return false; } if (prev != null && prev.val >= root.val) { return false; } prev = root; return dfs(root.right); } }
98
Validate Binary Search Tree
Medium
<p>Given the <code>root</code> of a binary tree, <em>determine if it is a valid binary search tree (BST)</em>.</p> <p>A <strong>valid BST</strong> is defined as follows:</p> <ul> <li>The left <span data-keyword="subtree">subtree</span> of a node contains only nodes with keys&nbsp;<strong>strictly less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>strictly greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree2.jpg" style="width: 422px; height: 292px;" /> <pre> <strong>Input:</strong> root = [5,1,4,null,null,3,6] <strong>Output:</strong> false <strong>Explanation:</strong> The root node&#39;s value is 5 but its right child&#39;s value is 4. </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>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {boolean} */ var isValidBST = function (root) { let prev = null; const dfs = root => { if (!root) { return true; } if (!dfs(root.left)) { return false; } if (prev && prev.val >= root.val) { return false; } prev = root; return dfs(root.right); }; return dfs(root); };
98
Validate Binary Search Tree
Medium
<p>Given the <code>root</code> of a binary tree, <em>determine if it is a valid binary search tree (BST)</em>.</p> <p>A <strong>valid BST</strong> is defined as follows:</p> <ul> <li>The left <span data-keyword="subtree">subtree</span> of a node contains only nodes with keys&nbsp;<strong>strictly less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>strictly greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree2.jpg" style="width: 422px; height: 292px;" /> <pre> <strong>Input:</strong> root = [5,1,4,null,null,3,6] <strong>Output:</strong> false <strong>Explanation:</strong> The root node&#39;s value is 5 but its right child&#39;s value is 4. </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>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: def dfs(root: Optional[TreeNode]) -> bool: if root is None: return True if not dfs(root.left): return False nonlocal prev if prev >= root.val: return False prev = root.val return dfs(root.right) prev = -inf return dfs(root)
98
Validate Binary Search Tree
Medium
<p>Given the <code>root</code> of a binary tree, <em>determine if it is a valid binary search tree (BST)</em>.</p> <p>A <strong>valid BST</strong> is defined as follows:</p> <ul> <li>The left <span data-keyword="subtree">subtree</span> of a node contains only nodes with keys&nbsp;<strong>strictly less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>strictly greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree2.jpg" style="width: 422px; height: 292px;" /> <pre> <strong>Input:</strong> root = [5,1,4,null,null,3,6] <strong>Output:</strong> false <strong>Explanation:</strong> The root node&#39;s value is 5 but its right child&#39;s value is 4. </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>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { fn dfs(root: &Option<Rc<RefCell<TreeNode>>>, prev: &mut Option<i32>) -> bool { if root.is_none() { return true; } let root = root.as_ref().unwrap().borrow(); if !Self::dfs(&root.left, prev) { return false; } if prev.is_some() && prev.unwrap() >= root.val { return false; } *prev = Some(root.val); Self::dfs(&root.right, prev) } pub fn is_valid_bst(root: Option<Rc<RefCell<TreeNode>>>) -> bool { Self::dfs(&root, &mut None) } }