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
112
Path Sum
Easy
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <code>true</code> if the tree has a <strong>root-to-leaf</strong> path such that adding up all the values along the path equals <code>targetSum</code>.</p> <p>A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 <strong>Output:</strong> true <strong>Explanation:</strong> The root-to-leaf path with the target sum is shown. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum2.jpg" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> false <strong>Explanation:</strong> There are two root-to-leaf paths in the tree: (1 --&gt; 2): The sum is 3. (1 --&gt; 3): The sum is 4. There is no root-to-leaf path with sum = 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], targetSum = 0 <strong>Output:</strong> false <strong>Explanation:</strong> Since the tree is empty, there are no root-to-leaf paths. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn has_path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> bool { match root { None => false, Some(node) => { let mut node = node.borrow_mut(); // 确定叶结点身份 if node.left.is_none() && node.right.is_none() { return target_sum - node.val == 0; } let val = node.val; Self::has_path_sum(node.left.take(), target_sum - val) || Self::has_path_sum(node.right.take(), target_sum - val) } } } }
112
Path Sum
Easy
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <code>true</code> if the tree has a <strong>root-to-leaf</strong> path such that adding up all the values along the path equals <code>targetSum</code>.</p> <p>A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 <strong>Output:</strong> true <strong>Explanation:</strong> The root-to-leaf path with the target sum is shown. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum2.jpg" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> false <strong>Explanation:</strong> There are two root-to-leaf paths in the tree: (1 --&gt; 2): The sum is 3. (1 --&gt; 3): The sum is 4. There is no root-to-leaf path with sum = 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], targetSum = 0 <strong>Output:</strong> false <strong>Explanation:</strong> Since the tree is empty, there are no root-to-leaf paths. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function hasPathSum(root: TreeNode | null, targetSum: number): boolean { if (root === null) { return false; } const { val, left, right } = root; if (left === null && right === null) { return targetSum - val === 0; } return hasPathSum(left, targetSum - val) || hasPathSum(right, targetSum - val); }
113
Path Sum II
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>all <strong>root-to-leaf</strong> paths where the sum of the node values in the path equals </em><code>targetSum</code><em>. Each path should be returned as a list of the node <strong>values</strong>, not node references</em>.</p> <p>A <strong>root-to-leaf</strong> path is a path starting from the root and ending at any leaf node. A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0113.Path%20Sum%20II/images/pathsumii1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> [[5,4,11,2],[5,8,4,5]] <strong>Explanation:</strong> There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0113.Path%20Sum%20II/images/pathsum2.jpg" style="width: 212px; height: 181px;" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], targetSum = 0 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; 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<vector<int>> pathSum(TreeNode* root, int targetSum) { vector<vector<int>> ans; vector<int> t; function<void(TreeNode*, int)> dfs = [&](TreeNode* root, int s) { if (!root) return; s -= root->val; t.emplace_back(root->val); if (!root->left && !root->right && s == 0) ans.emplace_back(t); dfs(root->left, s); dfs(root->right, s); t.pop_back(); }; dfs(root, targetSum); return ans; } };
113
Path Sum II
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>all <strong>root-to-leaf</strong> paths where the sum of the node values in the path equals </em><code>targetSum</code><em>. Each path should be returned as a list of the node <strong>values</strong>, not node references</em>.</p> <p>A <strong>root-to-leaf</strong> path is a path starting from the root and ending at any leaf node. A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0113.Path%20Sum%20II/images/pathsumii1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> [[5,4,11,2],[5,8,4,5]] <strong>Explanation:</strong> There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0113.Path%20Sum%20II/images/pathsum2.jpg" style="width: 212px; height: 181px;" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], targetSum = 0 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Backtracking; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func pathSum(root *TreeNode, targetSum int) (ans [][]int) { t := []int{} var dfs func(*TreeNode, int) dfs = func(root *TreeNode, s int) { if root == nil { return } s -= root.Val t = append(t, root.Val) if root.Left == nil && root.Right == nil && s == 0 { ans = append(ans, slices.Clone(t)) } dfs(root.Left, s) dfs(root.Right, s) t = t[:len(t)-1] } dfs(root, targetSum) return }
113
Path Sum II
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>all <strong>root-to-leaf</strong> paths where the sum of the node values in the path equals </em><code>targetSum</code><em>. Each path should be returned as a list of the node <strong>values</strong>, not node references</em>.</p> <p>A <strong>root-to-leaf</strong> path is a path starting from the root and ending at any leaf node. A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0113.Path%20Sum%20II/images/pathsumii1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> [[5,4,11,2],[5,8,4,5]] <strong>Explanation:</strong> There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0113.Path%20Sum%20II/images/pathsum2.jpg" style="width: 212px; height: 181px;" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], targetSum = 0 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; 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 { private List<List<Integer>> ans = new ArrayList<>(); private List<Integer> t = new ArrayList<>(); public List<List<Integer>> pathSum(TreeNode root, int targetSum) { dfs(root, targetSum); return ans; } private void dfs(TreeNode root, int s) { if (root == null) { return; } s -= root.val; t.add(root.val); if (root.left == null && root.right == null && s == 0) { ans.add(new ArrayList<>(t)); } dfs(root.left, s); dfs(root.right, s); t.remove(t.size() - 1); } }
113
Path Sum II
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>all <strong>root-to-leaf</strong> paths where the sum of the node values in the path equals </em><code>targetSum</code><em>. Each path should be returned as a list of the node <strong>values</strong>, not node references</em>.</p> <p>A <strong>root-to-leaf</strong> path is a path starting from the root and ending at any leaf node. A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0113.Path%20Sum%20II/images/pathsumii1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> [[5,4,11,2],[5,8,4,5]] <strong>Explanation:</strong> There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0113.Path%20Sum%20II/images/pathsum2.jpg" style="width: 212px; height: 181px;" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], targetSum = 0 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Backtracking; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} targetSum * @return {number[][]} */ var pathSum = function (root, targetSum) { const ans = []; const t = []; function dfs(root, s) { if (!root) return; s -= root.val; t.push(root.val); if (!root.left && !root.right && s == 0) ans.push([...t]); dfs(root.left, s); dfs(root.right, s); t.pop(); } dfs(root, targetSum); return ans; };
113
Path Sum II
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>all <strong>root-to-leaf</strong> paths where the sum of the node values in the path equals </em><code>targetSum</code><em>. Each path should be returned as a list of the node <strong>values</strong>, not node references</em>.</p> <p>A <strong>root-to-leaf</strong> path is a path starting from the root and ending at any leaf node. A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0113.Path%20Sum%20II/images/pathsumii1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> [[5,4,11,2],[5,8,4,5]] <strong>Explanation:</strong> There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0113.Path%20Sum%20II/images/pathsum2.jpg" style="width: 212px; height: 181px;" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], targetSum = 0 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; 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 pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: def dfs(root, s): if root is None: return s += root.val t.append(root.val) if root.left is None and root.right is None and s == targetSum: ans.append(t[:]) dfs(root.left, s) dfs(root.right, s) t.pop() ans = [] t = [] dfs(root, 0) return ans
113
Path Sum II
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>all <strong>root-to-leaf</strong> paths where the sum of the node values in the path equals </em><code>targetSum</code><em>. Each path should be returned as a list of the node <strong>values</strong>, not node references</em>.</p> <p>A <strong>root-to-leaf</strong> path is a path starting from the root and ending at any leaf node. A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0113.Path%20Sum%20II/images/pathsumii1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> [[5,4,11,2],[5,8,4,5]] <strong>Explanation:</strong> There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0113.Path%20Sum%20II/images/pathsum2.jpg" style="width: 212px; height: 181px;" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2], targetSum = 0 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; 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 { fn dfs( root: Option<Rc<RefCell<TreeNode>>>, paths: &mut Vec<i32>, mut target_sum: i32, res: &mut Vec<Vec<i32>>, ) { if let Some(node) = root { let mut node = node.borrow_mut(); target_sum -= node.val; paths.push(node.val); if node.left.is_none() && node.right.is_none() { if target_sum == 0 { res.push(paths.clone()); } } else { if node.left.is_some() { Self::dfs(node.left.take(), paths, target_sum, res); } if node.right.is_some() { Self::dfs(node.right.take(), paths, target_sum, res); } } paths.pop(); } } pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> Vec<Vec<i32>> { let mut res = vec![]; let mut paths = vec![]; Self::dfs(root, &mut paths, target_sum, &mut res); res } }
114
Flatten Binary Tree to Linked List
Medium
<p>Given the <code>root</code> of a binary tree, flatten the tree into a &quot;linked list&quot;:</p> <ul> <li>The &quot;linked list&quot; should use the same <code>TreeNode</code> class where the <code>right</code> child pointer points to the next node in the list and the <code>left</code> child pointer is always <code>null</code>.</li> <li>The &quot;linked list&quot; should be in the same order as a <a href="https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR" target="_blank"><strong>pre-order</strong><strong> traversal</strong></a> of the binary tree.</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/0100-0199/0114.Flatten%20Binary%20Tree%20to%20Linked%20List/images/flaten.jpg" style="width: 500px; height: 226px;" /> <pre> <strong>Input:</strong> root = [1,2,5,3,4,null,6] <strong>Output:</strong> [1,null,2,null,3,null,4,null,5,null,6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you flatten the tree in-place (with <code>O(1)</code> extra space)?
Stack; Tree; Depth-First Search; Linked List; 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: void flatten(TreeNode* root) { while (root) { if (root->left) { TreeNode* pre = root->left; while (pre->right) { pre = pre->right; } pre->right = root->right; root->right = root->left; root->left = nullptr; } root = root->right; } } };
114
Flatten Binary Tree to Linked List
Medium
<p>Given the <code>root</code> of a binary tree, flatten the tree into a &quot;linked list&quot;:</p> <ul> <li>The &quot;linked list&quot; should use the same <code>TreeNode</code> class where the <code>right</code> child pointer points to the next node in the list and the <code>left</code> child pointer is always <code>null</code>.</li> <li>The &quot;linked list&quot; should be in the same order as a <a href="https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR" target="_blank"><strong>pre-order</strong><strong> traversal</strong></a> of the binary tree.</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/0100-0199/0114.Flatten%20Binary%20Tree%20to%20Linked%20List/images/flaten.jpg" style="width: 500px; height: 226px;" /> <pre> <strong>Input:</strong> root = [1,2,5,3,4,null,6] <strong>Output:</strong> [1,null,2,null,3,null,4,null,5,null,6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you flatten the tree in-place (with <code>O(1)</code> extra space)?
Stack; Tree; Depth-First Search; Linked List; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func flatten(root *TreeNode) { for root != nil { if root.Left != nil { pre := root.Left for pre.Right != nil { pre = pre.Right } pre.Right = root.Right root.Right = root.Left root.Left = nil } root = root.Right } }
114
Flatten Binary Tree to Linked List
Medium
<p>Given the <code>root</code> of a binary tree, flatten the tree into a &quot;linked list&quot;:</p> <ul> <li>The &quot;linked list&quot; should use the same <code>TreeNode</code> class where the <code>right</code> child pointer points to the next node in the list and the <code>left</code> child pointer is always <code>null</code>.</li> <li>The &quot;linked list&quot; should be in the same order as a <a href="https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR" target="_blank"><strong>pre-order</strong><strong> traversal</strong></a> of the binary tree.</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/0100-0199/0114.Flatten%20Binary%20Tree%20to%20Linked%20List/images/flaten.jpg" style="width: 500px; height: 226px;" /> <pre> <strong>Input:</strong> root = [1,2,5,3,4,null,6] <strong>Output:</strong> [1,null,2,null,3,null,4,null,5,null,6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you flatten the tree in-place (with <code>O(1)</code> extra space)?
Stack; Tree; Depth-First Search; Linked List; 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 void flatten(TreeNode root) { while (root != null) { if (root.left != null) { // 找到当前节点左子树的最右节点 TreeNode pre = root.left; while (pre.right != null) { pre = pre.right; } // 将左子树的最右节点指向原来的右子树 pre.right = root.right; // 将当前节点指向左子树 root.right = root.left; root.left = null; } root = root.right; } } }
114
Flatten Binary Tree to Linked List
Medium
<p>Given the <code>root</code> of a binary tree, flatten the tree into a &quot;linked list&quot;:</p> <ul> <li>The &quot;linked list&quot; should use the same <code>TreeNode</code> class where the <code>right</code> child pointer points to the next node in the list and the <code>left</code> child pointer is always <code>null</code>.</li> <li>The &quot;linked list&quot; should be in the same order as a <a href="https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR" target="_blank"><strong>pre-order</strong><strong> traversal</strong></a> of the binary tree.</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/0100-0199/0114.Flatten%20Binary%20Tree%20to%20Linked%20List/images/flaten.jpg" style="width: 500px; height: 226px;" /> <pre> <strong>Input:</strong> root = [1,2,5,3,4,null,6] <strong>Output:</strong> [1,null,2,null,3,null,4,null,5,null,6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you flatten the tree in-place (with <code>O(1)</code> extra space)?
Stack; Tree; Depth-First Search; Linked List; 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 {void} Do not return anything, modify root in-place instead. */ var flatten = function (root) { while (root) { if (root.left) { let pre = root.left; while (pre.right) { pre = pre.right; } pre.right = root.right; root.right = root.left; root.left = null; } root = root.right; } };
114
Flatten Binary Tree to Linked List
Medium
<p>Given the <code>root</code> of a binary tree, flatten the tree into a &quot;linked list&quot;:</p> <ul> <li>The &quot;linked list&quot; should use the same <code>TreeNode</code> class where the <code>right</code> child pointer points to the next node in the list and the <code>left</code> child pointer is always <code>null</code>.</li> <li>The &quot;linked list&quot; should be in the same order as a <a href="https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR" target="_blank"><strong>pre-order</strong><strong> traversal</strong></a> of the binary tree.</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/0100-0199/0114.Flatten%20Binary%20Tree%20to%20Linked%20List/images/flaten.jpg" style="width: 500px; height: 226px;" /> <pre> <strong>Input:</strong> root = [1,2,5,3,4,null,6] <strong>Output:</strong> [1,null,2,null,3,null,4,null,5,null,6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you flatten the tree in-place (with <code>O(1)</code> extra space)?
Stack; Tree; Depth-First Search; Linked List; 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 flatten(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ while root: if root.left: pre = root.left while pre.right: pre = pre.right pre.right = root.right root.right = root.left root.left = None root = root.right
114
Flatten Binary Tree to Linked List
Medium
<p>Given the <code>root</code> of a binary tree, flatten the tree into a &quot;linked list&quot;:</p> <ul> <li>The &quot;linked list&quot; should use the same <code>TreeNode</code> class where the <code>right</code> child pointer points to the next node in the list and the <code>left</code> child pointer is always <code>null</code>.</li> <li>The &quot;linked list&quot; should be in the same order as a <a href="https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR" target="_blank"><strong>pre-order</strong><strong> traversal</strong></a> of the binary tree.</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/0100-0199/0114.Flatten%20Binary%20Tree%20to%20Linked%20List/images/flaten.jpg" style="width: 500px; height: 226px;" /> <pre> <strong>Input:</strong> root = [1,2,5,3,4,null,6] <strong>Output:</strong> [1,null,2,null,3,null,4,null,5,null,6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you flatten the tree in-place (with <code>O(1)</code> extra space)?
Stack; Tree; Depth-First Search; Linked List; 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 { #[allow(dead_code)] pub fn flatten(root: &mut Option<Rc<RefCell<TreeNode>>>) { if root.is_none() { return; } let mut v: Vec<Option<Rc<RefCell<TreeNode>>>> = Vec::new(); // Initialize the vector Self::pre_order_traverse(&mut v, root); // Traverse the vector let n = v.len(); for i in 0..n - 1 { v[i].as_ref().unwrap().borrow_mut().left = None; v[i].as_ref().unwrap().borrow_mut().right = v[i + 1].clone(); } } #[allow(dead_code)] fn pre_order_traverse( v: &mut Vec<Option<Rc<RefCell<TreeNode>>>>, root: &Option<Rc<RefCell<TreeNode>>>, ) { if root.is_none() { return; } v.push(root.clone()); let left = root.as_ref().unwrap().borrow().left.clone(); let right = root.as_ref().unwrap().borrow().right.clone(); Self::pre_order_traverse(v, &left); Self::pre_order_traverse(v, &right); } }
114
Flatten Binary Tree to Linked List
Medium
<p>Given the <code>root</code> of a binary tree, flatten the tree into a &quot;linked list&quot;:</p> <ul> <li>The &quot;linked list&quot; should use the same <code>TreeNode</code> class where the <code>right</code> child pointer points to the next node in the list and the <code>left</code> child pointer is always <code>null</code>.</li> <li>The &quot;linked list&quot; should be in the same order as a <a href="https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR" target="_blank"><strong>pre-order</strong><strong> traversal</strong></a> of the binary tree.</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/0100-0199/0114.Flatten%20Binary%20Tree%20to%20Linked%20List/images/flaten.jpg" style="width: 500px; height: 226px;" /> <pre> <strong>Input:</strong> root = [1,2,5,3,4,null,6] <strong>Output:</strong> [1,null,2,null,3,null,4,null,5,null,6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Can you flatten the tree in-place (with <code>O(1)</code> extra space)?
Stack; Tree; Depth-First Search; Linked List; 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) * } * } */ /** Do not return anything, modify root in-place instead. */ function flatten(root: TreeNode | null): void { while (root !== null) { if (root.left !== null) { let pre = root.left; while (pre.right !== null) { pre = pre.right; } pre.right = root.right; root.right = root.left; root.left = null; } root = root.right; } }
115
Distinct Subsequences
Hard
<p>Given two strings s and t, return <i>the number of distinct</i> <b><i>subsequences</i></b><i> of </i>s<i> which equals </i>t.</p> <p>The test cases are generated so that the answer fits on a 32-bit signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;rabbbit&quot;, t = &quot;rabbit&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> As shown below, there are 3 ways you can generate &quot;rabbit&quot; from s. <code><strong><u>rabb</u></strong>b<strong><u>it</u></strong></code> <code><strong><u>ra</u></strong>b<strong><u>bbit</u></strong></code> <code><strong><u>rab</u></strong>b<strong><u>bit</u></strong></code> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;babgbag&quot;, t = &quot;bag&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> As shown below, there are 5 ways you can generate &quot;bag&quot; from s. <code><strong><u>ba</u></strong>b<u><strong>g</strong></u>bag</code> <code><strong><u>ba</u></strong>bgba<strong><u>g</u></strong></code> <code><u><strong>b</strong></u>abgb<strong><u>ag</u></strong></code> <code>ba<u><strong>b</strong></u>gb<u><strong>ag</strong></u></code> <code>babg<strong><u>bag</u></strong></code></pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li> <li><code>s</code> and <code>t</code> consist of English letters.</li> </ul>
String; Dynamic Programming
C++
class Solution { public: int numDistinct(string s, string t) { int m = s.size(), n = t.size(); unsigned long long f[m + 1][n + 1]; memset(f, 0, sizeof(f)); for (int i = 0; i < m + 1; ++i) { f[i][0] = 1; } for (int i = 1; i < m + 1; ++i) { for (int j = 1; j < n + 1; ++j) { f[i][j] = f[i - 1][j]; if (s[i - 1] == t[j - 1]) { f[i][j] += f[i - 1][j - 1]; } } } return f[m][n]; } };
115
Distinct Subsequences
Hard
<p>Given two strings s and t, return <i>the number of distinct</i> <b><i>subsequences</i></b><i> of </i>s<i> which equals </i>t.</p> <p>The test cases are generated so that the answer fits on a 32-bit signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;rabbbit&quot;, t = &quot;rabbit&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> As shown below, there are 3 ways you can generate &quot;rabbit&quot; from s. <code><strong><u>rabb</u></strong>b<strong><u>it</u></strong></code> <code><strong><u>ra</u></strong>b<strong><u>bbit</u></strong></code> <code><strong><u>rab</u></strong>b<strong><u>bit</u></strong></code> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;babgbag&quot;, t = &quot;bag&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> As shown below, there are 5 ways you can generate &quot;bag&quot; from s. <code><strong><u>ba</u></strong>b<u><strong>g</strong></u>bag</code> <code><strong><u>ba</u></strong>bgba<strong><u>g</u></strong></code> <code><u><strong>b</strong></u>abgb<strong><u>ag</u></strong></code> <code>ba<u><strong>b</strong></u>gb<u><strong>ag</strong></u></code> <code>babg<strong><u>bag</u></strong></code></pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li> <li><code>s</code> and <code>t</code> consist of English letters.</li> </ul>
String; Dynamic Programming
Go
func numDistinct(s string, t string) int { m, n := len(s), len(t) f := make([][]int, m+1) for i := range f { f[i] = make([]int, n+1) } for i := 0; i <= m; i++ { f[i][0] = 1 } for i := 1; i <= m; i++ { for j := 1; j <= n; j++ { f[i][j] = f[i-1][j] if s[i-1] == t[j-1] { f[i][j] += f[i-1][j-1] } } } return f[m][n] }
115
Distinct Subsequences
Hard
<p>Given two strings s and t, return <i>the number of distinct</i> <b><i>subsequences</i></b><i> of </i>s<i> which equals </i>t.</p> <p>The test cases are generated so that the answer fits on a 32-bit signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;rabbbit&quot;, t = &quot;rabbit&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> As shown below, there are 3 ways you can generate &quot;rabbit&quot; from s. <code><strong><u>rabb</u></strong>b<strong><u>it</u></strong></code> <code><strong><u>ra</u></strong>b<strong><u>bbit</u></strong></code> <code><strong><u>rab</u></strong>b<strong><u>bit</u></strong></code> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;babgbag&quot;, t = &quot;bag&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> As shown below, there are 5 ways you can generate &quot;bag&quot; from s. <code><strong><u>ba</u></strong>b<u><strong>g</strong></u>bag</code> <code><strong><u>ba</u></strong>bgba<strong><u>g</u></strong></code> <code><u><strong>b</strong></u>abgb<strong><u>ag</u></strong></code> <code>ba<u><strong>b</strong></u>gb<u><strong>ag</strong></u></code> <code>babg<strong><u>bag</u></strong></code></pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li> <li><code>s</code> and <code>t</code> consist of English letters.</li> </ul>
String; Dynamic Programming
Java
class Solution { public int numDistinct(String s, String t) { int m = s.length(), n = t.length(); int[][] f = new int[m + 1][n + 1]; for (int i = 0; i < m + 1; ++i) { f[i][0] = 1; } for (int i = 1; i < m + 1; ++i) { for (int j = 1; j < n + 1; ++j) { f[i][j] = f[i - 1][j]; if (s.charAt(i - 1) == t.charAt(j - 1)) { f[i][j] += f[i - 1][j - 1]; } } } return f[m][n]; } }
115
Distinct Subsequences
Hard
<p>Given two strings s and t, return <i>the number of distinct</i> <b><i>subsequences</i></b><i> of </i>s<i> which equals </i>t.</p> <p>The test cases are generated so that the answer fits on a 32-bit signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;rabbbit&quot;, t = &quot;rabbit&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> As shown below, there are 3 ways you can generate &quot;rabbit&quot; from s. <code><strong><u>rabb</u></strong>b<strong><u>it</u></strong></code> <code><strong><u>ra</u></strong>b<strong><u>bbit</u></strong></code> <code><strong><u>rab</u></strong>b<strong><u>bit</u></strong></code> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;babgbag&quot;, t = &quot;bag&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> As shown below, there are 5 ways you can generate &quot;bag&quot; from s. <code><strong><u>ba</u></strong>b<u><strong>g</strong></u>bag</code> <code><strong><u>ba</u></strong>bgba<strong><u>g</u></strong></code> <code><u><strong>b</strong></u>abgb<strong><u>ag</u></strong></code> <code>ba<u><strong>b</strong></u>gb<u><strong>ag</strong></u></code> <code>babg<strong><u>bag</u></strong></code></pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li> <li><code>s</code> and <code>t</code> consist of English letters.</li> </ul>
String; Dynamic Programming
Python
class Solution: def numDistinct(self, s: str, t: str) -> int: m, n = len(s), len(t) f = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): f[i][0] = 1 for i, a in enumerate(s, 1): for j, b in enumerate(t, 1): f[i][j] = f[i - 1][j] if a == b: f[i][j] += f[i - 1][j - 1] return f[m][n]
115
Distinct Subsequences
Hard
<p>Given two strings s and t, return <i>the number of distinct</i> <b><i>subsequences</i></b><i> of </i>s<i> which equals </i>t.</p> <p>The test cases are generated so that the answer fits on a 32-bit signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;rabbbit&quot;, t = &quot;rabbit&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> As shown below, there are 3 ways you can generate &quot;rabbit&quot; from s. <code><strong><u>rabb</u></strong>b<strong><u>it</u></strong></code> <code><strong><u>ra</u></strong>b<strong><u>bbit</u></strong></code> <code><strong><u>rab</u></strong>b<strong><u>bit</u></strong></code> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;babgbag&quot;, t = &quot;bag&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> As shown below, there are 5 ways you can generate &quot;bag&quot; from s. <code><strong><u>ba</u></strong>b<u><strong>g</strong></u>bag</code> <code><strong><u>ba</u></strong>bgba<strong><u>g</u></strong></code> <code><u><strong>b</strong></u>abgb<strong><u>ag</u></strong></code> <code>ba<u><strong>b</strong></u>gb<u><strong>ag</strong></u></code> <code>babg<strong><u>bag</u></strong></code></pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li> <li><code>s</code> and <code>t</code> consist of English letters.</li> </ul>
String; Dynamic Programming
Rust
impl Solution { #[allow(dead_code)] pub fn num_distinct(s: String, t: String) -> i32 { let n = s.len(); let m = t.len(); let mut dp: Vec<Vec<u64>> = vec![vec![0; m + 1]; n + 1]; // Initialize the dp vector for i in 0..=n { dp[i][0] = 1; } // Begin the actual dp process for i in 1..=n { for j in 1..=m { dp[i][j] = if s.as_bytes()[i - 1] == t.as_bytes()[j - 1] { dp[i - 1][j] + dp[i - 1][j - 1] } else { dp[i - 1][j] }; } } dp[n][m] as i32 } }
115
Distinct Subsequences
Hard
<p>Given two strings s and t, return <i>the number of distinct</i> <b><i>subsequences</i></b><i> of </i>s<i> which equals </i>t.</p> <p>The test cases are generated so that the answer fits on a 32-bit signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;rabbbit&quot;, t = &quot;rabbit&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> As shown below, there are 3 ways you can generate &quot;rabbit&quot; from s. <code><strong><u>rabb</u></strong>b<strong><u>it</u></strong></code> <code><strong><u>ra</u></strong>b<strong><u>bbit</u></strong></code> <code><strong><u>rab</u></strong>b<strong><u>bit</u></strong></code> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;babgbag&quot;, t = &quot;bag&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> As shown below, there are 5 ways you can generate &quot;bag&quot; from s. <code><strong><u>ba</u></strong>b<u><strong>g</strong></u>bag</code> <code><strong><u>ba</u></strong>bgba<strong><u>g</u></strong></code> <code><u><strong>b</strong></u>abgb<strong><u>ag</u></strong></code> <code>ba<u><strong>b</strong></u>gb<u><strong>ag</strong></u></code> <code>babg<strong><u>bag</u></strong></code></pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li> <li><code>s</code> and <code>t</code> consist of English letters.</li> </ul>
String; Dynamic Programming
TypeScript
function numDistinct(s: string, t: string): number { const m = s.length; const n = t.length; const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); for (let i = 0; i <= m; ++i) { f[i][0] = 1; } for (let i = 1; i <= m; ++i) { for (let j = 1; j <= n; ++j) { f[i][j] = f[i - 1][j]; if (s[i - 1] === t[j - 1]) { f[i][j] += f[i - 1][j - 1]; } } } return f[m][n]; }
116
Populating Next Right Pointers in Each Node
Medium
<p>You are given a <strong>perfect binary tree</strong> where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:</p> <pre> struct Node { int val; Node *left; Node *right; Node *next; } </pre> <p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p> <p>Initially, all next pointers are set to <code>NULL</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/0100-0199/0116.Populating%20Next%20Right%20Pointers%20in%20Each%20Node/images/116_sample.png" style="width: 500px; height: 171px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6,7] <strong>Output:</strong> [1,#,2,3,#,4,5,6,7,#] <strong>Explanation: </strong>Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2<sup>12</sup> - 1]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong></p> <ul> <li>You may only use constant extra space.</li> <li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Linked List; Binary Tree
C++
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() : val(0), left(NULL), right(NULL), next(NULL) {} Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} Node(int _val, Node* _left, Node* _right, Node* _next) : val(_val), left(_left), right(_right), next(_next) {} }; */ class Solution { public: Node* connect(Node* root) { if (!root) { return root; } queue<Node*> q{{root}}; while (!q.empty()) { Node* p = nullptr; for (int n = q.size(); n; --n) { Node* node = q.front(); q.pop(); if (p) { p->next = node; } p = node; if (node->left) { q.push(node->left); } if (node->right) { q.push(node->right); } } } return root; } };
116
Populating Next Right Pointers in Each Node
Medium
<p>You are given a <strong>perfect binary tree</strong> where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:</p> <pre> struct Node { int val; Node *left; Node *right; Node *next; } </pre> <p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p> <p>Initially, all next pointers are set to <code>NULL</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/0100-0199/0116.Populating%20Next%20Right%20Pointers%20in%20Each%20Node/images/116_sample.png" style="width: 500px; height: 171px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6,7] <strong>Output:</strong> [1,#,2,3,#,4,5,6,7,#] <strong>Explanation: </strong>Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2<sup>12</sup> - 1]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong></p> <ul> <li>You may only use constant extra space.</li> <li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Linked List; Binary Tree
Go
/** * Definition for a Node. * type Node struct { * Val int * Left *Node * Right *Node * Next *Node * } */ func connect(root *Node) *Node { if root == nil { return root } q := []*Node{root} for len(q) > 0 { var p *Node for n := len(q); n > 0; n-- { node := q[0] q = q[1:] if p != nil { p.Next = node } p = node if node.Left != nil { q = append(q, node.Left) } if node.Right != nil { q = append(q, node.Right) } } } return root }
116
Populating Next Right Pointers in Each Node
Medium
<p>You are given a <strong>perfect binary tree</strong> where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:</p> <pre> struct Node { int val; Node *left; Node *right; Node *next; } </pre> <p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p> <p>Initially, all next pointers are set to <code>NULL</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/0100-0199/0116.Populating%20Next%20Right%20Pointers%20in%20Each%20Node/images/116_sample.png" style="width: 500px; height: 171px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6,7] <strong>Output:</strong> [1,#,2,3,#,4,5,6,7,#] <strong>Explanation: </strong>Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2<sup>12</sup> - 1]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong></p> <ul> <li>You may only use constant extra space.</li> <li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Linked List; Binary Tree
Java
/* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; } }; */ class Solution { public Node connect(Node root) { if (root == null) { return root; } Deque<Node> q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { Node p = null; for (int n = q.size(); n > 0; --n) { Node node = q.poll(); if (p != null) { p.next = node; } p = node; if (node.left != null) { q.offer(node.left); } if (node.right != null) { q.offer(node.right); } } } return root; } }
116
Populating Next Right Pointers in Each Node
Medium
<p>You are given a <strong>perfect binary tree</strong> where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:</p> <pre> struct Node { int val; Node *left; Node *right; Node *next; } </pre> <p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p> <p>Initially, all next pointers are set to <code>NULL</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/0100-0199/0116.Populating%20Next%20Right%20Pointers%20in%20Each%20Node/images/116_sample.png" style="width: 500px; height: 171px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6,7] <strong>Output:</strong> [1,#,2,3,#,4,5,6,7,#] <strong>Explanation: </strong>Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2<sup>12</sup> - 1]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong></p> <ul> <li>You may only use constant extra space.</li> <li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Linked List; Binary Tree
Python
""" # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ class Solution: def connect(self, root: "Optional[Node]") -> "Optional[Node]": if root is None: return root q = deque([root]) while q: p = None for _ in range(len(q)): node = q.popleft() if p: p.next = node p = node if node.left: q.append(node.left) if node.right: q.append(node.right) return root
116
Populating Next Right Pointers in Each Node
Medium
<p>You are given a <strong>perfect binary tree</strong> where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:</p> <pre> struct Node { int val; Node *left; Node *right; Node *next; } </pre> <p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p> <p>Initially, all next pointers are set to <code>NULL</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/0100-0199/0116.Populating%20Next%20Right%20Pointers%20in%20Each%20Node/images/116_sample.png" style="width: 500px; height: 171px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6,7] <strong>Output:</strong> [1,#,2,3,#,4,5,6,7,#] <strong>Explanation: </strong>Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2<sup>12</sup> - 1]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong></p> <ul> <li>You may only use constant extra space.</li> <li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Linked List; Binary Tree
TypeScript
/** * Definition for Node. * class Node { * val: number * left: Node | null * right: Node | null * next: Node | null * constructor(val?: number, left?: Node, right?: Node, next?: Node) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * this.next = (next===undefined ? null : next) * } * } */ function connect(root: Node | null): Node | null { if (root == null || root.left == null) { return root; } const { left, right, next } = root; left.next = right; if (next != null) { right.next = next.left; } connect(left); connect(right); return root; }
117
Populating Next Right Pointers in Each Node II
Medium
<p>Given a binary tree</p> <pre> struct Node { int val; Node *left; Node *right; Node *next; } </pre> <p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p> <p>Initially, all next pointers are set to <code>NULL</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/0100-0199/0117.Populating%20Next%20Right%20Pointers%20in%20Each%20Node%20II/images/117_sample.png" style="width: 500px; height: 171px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,null,7] <strong>Output:</strong> [1,#,2,3,#,4,5,7,#] <strong>Explanation: </strong>Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 6000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong></p> <ul> <li>You may only use constant extra space.</li> <li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Linked List; Binary Tree
C++
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() : val(0), left(NULL), right(NULL), next(NULL) {} Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} Node(int _val, Node* _left, Node* _right, Node* _next) : val(_val), left(_left), right(_right), next(_next) {} }; */ class Solution { public: Node* connect(Node* root) { if (!root) { return root; } queue<Node*> q{{root}}; while (!q.empty()) { Node* p = nullptr; for (int n = q.size(); n; --n) { Node* node = q.front(); q.pop(); if (p) { p->next = node; } p = node; if (node->left) { q.push(node->left); } if (node->right) { q.push(node->right); } } } return root; } };
117
Populating Next Right Pointers in Each Node II
Medium
<p>Given a binary tree</p> <pre> struct Node { int val; Node *left; Node *right; Node *next; } </pre> <p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p> <p>Initially, all next pointers are set to <code>NULL</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/0100-0199/0117.Populating%20Next%20Right%20Pointers%20in%20Each%20Node%20II/images/117_sample.png" style="width: 500px; height: 171px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,null,7] <strong>Output:</strong> [1,#,2,3,#,4,5,7,#] <strong>Explanation: </strong>Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 6000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong></p> <ul> <li>You may only use constant extra space.</li> <li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Linked List; Binary Tree
C#
/* // Definition for a Node. public class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; } } */ public class Solution { public Node Connect(Node root) { if (root == null) { return null; } var q = new Queue<Node>(); q.Enqueue(root); while (q.Count > 0) { Node p = null; for (int i = q.Count; i > 0; --i) { var node = q.Dequeue(); if (p != null) { p.next = node; } p = node; if (node.left != null) { q.Enqueue(node.left); } if (node.right != null) { q.Enqueue(node.right); } } } return root; } }
117
Populating Next Right Pointers in Each Node II
Medium
<p>Given a binary tree</p> <pre> struct Node { int val; Node *left; Node *right; Node *next; } </pre> <p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p> <p>Initially, all next pointers are set to <code>NULL</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/0100-0199/0117.Populating%20Next%20Right%20Pointers%20in%20Each%20Node%20II/images/117_sample.png" style="width: 500px; height: 171px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,null,7] <strong>Output:</strong> [1,#,2,3,#,4,5,7,#] <strong>Explanation: </strong>Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 6000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong></p> <ul> <li>You may only use constant extra space.</li> <li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Linked List; Binary Tree
Go
/** * Definition for a Node. * type Node struct { * Val int * Left *Node * Right *Node * Next *Node * } */ func connect(root *Node) *Node { if root == nil { return root } q := []*Node{root} for len(q) > 0 { var p *Node for n := len(q); n > 0; n-- { node := q[0] q = q[1:] if p != nil { p.Next = node } p = node if node.Left != nil { q = append(q, node.Left) } if node.Right != nil { q = append(q, node.Right) } } } return root }
117
Populating Next Right Pointers in Each Node II
Medium
<p>Given a binary tree</p> <pre> struct Node { int val; Node *left; Node *right; Node *next; } </pre> <p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p> <p>Initially, all next pointers are set to <code>NULL</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/0100-0199/0117.Populating%20Next%20Right%20Pointers%20in%20Each%20Node%20II/images/117_sample.png" style="width: 500px; height: 171px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,null,7] <strong>Output:</strong> [1,#,2,3,#,4,5,7,#] <strong>Explanation: </strong>Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 6000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong></p> <ul> <li>You may only use constant extra space.</li> <li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Linked List; Binary Tree
Java
/* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; } }; */ class Solution { public Node connect(Node root) { if (root == null) { return root; } Deque<Node> q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { Node p = null; for (int n = q.size(); n > 0; --n) { Node node = q.poll(); if (p != null) { p.next = node; } p = node; if (node.left != null) { q.offer(node.left); } if (node.right != null) { q.offer(node.right); } } } return root; } }
117
Populating Next Right Pointers in Each Node II
Medium
<p>Given a binary tree</p> <pre> struct Node { int val; Node *left; Node *right; Node *next; } </pre> <p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p> <p>Initially, all next pointers are set to <code>NULL</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/0100-0199/0117.Populating%20Next%20Right%20Pointers%20in%20Each%20Node%20II/images/117_sample.png" style="width: 500px; height: 171px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,null,7] <strong>Output:</strong> [1,#,2,3,#,4,5,7,#] <strong>Explanation: </strong>Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 6000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong></p> <ul> <li>You may only use constant extra space.</li> <li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Linked List; Binary Tree
Python
""" # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ class Solution: def connect(self, root: "Node") -> "Node": if root is None: return root q = deque([root]) while q: p = None for _ in range(len(q)): node = q.popleft() if p: p.next = node p = node if node.left: q.append(node.left) if node.right: q.append(node.right) return root
117
Populating Next Right Pointers in Each Node II
Medium
<p>Given a binary tree</p> <pre> struct Node { int val; Node *left; Node *right; Node *next; } </pre> <p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p> <p>Initially, all next pointers are set to <code>NULL</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/0100-0199/0117.Populating%20Next%20Right%20Pointers%20in%20Each%20Node%20II/images/117_sample.png" style="width: 500px; height: 171px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,null,7] <strong>Output:</strong> [1,#,2,3,#,4,5,7,#] <strong>Explanation: </strong>Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 6000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong></p> <ul> <li>You may only use constant extra space.</li> <li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Linked List; Binary Tree
TypeScript
/** * Definition for Node. * class Node { * val: number * left: Node | null * right: Node | null * next: Node | null * constructor(val?: number, left?: Node, right?: Node, next?: Node) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * this.next = (next===undefined ? null : next) * } * } */ function connect(root: Node | null): Node | null { if (!root) { return null; } const q: Node[] = [root]; while (q.length) { const nq: Node[] = []; let p: Node | null = null; for (const node of q) { if (p) { p.next = node; } p = node; const { left, right } = node; left && nq.push(left); right && nq.push(right); } q.splice(0, q.length, ...nq); } return root; }
118
Pascal's Triangle
Easy
<p>Given an integer <code>numRows</code>, return the first numRows of <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0118.Pascal%27s%20Triangle/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> numRows = 5 <strong>Output:</strong> [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> numRows = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numRows &lt;= 30</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> f; f.push_back(vector<int>(1, 1)); for (int i = 0; i < numRows - 1; ++i) { vector<int> g; g.push_back(1); for (int j = 1; j < f[i].size(); ++j) { g.push_back(f[i][j - 1] + f[i][j]); } g.push_back(1); f.push_back(g); } return f; } };
118
Pascal's Triangle
Easy
<p>Given an integer <code>numRows</code>, return the first numRows of <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0118.Pascal%27s%20Triangle/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> numRows = 5 <strong>Output:</strong> [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> numRows = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numRows &lt;= 30</code></li> </ul>
Array; Dynamic Programming
C#
public class Solution { public IList<IList<int>> Generate(int numRows) { var f = new List<IList<int>> { new List<int> { 1 } }; for (int i = 1; i < numRows; ++i) { var g = new List<int> { 1 }; for (int j = 1; j < f[i - 1].Count; ++j) { g.Add(f[i - 1][j - 1] + f[i - 1][j]); } g.Add(1); f.Add(g); } return f; } }
118
Pascal's Triangle
Easy
<p>Given an integer <code>numRows</code>, return the first numRows of <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0118.Pascal%27s%20Triangle/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> numRows = 5 <strong>Output:</strong> [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> numRows = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numRows &lt;= 30</code></li> </ul>
Array; Dynamic Programming
Go
func generate(numRows int) [][]int { f := [][]int{[]int{1}} for i := 0; i < numRows-1; i++ { g := []int{1} for j := 1; j < len(f[i]); j++ { g = append(g, f[i][j-1]+f[i][j]) } g = append(g, 1) f = append(f, g) } return f }
118
Pascal's Triangle
Easy
<p>Given an integer <code>numRows</code>, return the first numRows of <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0118.Pascal%27s%20Triangle/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> numRows = 5 <strong>Output:</strong> [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> numRows = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numRows &lt;= 30</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> f = new ArrayList<>(); f.add(List.of(1)); for (int i = 0; i < numRows - 1; ++i) { List<Integer> g = new ArrayList<>(); g.add(1); for (int j = 1; j < f.get(i).size(); ++j) { g.add(f.get(i).get(j - 1) + f.get(i).get(j)); } g.add(1); f.add(g); } return f; } }
118
Pascal's Triangle
Easy
<p>Given an integer <code>numRows</code>, return the first numRows of <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0118.Pascal%27s%20Triangle/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> numRows = 5 <strong>Output:</strong> [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> numRows = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numRows &lt;= 30</code></li> </ul>
Array; Dynamic Programming
JavaScript
/** * @param {number} numRows * @return {number[][]} */ var generate = function (numRows) { const f = [[1]]; for (let i = 0; i < numRows - 1; ++i) { const g = [1]; for (let j = 1; j < f[i].length; ++j) { g.push(f[i][j - 1] + f[i][j]); } g.push(1); f.push(g); } return f; };
118
Pascal's Triangle
Easy
<p>Given an integer <code>numRows</code>, return the first numRows of <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0118.Pascal%27s%20Triangle/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> numRows = 5 <strong>Output:</strong> [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> numRows = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numRows &lt;= 30</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def generate(self, numRows: int) -> List[List[int]]: f = [[1]] for i in range(numRows - 1): g = [1] + [a + b for a, b in pairwise(f[-1])] + [1] f.append(g) return f
118
Pascal's Triangle
Easy
<p>Given an integer <code>numRows</code>, return the first numRows of <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0118.Pascal%27s%20Triangle/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> numRows = 5 <strong>Output:</strong> [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> numRows = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numRows &lt;= 30</code></li> </ul>
Array; Dynamic Programming
Rust
impl Solution { pub fn generate(num_rows: i32) -> Vec<Vec<i32>> { let mut f = vec![vec![1]]; for i in 1..num_rows { let mut g = vec![1]; for j in 1..f[i as usize - 1].len() { g.push(f[i as usize - 1][j - 1] + f[i as usize - 1][j]); } g.push(1); f.push(g); } f } }
118
Pascal's Triangle
Easy
<p>Given an integer <code>numRows</code>, return the first numRows of <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0118.Pascal%27s%20Triangle/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> numRows = 5 <strong>Output:</strong> [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> numRows = 1 <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numRows &lt;= 30</code></li> </ul>
Array; Dynamic Programming
TypeScript
function generate(numRows: number): number[][] { const f: number[][] = [[1]]; for (let i = 0; i < numRows - 1; ++i) { const g: number[] = [1]; for (let j = 1; j < f[i].length; ++j) { g.push(f[i][j - 1] + f[i][j]); } g.push(1); f.push(g); } return f; }
119
Pascal's Triangle II
Easy
<p>Given an integer <code>rowIndex</code>, return the <code>rowIndex<sup>th</sup></code> (<strong>0-indexed</strong>) row of the <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0119.Pascal%27s%20Triangle%20II/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> rowIndex = 3 <strong>Output:</strong> [1,3,3,1] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> rowIndex = 0 <strong>Output:</strong> [1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> rowIndex = 1 <strong>Output:</strong> [1,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= rowIndex &lt;= 33</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you optimize your algorithm to use only <code>O(rowIndex)</code> extra space?</p>
Array; Dynamic Programming
C++
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> f(rowIndex + 1, 1); for (int i = 2; i < rowIndex + 1; ++i) { for (int j = i - 1; j; --j) { f[j] += f[j - 1]; } } return f; } };
119
Pascal's Triangle II
Easy
<p>Given an integer <code>rowIndex</code>, return the <code>rowIndex<sup>th</sup></code> (<strong>0-indexed</strong>) row of the <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0119.Pascal%27s%20Triangle%20II/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> rowIndex = 3 <strong>Output:</strong> [1,3,3,1] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> rowIndex = 0 <strong>Output:</strong> [1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> rowIndex = 1 <strong>Output:</strong> [1,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= rowIndex &lt;= 33</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you optimize your algorithm to use only <code>O(rowIndex)</code> extra space?</p>
Array; Dynamic Programming
Go
func getRow(rowIndex int) []int { f := make([]int, rowIndex+1) for i := range f { f[i] = 1 } for i := 2; i < rowIndex+1; i++ { for j := i - 1; j > 0; j-- { f[j] += f[j-1] } } return f }
119
Pascal's Triangle II
Easy
<p>Given an integer <code>rowIndex</code>, return the <code>rowIndex<sup>th</sup></code> (<strong>0-indexed</strong>) row of the <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0119.Pascal%27s%20Triangle%20II/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> rowIndex = 3 <strong>Output:</strong> [1,3,3,1] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> rowIndex = 0 <strong>Output:</strong> [1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> rowIndex = 1 <strong>Output:</strong> [1,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= rowIndex &lt;= 33</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you optimize your algorithm to use only <code>O(rowIndex)</code> extra space?</p>
Array; Dynamic Programming
Java
class Solution { public List<Integer> getRow(int rowIndex) { List<Integer> f = new ArrayList<>(); for (int i = 0; i < rowIndex + 1; ++i) { f.add(1); } for (int i = 2; i < rowIndex + 1; ++i) { for (int j = i - 1; j > 0; --j) { f.set(j, f.get(j) + f.get(j - 1)); } } return f; } }
119
Pascal's Triangle II
Easy
<p>Given an integer <code>rowIndex</code>, return the <code>rowIndex<sup>th</sup></code> (<strong>0-indexed</strong>) row of the <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0119.Pascal%27s%20Triangle%20II/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> rowIndex = 3 <strong>Output:</strong> [1,3,3,1] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> rowIndex = 0 <strong>Output:</strong> [1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> rowIndex = 1 <strong>Output:</strong> [1,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= rowIndex &lt;= 33</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you optimize your algorithm to use only <code>O(rowIndex)</code> extra space?</p>
Array; Dynamic Programming
JavaScript
/** * @param {number} rowIndex * @return {number[]} */ var getRow = function (rowIndex) { const f = Array(rowIndex + 1).fill(1); for (let i = 2; i < rowIndex + 1; ++i) { for (let j = i - 1; j; --j) { f[j] += f[j - 1]; } } return f; };
119
Pascal's Triangle II
Easy
<p>Given an integer <code>rowIndex</code>, return the <code>rowIndex<sup>th</sup></code> (<strong>0-indexed</strong>) row of the <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0119.Pascal%27s%20Triangle%20II/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> rowIndex = 3 <strong>Output:</strong> [1,3,3,1] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> rowIndex = 0 <strong>Output:</strong> [1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> rowIndex = 1 <strong>Output:</strong> [1,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= rowIndex &lt;= 33</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you optimize your algorithm to use only <code>O(rowIndex)</code> extra space?</p>
Array; Dynamic Programming
Python
class Solution: def getRow(self, rowIndex: int) -> List[int]: f = [1] * (rowIndex + 1) for i in range(2, rowIndex + 1): for j in range(i - 1, 0, -1): f[j] += f[j - 1] return f
119
Pascal's Triangle II
Easy
<p>Given an integer <code>rowIndex</code>, return the <code>rowIndex<sup>th</sup></code> (<strong>0-indexed</strong>) row of the <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0119.Pascal%27s%20Triangle%20II/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> rowIndex = 3 <strong>Output:</strong> [1,3,3,1] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> rowIndex = 0 <strong>Output:</strong> [1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> rowIndex = 1 <strong>Output:</strong> [1,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= rowIndex &lt;= 33</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you optimize your algorithm to use only <code>O(rowIndex)</code> extra space?</p>
Array; Dynamic Programming
Rust
impl Solution { pub fn get_row(row_index: i32) -> Vec<i32> { let n = (row_index + 1) as usize; let mut f = vec![1; n]; for i in 2..n { for j in (1..i).rev() { f[j] += f[j - 1]; } } f } }
119
Pascal's Triangle II
Easy
<p>Given an integer <code>rowIndex</code>, return the <code>rowIndex<sup>th</sup></code> (<strong>0-indexed</strong>) row of the <strong>Pascal&#39;s triangle</strong>.</p> <p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0119.Pascal%27s%20Triangle%20II/images/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> rowIndex = 3 <strong>Output:</strong> [1,3,3,1] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> rowIndex = 0 <strong>Output:</strong> [1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> rowIndex = 1 <strong>Output:</strong> [1,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= rowIndex &lt;= 33</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you optimize your algorithm to use only <code>O(rowIndex)</code> extra space?</p>
Array; Dynamic Programming
TypeScript
function getRow(rowIndex: number): number[] { const f: number[] = Array(rowIndex + 1).fill(1); for (let i = 2; i < rowIndex + 1; ++i) { for (let j = i - 1; j; --j) { f[j] += f[j - 1]; } } return f; }
120
Triangle
Medium
<p>Given a <code>triangle</code> array, return <em>the minimum path sum from top to bottom</em>.</p> <p>For each step, you may move to an adjacent number of the row below. More formally, if you are on index <code>i</code> on the current row, you may move to either index <code>i</code> or index <code>i + 1</code> on the next row.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The triangle looks like: <u>2</u> <u>3</u> 4 6 <u>5</u> 7 4 <u>1</u> 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> triangle = [[-10]] <strong>Output:</strong> -10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= triangle.length &lt;= 200</code></li> <li><code>triangle[0].length == 1</code></li> <li><code>triangle[i].length == triangle[i - 1].length + 1</code></li> <li><code>-10<sup>4</sup> &lt;= triangle[i][j] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you&nbsp;do this using only <code>O(n)</code> extra space, where <code>n</code> is the total number of rows in the triangle?
Array; Dynamic Programming
C++
class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { int n = triangle.size(); int f[n + 1]; memset(f, 0, sizeof(f)); for (int i = n - 1; ~i; --i) { for (int j = 0; j <= i; ++j) { f[j] = min(f[j], f[j + 1]) + triangle[i][j]; } } return f[0]; } };
120
Triangle
Medium
<p>Given a <code>triangle</code> array, return <em>the minimum path sum from top to bottom</em>.</p> <p>For each step, you may move to an adjacent number of the row below. More formally, if you are on index <code>i</code> on the current row, you may move to either index <code>i</code> or index <code>i + 1</code> on the next row.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The triangle looks like: <u>2</u> <u>3</u> 4 6 <u>5</u> 7 4 <u>1</u> 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> triangle = [[-10]] <strong>Output:</strong> -10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= triangle.length &lt;= 200</code></li> <li><code>triangle[0].length == 1</code></li> <li><code>triangle[i].length == triangle[i - 1].length + 1</code></li> <li><code>-10<sup>4</sup> &lt;= triangle[i][j] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you&nbsp;do this using only <code>O(n)</code> extra space, where <code>n</code> is the total number of rows in the triangle?
Array; Dynamic Programming
Go
func minimumTotal(triangle [][]int) int { n := len(triangle) f := make([]int, n+1) for i := n - 1; i >= 0; i-- { for j := 0; j <= i; j++ { f[j] = min(f[j], f[j+1]) + triangle[i][j] } } return f[0] }
120
Triangle
Medium
<p>Given a <code>triangle</code> array, return <em>the minimum path sum from top to bottom</em>.</p> <p>For each step, you may move to an adjacent number of the row below. More formally, if you are on index <code>i</code> on the current row, you may move to either index <code>i</code> or index <code>i + 1</code> on the next row.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The triangle looks like: <u>2</u> <u>3</u> 4 6 <u>5</u> 7 4 <u>1</u> 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> triangle = [[-10]] <strong>Output:</strong> -10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= triangle.length &lt;= 200</code></li> <li><code>triangle[0].length == 1</code></li> <li><code>triangle[i].length == triangle[i - 1].length + 1</code></li> <li><code>-10<sup>4</sup> &lt;= triangle[i][j] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you&nbsp;do this using only <code>O(n)</code> extra space, where <code>n</code> is the total number of rows in the triangle?
Array; Dynamic Programming
Java
class Solution { public int minimumTotal(List<List<Integer>> triangle) { int n = triangle.size(); int[] f = new int[n + 1]; for (int i = n - 1; i >= 0; --i) { for (int j = 0; j <= i; ++j) { f[j] = Math.min(f[j], f[j + 1]) + triangle.get(i).get(j); } } return f[0]; } }
120
Triangle
Medium
<p>Given a <code>triangle</code> array, return <em>the minimum path sum from top to bottom</em>.</p> <p>For each step, you may move to an adjacent number of the row below. More formally, if you are on index <code>i</code> on the current row, you may move to either index <code>i</code> or index <code>i + 1</code> on the next row.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The triangle looks like: <u>2</u> <u>3</u> 4 6 <u>5</u> 7 4 <u>1</u> 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> triangle = [[-10]] <strong>Output:</strong> -10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= triangle.length &lt;= 200</code></li> <li><code>triangle[0].length == 1</code></li> <li><code>triangle[i].length == triangle[i - 1].length + 1</code></li> <li><code>-10<sup>4</sup> &lt;= triangle[i][j] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you&nbsp;do this using only <code>O(n)</code> extra space, where <code>n</code> is the total number of rows in the triangle?
Array; Dynamic Programming
Python
class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: n = len(triangle) f = [[0] * (n + 1) for _ in range(n + 1)] for i in range(n - 1, -1, -1): for j in range(i + 1): f[i][j] = min(f[i + 1][j], f[i + 1][j + 1]) + triangle[i][j] return f[0][0]
120
Triangle
Medium
<p>Given a <code>triangle</code> array, return <em>the minimum path sum from top to bottom</em>.</p> <p>For each step, you may move to an adjacent number of the row below. More formally, if you are on index <code>i</code> on the current row, you may move to either index <code>i</code> or index <code>i + 1</code> on the next row.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The triangle looks like: <u>2</u> <u>3</u> 4 6 <u>5</u> 7 4 <u>1</u> 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> triangle = [[-10]] <strong>Output:</strong> -10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= triangle.length &lt;= 200</code></li> <li><code>triangle[0].length == 1</code></li> <li><code>triangle[i].length == triangle[i - 1].length + 1</code></li> <li><code>-10<sup>4</sup> &lt;= triangle[i][j] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you&nbsp;do this using only <code>O(n)</code> extra space, where <code>n</code> is the total number of rows in the triangle?
Array; Dynamic Programming
Rust
impl Solution { pub fn minimum_total(triangle: Vec<Vec<i32>>) -> i32 { let n = triangle.len(); let mut f = vec![0; n + 1]; for i in (0..n).rev() { for j in 0..=i { f[j] = f[j].min(f[j + 1]) + triangle[i][j]; } } f[0] } }
120
Triangle
Medium
<p>Given a <code>triangle</code> array, return <em>the minimum path sum from top to bottom</em>.</p> <p>For each step, you may move to an adjacent number of the row below. More formally, if you are on index <code>i</code> on the current row, you may move to either index <code>i</code> or index <code>i + 1</code> on the next row.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The triangle looks like: <u>2</u> <u>3</u> 4 6 <u>5</u> 7 4 <u>1</u> 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> triangle = [[-10]] <strong>Output:</strong> -10 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= triangle.length &lt;= 200</code></li> <li><code>triangle[0].length == 1</code></li> <li><code>triangle[i].length == triangle[i - 1].length + 1</code></li> <li><code>-10<sup>4</sup> &lt;= triangle[i][j] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you&nbsp;do this using only <code>O(n)</code> extra space, where <code>n</code> is the total number of rows in the triangle?
Array; Dynamic Programming
TypeScript
function minimumTotal(triangle: number[][]): number { const n = triangle.length; const f: number[] = Array(n + 1).fill(0); for (let i = n - 1; ~i; --i) { for (let j = 0; j <= i; ++j) { f[j] = Math.min(f[j], f[j + 1]) + triangle[i][j]; } } return f[0]; }
121
Best Time to Buy and Sell Stock
Easy
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p> <p>Return <em>the maximum profit you can achieve from this transaction</em>. If you cannot achieve any profit, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transactions are done and the max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int maxProfit(vector<int>& prices) { int ans = 0, mi = prices[0]; for (int& v : prices) { ans = max(ans, v - mi); mi = min(mi, v); } return ans; } };
121
Best Time to Buy and Sell Stock
Easy
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p> <p>Return <em>the maximum profit you can achieve from this transaction</em>. If you cannot achieve any profit, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transactions are done and the max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Dynamic Programming
C#
public class Solution { public int MaxProfit(int[] prices) { int ans = 0, mi = prices[0]; foreach (int v in prices) { ans = Math.Max(ans, v - mi); mi = Math.Min(mi, v); } return ans; } }
121
Best Time to Buy and Sell Stock
Easy
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p> <p>Return <em>the maximum profit you can achieve from this transaction</em>. If you cannot achieve any profit, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transactions are done and the max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Dynamic Programming
Go
func maxProfit(prices []int) (ans int) { mi := prices[0] for _, v := range prices { ans = max(ans, v-mi) mi = min(mi, v) } return }
121
Best Time to Buy and Sell Stock
Easy
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p> <p>Return <em>the maximum profit you can achieve from this transaction</em>. If you cannot achieve any profit, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transactions are done and the max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int maxProfit(int[] prices) { int ans = 0, mi = prices[0]; for (int v : prices) { ans = Math.max(ans, v - mi); mi = Math.min(mi, v); } return ans; } }
121
Best Time to Buy and Sell Stock
Easy
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p> <p>Return <em>the maximum profit you can achieve from this transaction</em>. If you cannot achieve any profit, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transactions are done and the max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Dynamic Programming
JavaScript
/** * @param {number[]} prices * @return {number} */ var maxProfit = function (prices) { let ans = 0; let mi = prices[0]; for (const v of prices) { ans = Math.max(ans, v - mi); mi = Math.min(mi, v); } return ans; };
121
Best Time to Buy and Sell Stock
Easy
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p> <p>Return <em>the maximum profit you can achieve from this transaction</em>. If you cannot achieve any profit, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transactions are done and the max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Dynamic Programming
PHP
class Solution { /** * @param Integer[] $prices * @return Integer */ function maxProfit($prices) { $ans = 0; $mi = $prices[0]; foreach ($prices as $v) { $ans = max($ans, $v - $mi); $mi = min($mi, $v); } return $ans; } }
121
Best Time to Buy and Sell Stock
Easy
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p> <p>Return <em>the maximum profit you can achieve from this transaction</em>. If you cannot achieve any profit, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transactions are done and the max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maxProfit(self, prices: List[int]) -> int: ans, mi = 0, inf for v in prices: ans = max(ans, v - mi) mi = min(mi, v) return ans
121
Best Time to Buy and Sell Stock
Easy
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p> <p>Return <em>the maximum profit you can achieve from this transaction</em>. If you cannot achieve any profit, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transactions are done and the max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Dynamic Programming
Rust
impl Solution { pub fn max_profit(prices: Vec<i32>) -> i32 { let mut ans = 0; let mut mi = prices[0]; for &v in &prices { ans = ans.max(v - mi); mi = mi.min(v); } ans } }
121
Best Time to Buy and Sell Stock
Easy
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p> <p>Return <em>the maximum profit you can achieve from this transaction</em>. If you cannot achieve any profit, return <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transactions are done and the max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maxProfit(prices: number[]): number { let ans = 0; let mi = prices[0]; for (const v of prices) { ans = Math.max(ans, v - mi); mi = Math.min(mi, v); } return ans; }
122
Best Time to Buy and Sell Stock II
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>On each day, you may decide to buy and/or sell the stock. You can only hold <strong>at most one</strong> share of the stock at any time. However, you can buy it then immediately sell it on the <strong>same day</strong>.</p> <p>Find and return <em>the <strong>maximum</strong> profit you can achieve</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
C++
class Solution { public: int maxProfit(vector<int>& prices) { int ans = 0; for (int i = 1; i < prices.size(); ++i) ans += max(0, prices[i] - prices[i - 1]); return ans; } };
122
Best Time to Buy and Sell Stock II
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>On each day, you may decide to buy and/or sell the stock. You can only hold <strong>at most one</strong> share of the stock at any time. However, you can buy it then immediately sell it on the <strong>same day</strong>.</p> <p>Find and return <em>the <strong>maximum</strong> profit you can achieve</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
C#
public class Solution { public int MaxProfit(int[] prices) { int ans = 0; for (int i = 1; i < prices.Length; ++i) { ans += Math.Max(0, prices[i] - prices[i - 1]); } return ans; } }
122
Best Time to Buy and Sell Stock II
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>On each day, you may decide to buy and/or sell the stock. You can only hold <strong>at most one</strong> share of the stock at any time. However, you can buy it then immediately sell it on the <strong>same day</strong>.</p> <p>Find and return <em>the <strong>maximum</strong> profit you can achieve</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
Go
func maxProfit(prices []int) (ans int) { for i, v := range prices[1:] { t := v - prices[i] if t > 0 { ans += t } } return }
122
Best Time to Buy and Sell Stock II
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>On each day, you may decide to buy and/or sell the stock. You can only hold <strong>at most one</strong> share of the stock at any time. However, you can buy it then immediately sell it on the <strong>same day</strong>.</p> <p>Find and return <em>the <strong>maximum</strong> profit you can achieve</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
Java
class Solution { public int maxProfit(int[] prices) { int ans = 0; for (int i = 1; i < prices.length; ++i) { ans += Math.max(0, prices[i] - prices[i - 1]); } return ans; } }
122
Best Time to Buy and Sell Stock II
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>On each day, you may decide to buy and/or sell the stock. You can only hold <strong>at most one</strong> share of the stock at any time. However, you can buy it then immediately sell it on the <strong>same day</strong>.</p> <p>Find and return <em>the <strong>maximum</strong> profit you can achieve</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
JavaScript
/** * @param {number[]} prices * @return {number} */ var maxProfit = function (prices) { let ans = 0; for (let i = 1; i < prices.length; i++) { ans += Math.max(0, prices[i] - prices[i - 1]); } return ans; };
122
Best Time to Buy and Sell Stock II
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>On each day, you may decide to buy and/or sell the stock. You can only hold <strong>at most one</strong> share of the stock at any time. However, you can buy it then immediately sell it on the <strong>same day</strong>.</p> <p>Find and return <em>the <strong>maximum</strong> profit you can achieve</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
Python
class Solution: def maxProfit(self, prices: List[int]) -> int: return sum(max(0, b - a) for a, b in pairwise(prices))
122
Best Time to Buy and Sell Stock II
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>On each day, you may decide to buy and/or sell the stock. You can only hold <strong>at most one</strong> share of the stock at any time. However, you can buy it then immediately sell it on the <strong>same day</strong>.</p> <p>Find and return <em>the <strong>maximum</strong> profit you can achieve</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
Rust
impl Solution { pub fn max_profit(prices: Vec<i32>) -> i32 { let mut res = 0; for i in 1..prices.len() { res += (0).max(prices[i] - prices[i - 1]); } res } }
122
Best Time to Buy and Sell Stock II
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>On each day, you may decide to buy and/or sell the stock. You can only hold <strong>at most one</strong> share of the stock at any time. However, you can buy it then immediately sell it on the <strong>same day</strong>.</p> <p>Find and return <em>the <strong>maximum</strong> profit you can achieve</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [7,1,5,3,6,4] <strong>Output:</strong> 7 <strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
TypeScript
function maxProfit(prices: number[]): number { let ans = 0; for (let i = 1; i < prices.length; i++) { ans += Math.max(0, prices[i] - prices[i - 1]); } return ans; }
123
Best Time to Buy and Sell Stock III
Hard
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>Find the maximum profit you can achieve. You may complete <strong>at most two transactions</strong>.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [3,3,5,0,0,3,1,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transaction is done, i.e. max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int maxProfit(vector<int>& prices) { int f1 = -prices[0], f2 = 0, f3 = -prices[0], f4 = 0; for (int i = 1; i < prices.size(); ++i) { f1 = max(f1, -prices[i]); f2 = max(f2, f1 + prices[i]); f3 = max(f3, f2 - prices[i]); f4 = max(f4, f3 + prices[i]); } return f4; } };
123
Best Time to Buy and Sell Stock III
Hard
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>Find the maximum profit you can achieve. You may complete <strong>at most two transactions</strong>.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [3,3,5,0,0,3,1,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transaction is done, i.e. max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Dynamic Programming
C#
public class Solution { public int MaxProfit(int[] prices) { int f1 = -prices[0], f2 = 0, f3 = -prices[0], f4 = 0; for (int i = 1; i < prices.Length; ++i) { f1 = Math.Max(f1, -prices[i]); f2 = Math.Max(f2, f1 + prices[i]); f3 = Math.Max(f3, f2 - prices[i]); f4 = Math.Max(f4, f3 + prices[i]); } return f4; } }
123
Best Time to Buy and Sell Stock III
Hard
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>Find the maximum profit you can achieve. You may complete <strong>at most two transactions</strong>.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [3,3,5,0,0,3,1,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transaction is done, i.e. max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Dynamic Programming
Go
func maxProfit(prices []int) int { f1, f2, f3, f4 := -prices[0], 0, -prices[0], 0 for i := 1; i < len(prices); i++ { f1 = max(f1, -prices[i]) f2 = max(f2, f1+prices[i]) f3 = max(f3, f2-prices[i]) f4 = max(f4, f3+prices[i]) } return f4 }
123
Best Time to Buy and Sell Stock III
Hard
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>Find the maximum profit you can achieve. You may complete <strong>at most two transactions</strong>.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [3,3,5,0,0,3,1,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transaction is done, i.e. max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int maxProfit(int[] prices) { // 第一次买入,第一次卖出,第二次买入,第二次卖出 int f1 = -prices[0], f2 = 0, f3 = -prices[0], f4 = 0; for (int i = 1; i < prices.length; ++i) { f1 = Math.max(f1, -prices[i]); f2 = Math.max(f2, f1 + prices[i]); f3 = Math.max(f3, f2 - prices[i]); f4 = Math.max(f4, f3 + prices[i]); } return f4; } }
123
Best Time to Buy and Sell Stock III
Hard
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>Find the maximum profit you can achieve. You may complete <strong>at most two transactions</strong>.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [3,3,5,0,0,3,1,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transaction is done, i.e. max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maxProfit(self, prices: List[int]) -> int: # 第一次买入,第一次卖出,第二次买入,第二次卖出 f1, f2, f3, f4 = -prices[0], 0, -prices[0], 0 for price in prices[1:]: f1 = max(f1, -price) f2 = max(f2, f1 + price) f3 = max(f3, f2 - price) f4 = max(f4, f3 + price) return f4
123
Best Time to Buy and Sell Stock III
Hard
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>Find the maximum profit you can achieve. You may complete <strong>at most two transactions</strong>.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [3,3,5,0,0,3,1,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transaction is done, i.e. max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Dynamic Programming
Rust
impl Solution { #[allow(dead_code)] pub fn max_profit(prices: Vec<i32>) -> i32 { let mut f1 = -prices[0]; let mut f2 = 0; let mut f3 = -prices[0]; let mut f4 = 0; let n = prices.len(); for i in 1..n { f1 = std::cmp::max(f1, -prices[i]); f2 = std::cmp::max(f2, f1 + prices[i]); f3 = std::cmp::max(f3, f2 - prices[i]); f4 = std::cmp::max(f4, f3 + prices[i]); } f4 } }
123
Best Time to Buy and Sell Stock III
Hard
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p> <p>Find the maximum profit you can achieve. You may complete <strong>at most two transactions</strong>.</p> <p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [3,3,5,0,0,3,1,4] <strong>Output:</strong> 6 <strong>Explanation:</strong> Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,3,4,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> prices = [7,6,4,3,1] <strong>Output:</strong> 0 <strong>Explanation:</strong> In this case, no transaction is done, i.e. max profit = 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maxProfit(prices: number[]): number { let [f1, f2, f3, f4] = [-prices[0], 0, -prices[0], 0]; for (let i = 1; i < prices.length; ++i) { f1 = Math.max(f1, -prices[i]); f2 = Math.max(f2, f1 + prices[i]); f3 = Math.max(f3, f2 - prices[i]); f4 = Math.max(f4, f3 + prices[i]); } return f4; }
124
Binary Tree Maximum Path Sum
Hard
<p>A <strong>path</strong> in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence <strong>at most once</strong>. Note that the path does not need to pass through the root.</p> <p>The <strong>path sum</strong> of a path is the sum of the node&#39;s values in the path.</p> <p>Given the <code>root</code> of a binary tree, return <em>the maximum <strong>path sum</strong> of any <strong>non-empty</strong> path</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/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx1.jpg" style="width: 322px; height: 182px;" /> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> 6 <strong>Explanation:</strong> The optimal path is 2 -&gt; 1 -&gt; 3 with a path sum of 2 + 1 + 3 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx2.jpg" /> <pre> <strong>Input:</strong> root = [-10,9,20,null,null,15,7] <strong>Output:</strong> 42 <strong>Explanation:</strong> The optimal path is 15 -&gt; 20 -&gt; 7 with a path sum of 15 + 20 + 7 = 42. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int maxPathSum(TreeNode* root) { int ans = -1001; function<int(TreeNode*)> dfs = [&](TreeNode* root) { if (!root) { return 0; } int left = max(0, dfs(root->left)); int right = max(0, dfs(root->right)); ans = max(ans, left + right + root->val); return root->val + max(left, right); }; dfs(root); return ans; } };
124
Binary Tree Maximum Path Sum
Hard
<p>A <strong>path</strong> in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence <strong>at most once</strong>. Note that the path does not need to pass through the root.</p> <p>The <strong>path sum</strong> of a path is the sum of the node&#39;s values in the path.</p> <p>Given the <code>root</code> of a binary tree, return <em>the maximum <strong>path sum</strong> of any <strong>non-empty</strong> path</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/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx1.jpg" style="width: 322px; height: 182px;" /> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> 6 <strong>Explanation:</strong> The optimal path is 2 -&gt; 1 -&gt; 3 with a path sum of 2 + 1 + 3 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx2.jpg" /> <pre> <strong>Input:</strong> root = [-10,9,20,null,null,15,7] <strong>Output:</strong> 42 <strong>Explanation:</strong> The optimal path is 15 -&gt; 20 -&gt; 7 with a path sum of 15 + 20 + 7 = 42. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; 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 int ans = -1001; public int MaxPathSum(TreeNode root) { dfs(root); return ans; } private int dfs(TreeNode root) { if (root == null) { return 0; } int left = Math.Max(0, dfs(root.left)); int right = Math.Max(0, dfs(root.right)); ans = Math.Max(ans, left + right + root.val); return root.val + Math.Max(left, right); } }
124
Binary Tree Maximum Path Sum
Hard
<p>A <strong>path</strong> in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence <strong>at most once</strong>. Note that the path does not need to pass through the root.</p> <p>The <strong>path sum</strong> of a path is the sum of the node&#39;s values in the path.</p> <p>Given the <code>root</code> of a binary tree, return <em>the maximum <strong>path sum</strong> of any <strong>non-empty</strong> path</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/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx1.jpg" style="width: 322px; height: 182px;" /> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> 6 <strong>Explanation:</strong> The optimal path is 2 -&gt; 1 -&gt; 3 with a path sum of 2 + 1 + 3 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx2.jpg" /> <pre> <strong>Input:</strong> root = [-10,9,20,null,null,15,7] <strong>Output:</strong> 42 <strong>Explanation:</strong> The optimal path is 15 -&gt; 20 -&gt; 7 with a path sum of 15 + 20 + 7 = 42. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func maxPathSum(root *TreeNode) int { ans := -1001 var dfs func(*TreeNode) int dfs = func(root *TreeNode) int { if root == nil { return 0 } left := max(0, dfs(root.Left)) right := max(0, dfs(root.Right)) ans = max(ans, left+right+root.Val) return max(left, right) + root.Val } dfs(root) return ans }
124
Binary Tree Maximum Path Sum
Hard
<p>A <strong>path</strong> in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence <strong>at most once</strong>. Note that the path does not need to pass through the root.</p> <p>The <strong>path sum</strong> of a path is the sum of the node&#39;s values in the path.</p> <p>Given the <code>root</code> of a binary tree, return <em>the maximum <strong>path sum</strong> of any <strong>non-empty</strong> path</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/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx1.jpg" style="width: 322px; height: 182px;" /> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> 6 <strong>Explanation:</strong> The optimal path is 2 -&gt; 1 -&gt; 3 with a path sum of 2 + 1 + 3 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx2.jpg" /> <pre> <strong>Input:</strong> root = [-10,9,20,null,null,15,7] <strong>Output:</strong> 42 <strong>Explanation:</strong> The optimal path is 15 -&gt; 20 -&gt; 7 with a path sum of 15 + 20 + 7 = 42. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int ans = -1001; public int maxPathSum(TreeNode root) { dfs(root); return ans; } private int dfs(TreeNode root) { if (root == null) { return 0; } int left = Math.max(0, dfs(root.left)); int right = Math.max(0, dfs(root.right)); ans = Math.max(ans, root.val + left + right); return root.val + Math.max(left, right); } }
124
Binary Tree Maximum Path Sum
Hard
<p>A <strong>path</strong> in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence <strong>at most once</strong>. Note that the path does not need to pass through the root.</p> <p>The <strong>path sum</strong> of a path is the sum of the node&#39;s values in the path.</p> <p>Given the <code>root</code> of a binary tree, return <em>the maximum <strong>path sum</strong> of any <strong>non-empty</strong> path</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/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx1.jpg" style="width: 322px; height: 182px;" /> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> 6 <strong>Explanation:</strong> The optimal path is 2 -&gt; 1 -&gt; 3 with a path sum of 2 + 1 + 3 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx2.jpg" /> <pre> <strong>Input:</strong> root = [-10,9,20,null,null,15,7] <strong>Output:</strong> 42 <strong>Explanation:</strong> The optimal path is 15 -&gt; 20 -&gt; 7 with a path sum of 15 + 20 + 7 = 42. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; 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 maxPathSum = function (root) { let ans = -1001; const dfs = root => { if (!root) { return 0; } const left = Math.max(0, dfs(root.left)); const right = Math.max(0, dfs(root.right)); ans = Math.max(ans, left + right + root.val); return Math.max(left, right) + root.val; }; dfs(root); return ans; };
124
Binary Tree Maximum Path Sum
Hard
<p>A <strong>path</strong> in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence <strong>at most once</strong>. Note that the path does not need to pass through the root.</p> <p>The <strong>path sum</strong> of a path is the sum of the node&#39;s values in the path.</p> <p>Given the <code>root</code> of a binary tree, return <em>the maximum <strong>path sum</strong> of any <strong>non-empty</strong> path</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/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx1.jpg" style="width: 322px; height: 182px;" /> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> 6 <strong>Explanation:</strong> The optimal path is 2 -&gt; 1 -&gt; 3 with a path sum of 2 + 1 + 3 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx2.jpg" /> <pre> <strong>Input:</strong> root = [-10,9,20,null,null,15,7] <strong>Output:</strong> 42 <strong>Explanation:</strong> The optimal path is 15 -&gt; 20 -&gt; 7 with a path sum of 15 + 20 + 7 = 42. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxPathSum(self, root: Optional[TreeNode]) -> int: def dfs(root: Optional[TreeNode]) -> int: if root is None: return 0 left = max(0, dfs(root.left)) right = max(0, dfs(root.right)) nonlocal ans ans = max(ans, root.val + left + right) return root.val + max(left, right) ans = -inf dfs(root) return ans
124
Binary Tree Maximum Path Sum
Hard
<p>A <strong>path</strong> in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence <strong>at most once</strong>. Note that the path does not need to pass through the root.</p> <p>The <strong>path sum</strong> of a path is the sum of the node&#39;s values in the path.</p> <p>Given the <code>root</code> of a binary tree, return <em>the maximum <strong>path sum</strong> of any <strong>non-empty</strong> path</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/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx1.jpg" style="width: 322px; height: 182px;" /> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> 6 <strong>Explanation:</strong> The optimal path is 2 -&gt; 1 -&gt; 3 with a path sum of 2 + 1 + 3 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx2.jpg" /> <pre> <strong>Input:</strong> root = [-10,9,20,null,null,15,7] <strong>Output:</strong> 42 <strong>Explanation:</strong> The optimal path is 15 -&gt; 20 -&gt; 7 with a path sum of 15 + 20 + 7 = 42. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { fn dfs(root: &Option<Rc<RefCell<TreeNode>>>, res: &mut i32) -> i32 { if root.is_none() { return 0; } let node = root.as_ref().unwrap().borrow(); let left = (0).max(Self::dfs(&node.left, res)); let right = (0).max(Self::dfs(&node.right, res)); *res = (node.val + left + right).max(*res); node.val + left.max(right) } pub fn max_path_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { let mut res = -1000; Self::dfs(&root, &mut res); res } }
124
Binary Tree Maximum Path Sum
Hard
<p>A <strong>path</strong> in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence <strong>at most once</strong>. Note that the path does not need to pass through the root.</p> <p>The <strong>path sum</strong> of a path is the sum of the node&#39;s values in the path.</p> <p>Given the <code>root</code> of a binary tree, return <em>the maximum <strong>path sum</strong> of any <strong>non-empty</strong> path</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/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx1.jpg" style="width: 322px; height: 182px;" /> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> 6 <strong>Explanation:</strong> The optimal path is 2 -&gt; 1 -&gt; 3 with a path sum of 2 + 1 + 3 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/images/exx2.jpg" /> <pre> <strong>Input:</strong> root = [-10,9,20,null,null,15,7] <strong>Output:</strong> 42 <strong>Explanation:</strong> The optimal path is 15 -&gt; 20 -&gt; 7 with a path sum of 15 + 20 + 7 = 42. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Dynamic Programming; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function maxPathSum(root: TreeNode | null): number { let ans = -1001; const dfs = (root: TreeNode | null): number => { if (!root) { return 0; } const left = Math.max(0, dfs(root.left)); const right = Math.max(0, dfs(root.right)); ans = Math.max(ans, left + right + root.val); return Math.max(left, right) + root.val; }; dfs(root); return ans; }
125
Valid Palindrome
Easy
<p>A phrase is a <strong>palindrome</strong> if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.</p> <p>Given a string <code>s</code>, return <code>true</code><em> if it is a <strong>palindrome</strong>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;A man, a plan, a canal: Panama&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;amanaplanacanalpanama&quot; is a palindrome. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;race a car&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;raceacar&quot; is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot; &quot; <strong>Output:</strong> true <strong>Explanation:</strong> s is an empty string &quot;&quot; after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of printable ASCII characters.</li> </ul>
Two Pointers; String
C++
class Solution { public: bool isPalindrome(string s) { int i = 0, j = s.size() - 1; while (i < j) { if (!isalnum(s[i])) { ++i; } else if (!isalnum(s[j])) { --j; } else if (tolower(s[i]) != tolower(s[j])) { return false; } else { ++i; --j; } } return true; } };
125
Valid Palindrome
Easy
<p>A phrase is a <strong>palindrome</strong> if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.</p> <p>Given a string <code>s</code>, return <code>true</code><em> if it is a <strong>palindrome</strong>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;A man, a plan, a canal: Panama&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;amanaplanacanalpanama&quot; is a palindrome. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;race a car&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;raceacar&quot; is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot; &quot; <strong>Output:</strong> true <strong>Explanation:</strong> s is an empty string &quot;&quot; after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of printable ASCII characters.</li> </ul>
Two Pointers; String
C#
public class Solution { public bool IsPalindrome(string s) { int i = 0, j = s.Length - 1; while (i < j) { if (!char.IsLetterOrDigit(s[i])) { ++i; } else if (!char.IsLetterOrDigit(s[j])) { --j; } else if (char.ToLower(s[i++]) != char.ToLower(s[j--])) { return false; } } return true; } }
125
Valid Palindrome
Easy
<p>A phrase is a <strong>palindrome</strong> if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.</p> <p>Given a string <code>s</code>, return <code>true</code><em> if it is a <strong>palindrome</strong>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;A man, a plan, a canal: Panama&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;amanaplanacanalpanama&quot; is a palindrome. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;race a car&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;raceacar&quot; is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot; &quot; <strong>Output:</strong> true <strong>Explanation:</strong> s is an empty string &quot;&quot; after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of printable ASCII characters.</li> </ul>
Two Pointers; String
Go
func isPalindrome(s string) bool { i, j := 0, len(s)-1 for i < j { if !isalnum(s[i]) { i++ } else if !isalnum(s[j]) { j-- } else if tolower(s[i]) != tolower(s[j]) { return false } else { i, j = i+1, j-1 } } return true } func isalnum(ch byte) bool { return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') } func tolower(ch byte) byte { if ch >= 'A' && ch <= 'Z' { return ch + 32 } return ch }
125
Valid Palindrome
Easy
<p>A phrase is a <strong>palindrome</strong> if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.</p> <p>Given a string <code>s</code>, return <code>true</code><em> if it is a <strong>palindrome</strong>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;A man, a plan, a canal: Panama&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;amanaplanacanalpanama&quot; is a palindrome. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;race a car&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;raceacar&quot; is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot; &quot; <strong>Output:</strong> true <strong>Explanation:</strong> s is an empty string &quot;&quot; after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of printable ASCII characters.</li> </ul>
Two Pointers; String
Java
class Solution { public boolean isPalindrome(String s) { int i = 0, j = s.length() - 1; while (i < j) { if (!Character.isLetterOrDigit(s.charAt(i))) { ++i; } else if (!Character.isLetterOrDigit(s.charAt(j))) { --j; } else if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) { return false; } else { ++i; --j; } } return true; } }
125
Valid Palindrome
Easy
<p>A phrase is a <strong>palindrome</strong> if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.</p> <p>Given a string <code>s</code>, return <code>true</code><em> if it is a <strong>palindrome</strong>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;A man, a plan, a canal: Panama&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;amanaplanacanalpanama&quot; is a palindrome. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;race a car&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;raceacar&quot; is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot; &quot; <strong>Output:</strong> true <strong>Explanation:</strong> s is an empty string &quot;&quot; after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of printable ASCII characters.</li> </ul>
Two Pointers; String
JavaScript
/** * @param {string} s * @return {boolean} */ var isPalindrome = function (s) { let i = 0; let j = s.length - 1; while (i < j) { if (!/[a-zA-Z0-9]/.test(s[i])) { ++i; } else if (!/[a-zA-Z0-9]/.test(s[j])) { --j; } else if (s[i].toLowerCase() !== s[j].toLowerCase()) { return false; } else { ++i; --j; } } return true; };
125
Valid Palindrome
Easy
<p>A phrase is a <strong>palindrome</strong> if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.</p> <p>Given a string <code>s</code>, return <code>true</code><em> if it is a <strong>palindrome</strong>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;A man, a plan, a canal: Panama&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;amanaplanacanalpanama&quot; is a palindrome. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;race a car&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;raceacar&quot; is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot; &quot; <strong>Output:</strong> true <strong>Explanation:</strong> s is an empty string &quot;&quot; after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of printable ASCII characters.</li> </ul>
Two Pointers; String
PHP
class Solution { /** * @param String $s * @return Boolean */ function isPalindrome($s) { $regex = '/[a-z0-9]/'; $s = strtolower($s); preg_match_all($regex, $s, $matches); if ($matches[0] == null) { return true; } $len = floor(count($matches[0]) / 2); for ($i = 0; $i < $len; $i++) { if ($matches[0][$i] != $matches[0][count($matches[0]) - 1 - $i]) { return false; } } return true; } }
125
Valid Palindrome
Easy
<p>A phrase is a <strong>palindrome</strong> if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.</p> <p>Given a string <code>s</code>, return <code>true</code><em> if it is a <strong>palindrome</strong>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;A man, a plan, a canal: Panama&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;amanaplanacanalpanama&quot; is a palindrome. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;race a car&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;raceacar&quot; is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot; &quot; <strong>Output:</strong> true <strong>Explanation:</strong> s is an empty string &quot;&quot; after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of printable ASCII characters.</li> </ul>
Two Pointers; String
Python
class Solution: def isPalindrome(self, s: str) -> bool: i, j = 0, len(s) - 1 while i < j: if not s[i].isalnum(): i += 1 elif not s[j].isalnum(): j -= 1 elif s[i].lower() != s[j].lower(): return False else: i, j = i + 1, j - 1 return True
125
Valid Palindrome
Easy
<p>A phrase is a <strong>palindrome</strong> if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.</p> <p>Given a string <code>s</code>, return <code>true</code><em> if it is a <strong>palindrome</strong>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;A man, a plan, a canal: Panama&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;amanaplanacanalpanama&quot; is a palindrome. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;race a car&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;raceacar&quot; is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot; &quot; <strong>Output:</strong> true <strong>Explanation:</strong> s is an empty string &quot;&quot; after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of printable ASCII characters.</li> </ul>
Two Pointers; String
Rust
impl Solution { pub fn is_palindrome(s: String) -> bool { let s = s.to_lowercase(); let s = s.as_bytes(); let n = s.len(); let (mut l, mut r) = (0, n - 1); while l < r { while l < r && !s[l].is_ascii_alphanumeric() { l += 1; } while l < r && !s[r].is_ascii_alphanumeric() { r -= 1; } if s[l] != s[r] { return false; } l += 1; if r != 0 { r -= 1; } } true } }
125
Valid Palindrome
Easy
<p>A phrase is a <strong>palindrome</strong> if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.</p> <p>Given a string <code>s</code>, return <code>true</code><em> if it is a <strong>palindrome</strong>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;A man, a plan, a canal: Panama&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;amanaplanacanalpanama&quot; is a palindrome. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;race a car&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;raceacar&quot; is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot; &quot; <strong>Output:</strong> true <strong>Explanation:</strong> s is an empty string &quot;&quot; after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of printable ASCII characters.</li> </ul>
Two Pointers; String
TypeScript
function isPalindrome(s: string): boolean { let i = 0; let j = s.length - 1; while (i < j) { if (!/[a-zA-Z0-9]/.test(s[i])) { ++i; } else if (!/[a-zA-Z0-9]/.test(s[j])) { --j; } else if (s[i].toLowerCase() !== s[j].toLowerCase()) { return false; } else { ++i; --j; } } return true; }
126
Word Ladder II
Hard
<p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> such that:</p> <ul> <li>Every adjacent pair of words differs by a single letter.</li> <li>Every <code>s<sub>i</sub></code> for <code>1 &lt;= i &lt;= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li> <li><code>s<sub>k</sub> == endWord</code></li> </ul> <p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>all the <strong>shortest transformation sequences</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words </em><code>[beginWord, s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub>]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] <strong>Output:</strong> [[&quot;hit&quot;,&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;cog&quot;],[&quot;hit&quot;,&quot;hot&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]] <strong>Explanation:</strong>&nbsp;There are 2 shortest transformation sequences: &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; &quot;cog&quot; &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;lot&quot; -&gt; &quot;log&quot; -&gt; &quot;cog&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;] <strong>Output:</strong> [] <strong>Explanation:</strong> The endWord &quot;cog&quot; is not in wordList, therefore there is no valid transformation sequence. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= beginWord.length &lt;= 5</code></li> <li><code>endWord.length == beginWord.length</code></li> <li><code>1 &lt;= wordList.length &lt;= 500</code></li> <li><code>wordList[i].length == beginWord.length</code></li> <li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li> <li><code>beginWord != endWord</code></li> <li>All the words in <code>wordList</code> are <strong>unique</strong>.</li> <li>The <strong>sum</strong> of all shortest transformation sequences does not exceed <code>10<sup>5</sup></code>.</li> </ul>
Breadth-First Search; Hash Table; String; Backtracking
Go
func findLadders(beginWord string, endWord string, wordList []string) [][]string { var ans [][]string words := make(map[string]bool) for _, word := range wordList { words[word] = true } if !words[endWord] { return ans } words[beginWord] = false dist := map[string]int{beginWord: 0} prev := map[string]map[string]bool{} q := []string{beginWord} found := false step := 0 for len(q) > 0 && !found { step++ for i := len(q); i > 0; i-- { p := q[0] q = q[1:] chars := []byte(p) for j := 0; j < len(chars); j++ { ch := chars[j] for k := 'a'; k <= 'z'; k++ { chars[j] = byte(k) t := string(chars) if v, ok := dist[t]; ok { if v == step { prev[t][p] = true } } if !words[t] { continue } if len(prev[t]) == 0 { prev[t] = make(map[string]bool) } prev[t][p] = true words[t] = false q = append(q, t) dist[t] = step if endWord == t { found = true } } chars[j] = ch } } } var dfs func(path []string, begin, cur string) dfs = func(path []string, begin, cur string) { if cur == beginWord { cp := make([]string, len(path)) copy(cp, path) ans = append(ans, cp) return } for k := range prev[cur] { path = append([]string{k}, path...) dfs(path, beginWord, k) path = path[1:] } } if found { path := []string{endWord} dfs(path, beginWord, endWord) } return ans }
126
Word Ladder II
Hard
<p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> such that:</p> <ul> <li>Every adjacent pair of words differs by a single letter.</li> <li>Every <code>s<sub>i</sub></code> for <code>1 &lt;= i &lt;= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li> <li><code>s<sub>k</sub> == endWord</code></li> </ul> <p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>all the <strong>shortest transformation sequences</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words </em><code>[beginWord, s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub>]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] <strong>Output:</strong> [[&quot;hit&quot;,&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;cog&quot;],[&quot;hit&quot;,&quot;hot&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]] <strong>Explanation:</strong>&nbsp;There are 2 shortest transformation sequences: &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; &quot;cog&quot; &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;lot&quot; -&gt; &quot;log&quot; -&gt; &quot;cog&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;] <strong>Output:</strong> [] <strong>Explanation:</strong> The endWord &quot;cog&quot; is not in wordList, therefore there is no valid transformation sequence. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= beginWord.length &lt;= 5</code></li> <li><code>endWord.length == beginWord.length</code></li> <li><code>1 &lt;= wordList.length &lt;= 500</code></li> <li><code>wordList[i].length == beginWord.length</code></li> <li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li> <li><code>beginWord != endWord</code></li> <li>All the words in <code>wordList</code> are <strong>unique</strong>.</li> <li>The <strong>sum</strong> of all shortest transformation sequences does not exceed <code>10<sup>5</sup></code>.</li> </ul>
Breadth-First Search; Hash Table; String; Backtracking
Java
class Solution { private List<List<String>> ans; private Map<String, Set<String>> prev; public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) { ans = new ArrayList<>(); Set<String> words = new HashSet<>(wordList); if (!words.contains(endWord)) { return ans; } words.remove(beginWord); Map<String, Integer> dist = new HashMap<>(); dist.put(beginWord, 0); prev = new HashMap<>(); Queue<String> q = new ArrayDeque<>(); q.offer(beginWord); boolean found = false; int step = 0; while (!q.isEmpty() && !found) { ++step; for (int i = q.size(); i > 0; --i) { String p = q.poll(); char[] chars = p.toCharArray(); for (int j = 0; j < chars.length; ++j) { char ch = chars[j]; for (char k = 'a'; k <= 'z'; ++k) { chars[j] = k; String t = new String(chars); if (dist.getOrDefault(t, 0) == step) { prev.get(t).add(p); } if (!words.contains(t)) { continue; } prev.computeIfAbsent(t, key -> new HashSet<>()).add(p); words.remove(t); q.offer(t); dist.put(t, step); if (endWord.equals(t)) { found = true; } } chars[j] = ch; } } } if (found) { Deque<String> path = new ArrayDeque<>(); path.add(endWord); dfs(path, beginWord, endWord); } return ans; } private void dfs(Deque<String> path, String beginWord, String cur) { if (cur.equals(beginWord)) { ans.add(new ArrayList<>(path)); return; } for (String precursor : prev.get(cur)) { path.addFirst(precursor); dfs(path, beginWord, precursor); path.removeFirst(); } } }
126
Word Ladder II
Hard
<p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> such that:</p> <ul> <li>Every adjacent pair of words differs by a single letter.</li> <li>Every <code>s<sub>i</sub></code> for <code>1 &lt;= i &lt;= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li> <li><code>s<sub>k</sub> == endWord</code></li> </ul> <p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>all the <strong>shortest transformation sequences</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words </em><code>[beginWord, s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub>]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] <strong>Output:</strong> [[&quot;hit&quot;,&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;cog&quot;],[&quot;hit&quot;,&quot;hot&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]] <strong>Explanation:</strong>&nbsp;There are 2 shortest transformation sequences: &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; &quot;cog&quot; &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;lot&quot; -&gt; &quot;log&quot; -&gt; &quot;cog&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;] <strong>Output:</strong> [] <strong>Explanation:</strong> The endWord &quot;cog&quot; is not in wordList, therefore there is no valid transformation sequence. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= beginWord.length &lt;= 5</code></li> <li><code>endWord.length == beginWord.length</code></li> <li><code>1 &lt;= wordList.length &lt;= 500</code></li> <li><code>wordList[i].length == beginWord.length</code></li> <li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li> <li><code>beginWord != endWord</code></li> <li>All the words in <code>wordList</code> are <strong>unique</strong>.</li> <li>The <strong>sum</strong> of all shortest transformation sequences does not exceed <code>10<sup>5</sup></code>.</li> </ul>
Breadth-First Search; Hash Table; String; Backtracking
Python
class Solution: def findLadders( self, beginWord: str, endWord: str, wordList: List[str] ) -> List[List[str]]: def dfs(path, cur): if cur == beginWord: ans.append(path[::-1]) return for precursor in prev[cur]: path.append(precursor) dfs(path, precursor) path.pop() ans = [] words = set(wordList) if endWord not in words: return ans words.discard(beginWord) dist = {beginWord: 0} prev = defaultdict(set) q = deque([beginWord]) found = False step = 0 while q and not found: step += 1 for i in range(len(q), 0, -1): p = q.popleft() s = list(p) for i in range(len(s)): ch = s[i] for j in range(26): s[i] = chr(ord('a') + j) t = ''.join(s) if dist.get(t, 0) == step: prev[t].add(p) if t not in words: continue prev[t].add(p) words.discard(t) q.append(t) dist[t] = step if endWord == t: found = True s[i] = ch if found: path = [endWord] dfs(path, endWord) return ans
127
Word Ladder
Hard
<p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> such that:</p> <ul> <li>Every adjacent pair of words differs by a single letter.</li> <li>Every <code>s<sub>i</sub></code> for <code>1 &lt;= i &lt;= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li> <li><code>s<sub>k</sub> == endWord</code></li> </ul> <p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>the <strong>number of words</strong> in the <strong>shortest transformation sequence</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or </em><code>0</code><em> if no such sequence exists.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] <strong>Output:</strong> 5 <strong>Explanation:</strong> One shortest transformation sequence is &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; cog&quot;, which is 5 words long. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;] <strong>Output:</strong> 0 <strong>Explanation:</strong> The endWord &quot;cog&quot; is not in wordList, therefore there is no valid transformation sequence. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= beginWord.length &lt;= 10</code></li> <li><code>endWord.length == beginWord.length</code></li> <li><code>1 &lt;= wordList.length &lt;= 5000</code></li> <li><code>wordList[i].length == beginWord.length</code></li> <li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li> <li><code>beginWord != endWord</code></li> <li>All the words in <code>wordList</code> are <strong>unique</strong>.</li> </ul>
Breadth-First Search; Hash Table; String
C++
class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> words(wordList.begin(), wordList.end()); queue<string> q{{beginWord}}; int ans = 1; while (!q.empty()) { ++ans; for (int i = q.size(); i > 0; --i) { string s = q.front(); q.pop(); for (int j = 0; j < s.size(); ++j) { char ch = s[j]; for (char k = 'a'; k <= 'z'; ++k) { s[j] = k; if (!words.count(s)) continue; if (s == endWord) return ans; q.push(s); words.erase(s); } s[j] = ch; } } } return 0; } };
127
Word Ladder
Hard
<p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> such that:</p> <ul> <li>Every adjacent pair of words differs by a single letter.</li> <li>Every <code>s<sub>i</sub></code> for <code>1 &lt;= i &lt;= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li> <li><code>s<sub>k</sub> == endWord</code></li> </ul> <p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>the <strong>number of words</strong> in the <strong>shortest transformation sequence</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or </em><code>0</code><em> if no such sequence exists.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] <strong>Output:</strong> 5 <strong>Explanation:</strong> One shortest transformation sequence is &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; cog&quot;, which is 5 words long. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;] <strong>Output:</strong> 0 <strong>Explanation:</strong> The endWord &quot;cog&quot; is not in wordList, therefore there is no valid transformation sequence. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= beginWord.length &lt;= 10</code></li> <li><code>endWord.length == beginWord.length</code></li> <li><code>1 &lt;= wordList.length &lt;= 5000</code></li> <li><code>wordList[i].length == beginWord.length</code></li> <li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li> <li><code>beginWord != endWord</code></li> <li>All the words in <code>wordList</code> are <strong>unique</strong>.</li> </ul>
Breadth-First Search; Hash Table; String
C#
using System.Collections; using System.Collections.Generic; using System.Linq; public class Solution { public int LadderLength(string beginWord, string endWord, IList<string> wordList) { var words = Enumerable.Repeat(beginWord, 1).Concat(wordList).Select((word, i) => new { Word = word, Index = i }).ToList(); var endWordIndex = words.Find(w => w.Word == endWord)?.Index; if (endWordIndex == null) { return 0; } var paths = new List<int>[words.Count]; for (var i = 0; i < paths.Length; ++i) { paths[i] = new List<int>(); } for (var i = 0; i < beginWord.Length; ++i) { var hashMap = new Hashtable(); foreach (var item in words) { var newWord = string.Format("{0}_{1}", item.Word.Substring(0, i), item.Word.Substring(i + 1)); List<int> similars; if (!hashMap.ContainsKey(newWord)) { similars = new List<int>(); hashMap.Add(newWord, similars); } else { similars = (List<int>)hashMap[newWord]; } foreach (var similar in similars) { paths[similar].Add(item.Index); paths[item.Index].Add(similar); } similars.Add(item.Index); } } var left = words.Count - 1; var lastRound = new List<int> { 0 }; var visited = new bool[words.Count]; visited[0] = true; for (var result = 2; left > 0; ++result) { var thisRound = new List<int>(); foreach (var index in lastRound) { foreach (var next in paths[index]) { if (!visited[next]) { visited[next] = true; if (next == endWordIndex) return result; thisRound.Add(next); } } } if (thisRound.Count == 0) break; lastRound = thisRound; } return 0; } }
127
Word Ladder
Hard
<p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> such that:</p> <ul> <li>Every adjacent pair of words differs by a single letter.</li> <li>Every <code>s<sub>i</sub></code> for <code>1 &lt;= i &lt;= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li> <li><code>s<sub>k</sub> == endWord</code></li> </ul> <p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>the <strong>number of words</strong> in the <strong>shortest transformation sequence</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or </em><code>0</code><em> if no such sequence exists.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] <strong>Output:</strong> 5 <strong>Explanation:</strong> One shortest transformation sequence is &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; cog&quot;, which is 5 words long. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;] <strong>Output:</strong> 0 <strong>Explanation:</strong> The endWord &quot;cog&quot; is not in wordList, therefore there is no valid transformation sequence. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= beginWord.length &lt;= 10</code></li> <li><code>endWord.length == beginWord.length</code></li> <li><code>1 &lt;= wordList.length &lt;= 5000</code></li> <li><code>wordList[i].length == beginWord.length</code></li> <li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li> <li><code>beginWord != endWord</code></li> <li>All the words in <code>wordList</code> are <strong>unique</strong>.</li> </ul>
Breadth-First Search; Hash Table; String
Go
func ladderLength(beginWord string, endWord string, wordList []string) int { words := make(map[string]bool) for _, word := range wordList { words[word] = true } q := []string{beginWord} ans := 1 for len(q) > 0 { ans++ for i := len(q); i > 0; i-- { s := q[0] q = q[1:] chars := []byte(s) for j := 0; j < len(chars); j++ { ch := chars[j] for k := 'a'; k <= 'z'; k++ { chars[j] = byte(k) t := string(chars) if !words[t] { continue } if t == endWord { return ans } q = append(q, t) words[t] = false } chars[j] = ch } } } return 0 }