id
int64
1
3.65k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
249
Group Shifted Strings
Medium
<p>Perform the following shift operations on a string:</p> <ul> <li><strong>Right shift</strong>: Replace every letter with the <strong>successive</strong> letter of the English alphabet, where &#39;z&#39; is replaced by &#39;a&#39;. For example, <code>&quot;abc&quot;</code> can be right-shifted to <code>&quot;bcd&quot; </code>or <code>&quot;xyz&quot;</code> can be right-shifted to <code>&quot;yza&quot;</code>.</li> <li><strong>Left shift</strong>: Replace every letter with the <strong>preceding</strong> letter of the English alphabet, where &#39;a&#39; is replaced by &#39;z&#39;. For example, <code>&quot;bcd&quot;</code> can be left-shifted to <code>&quot;abc&quot;<font face="Times New Roman"> or </font></code><code>&quot;yza&quot;</code> can be left-shifted to <code>&quot;xyz&quot;</code>.</li> </ul> <p>We can keep shifting the string in both directions to form an <strong>endless</strong> <strong>shifting sequence</strong>.</p> <ul> <li>For example, shift <code>&quot;abc&quot;</code> to form the sequence: <code>... &lt;-&gt; &quot;abc&quot; &lt;-&gt; &quot;bcd&quot; &lt;-&gt; ... &lt;-&gt; &quot;xyz&quot; &lt;-&gt; &quot;yza&quot; &lt;-&gt; ...</code>.<code> &lt;-&gt; &quot;zab&quot; &lt;-&gt; &quot;abc&quot; &lt;-&gt; ...</code></li> </ul> <p>You are given an array of strings <code>strings</code>, group together all <code>strings[i]</code> that belong to the same shifting sequence. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strings = [&quot;abc&quot;,&quot;bcd&quot;,&quot;acef&quot;,&quot;xyz&quot;,&quot;az&quot;,&quot;ba&quot;,&quot;a&quot;,&quot;z&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;acef&quot;],[&quot;a&quot;,&quot;z&quot;],[&quot;abc&quot;,&quot;bcd&quot;,&quot;xyz&quot;],[&quot;az&quot;,&quot;ba&quot;]]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strings = [&quot;a&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;a&quot;]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strings.length &lt;= 200</code></li> <li><code>1 &lt;= strings[i].length &lt;= 50</code></li> <li><code>strings[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; String
Go
func groupStrings(strings []string) [][]string { g := make(map[string][]string) for _, s := range strings { t := []byte(s) diff := t[0] - 'a' for i := range t { t[i] -= diff if t[i] < 'a' { t[i] += 26 } } g[string(t)] = append(g[string(t)], s) } ans := make([][]string, 0, len(g)) for _, v := range g { ans = append(ans, v) } return ans }
249
Group Shifted Strings
Medium
<p>Perform the following shift operations on a string:</p> <ul> <li><strong>Right shift</strong>: Replace every letter with the <strong>successive</strong> letter of the English alphabet, where &#39;z&#39; is replaced by &#39;a&#39;. For example, <code>&quot;abc&quot;</code> can be right-shifted to <code>&quot;bcd&quot; </code>or <code>&quot;xyz&quot;</code> can be right-shifted to <code>&quot;yza&quot;</code>.</li> <li><strong>Left shift</strong>: Replace every letter with the <strong>preceding</strong> letter of the English alphabet, where &#39;a&#39; is replaced by &#39;z&#39;. For example, <code>&quot;bcd&quot;</code> can be left-shifted to <code>&quot;abc&quot;<font face="Times New Roman"> or </font></code><code>&quot;yza&quot;</code> can be left-shifted to <code>&quot;xyz&quot;</code>.</li> </ul> <p>We can keep shifting the string in both directions to form an <strong>endless</strong> <strong>shifting sequence</strong>.</p> <ul> <li>For example, shift <code>&quot;abc&quot;</code> to form the sequence: <code>... &lt;-&gt; &quot;abc&quot; &lt;-&gt; &quot;bcd&quot; &lt;-&gt; ... &lt;-&gt; &quot;xyz&quot; &lt;-&gt; &quot;yza&quot; &lt;-&gt; ...</code>.<code> &lt;-&gt; &quot;zab&quot; &lt;-&gt; &quot;abc&quot; &lt;-&gt; ...</code></li> </ul> <p>You are given an array of strings <code>strings</code>, group together all <code>strings[i]</code> that belong to the same shifting sequence. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strings = [&quot;abc&quot;,&quot;bcd&quot;,&quot;acef&quot;,&quot;xyz&quot;,&quot;az&quot;,&quot;ba&quot;,&quot;a&quot;,&quot;z&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;acef&quot;],[&quot;a&quot;,&quot;z&quot;],[&quot;abc&quot;,&quot;bcd&quot;,&quot;xyz&quot;],[&quot;az&quot;,&quot;ba&quot;]]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strings = [&quot;a&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;a&quot;]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strings.length &lt;= 200</code></li> <li><code>1 &lt;= strings[i].length &lt;= 50</code></li> <li><code>strings[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; String
Java
class Solution { public List<List<String>> groupStrings(String[] strings) { Map<String, List<String>> g = new HashMap<>(); for (var s : strings) { char[] t = s.toCharArray(); int diff = t[0] - 'a'; for (int i = 0; i < t.length; ++i) { t[i] = (char) (t[i] - diff); if (t[i] < 'a') { t[i] += 26; } } g.computeIfAbsent(new String(t), k -> new ArrayList<>()).add(s); } return new ArrayList<>(g.values()); } }
249
Group Shifted Strings
Medium
<p>Perform the following shift operations on a string:</p> <ul> <li><strong>Right shift</strong>: Replace every letter with the <strong>successive</strong> letter of the English alphabet, where &#39;z&#39; is replaced by &#39;a&#39;. For example, <code>&quot;abc&quot;</code> can be right-shifted to <code>&quot;bcd&quot; </code>or <code>&quot;xyz&quot;</code> can be right-shifted to <code>&quot;yza&quot;</code>.</li> <li><strong>Left shift</strong>: Replace every letter with the <strong>preceding</strong> letter of the English alphabet, where &#39;a&#39; is replaced by &#39;z&#39;. For example, <code>&quot;bcd&quot;</code> can be left-shifted to <code>&quot;abc&quot;<font face="Times New Roman"> or </font></code><code>&quot;yza&quot;</code> can be left-shifted to <code>&quot;xyz&quot;</code>.</li> </ul> <p>We can keep shifting the string in both directions to form an <strong>endless</strong> <strong>shifting sequence</strong>.</p> <ul> <li>For example, shift <code>&quot;abc&quot;</code> to form the sequence: <code>... &lt;-&gt; &quot;abc&quot; &lt;-&gt; &quot;bcd&quot; &lt;-&gt; ... &lt;-&gt; &quot;xyz&quot; &lt;-&gt; &quot;yza&quot; &lt;-&gt; ...</code>.<code> &lt;-&gt; &quot;zab&quot; &lt;-&gt; &quot;abc&quot; &lt;-&gt; ...</code></li> </ul> <p>You are given an array of strings <code>strings</code>, group together all <code>strings[i]</code> that belong to the same shifting sequence. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strings = [&quot;abc&quot;,&quot;bcd&quot;,&quot;acef&quot;,&quot;xyz&quot;,&quot;az&quot;,&quot;ba&quot;,&quot;a&quot;,&quot;z&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;acef&quot;],[&quot;a&quot;,&quot;z&quot;],[&quot;abc&quot;,&quot;bcd&quot;,&quot;xyz&quot;],[&quot;az&quot;,&quot;ba&quot;]]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">strings = [&quot;a&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[[&quot;a&quot;]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strings.length &lt;= 200</code></li> <li><code>1 &lt;= strings[i].length &lt;= 50</code></li> <li><code>strings[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; String
Python
class Solution: def groupStrings(self, strings: List[str]) -> List[List[str]]: g = defaultdict(list) for s in strings: diff = ord(s[0]) - ord("a") t = [] for c in s: c = ord(c) - diff if c < ord("a"): c += 26 t.append(chr(c)) g["".join(t)].append(s) return list(g.values())
250
Count Univalue Subtrees
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the number of <strong>uni-value</strong> </em><span data-keyword="subtree"><em>subtrees</em></span>.</p> <p>A <strong>uni-value subtree</strong> means all nodes of the subtree have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0250.Count%20Univalue%20Subtrees/images/unival_e1.jpg" style="width: 450px; height: 258px;" /> <pre> <strong>Input:</strong> root = [5,1,5,5,5,null,5] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [5,5,5,5,5,null,5] <strong>Output:</strong> 6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the node in the tree will be in the range <code>[0, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int countUnivalSubtrees(TreeNode* root) { int ans = 0; function<bool(TreeNode*)> dfs = [&](TreeNode* root) -> bool { if (!root) { return true; } bool l = dfs(root->left); bool r = dfs(root->right); if (!l || !r) { return false; } int a = root->left ? root->left->val : root->val; int b = root->right ? root->right->val : root->val; if (a == b && b == root->val) { ++ans; return true; } return false; }; dfs(root); return ans; } };
250
Count Univalue Subtrees
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the number of <strong>uni-value</strong> </em><span data-keyword="subtree"><em>subtrees</em></span>.</p> <p>A <strong>uni-value subtree</strong> means all nodes of the subtree have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0250.Count%20Univalue%20Subtrees/images/unival_e1.jpg" style="width: 450px; height: 258px;" /> <pre> <strong>Input:</strong> root = [5,1,5,5,5,null,5] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [5,5,5,5,5,null,5] <strong>Output:</strong> 6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the node in the tree will be in the range <code>[0, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func countUnivalSubtrees(root *TreeNode) (ans int) { var dfs func(*TreeNode) bool dfs = func(root *TreeNode) bool { if root == nil { return true } l, r := dfs(root.Left), dfs(root.Right) if !l || !r { return false } if root.Left != nil && root.Left.Val != root.Val { return false } if root.Right != nil && root.Right.Val != root.Val { return false } ans++ return true } dfs(root) return }
250
Count Univalue Subtrees
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the number of <strong>uni-value</strong> </em><span data-keyword="subtree"><em>subtrees</em></span>.</p> <p>A <strong>uni-value subtree</strong> means all nodes of the subtree have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0250.Count%20Univalue%20Subtrees/images/unival_e1.jpg" style="width: 450px; height: 258px;" /> <pre> <strong>Input:</strong> root = [5,1,5,5,5,null,5] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [5,5,5,5,5,null,5] <strong>Output:</strong> 6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the node in the tree will be in the range <code>[0, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int ans; public int countUnivalSubtrees(TreeNode root) { dfs(root); return ans; } private boolean dfs(TreeNode root) { if (root == null) { return true; } boolean l = dfs(root.left); boolean r = dfs(root.right); if (!l || !r) { return false; } int a = root.left == null ? root.val : root.left.val; int b = root.right == null ? root.val : root.right.val; if (a == b && b == root.val) { ++ans; return true; } return false; } }
250
Count Univalue Subtrees
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the number of <strong>uni-value</strong> </em><span data-keyword="subtree"><em>subtrees</em></span>.</p> <p>A <strong>uni-value subtree</strong> means all nodes of the subtree have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0250.Count%20Univalue%20Subtrees/images/unival_e1.jpg" style="width: 450px; height: 258px;" /> <pre> <strong>Input:</strong> root = [5,1,5,5,5,null,5] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [5,5,5,5,5,null,5] <strong>Output:</strong> 6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the node in the tree will be in the range <code>[0, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var countUnivalSubtrees = function (root) { let ans = 0; const dfs = root => { if (!root) { return true; } const l = dfs(root.left); const r = dfs(root.right); if (!l || !r) { return false; } if (root.left && root.left.val !== root.val) { return false; } if (root.right && root.right.val !== root.val) { return false; } ++ans; return true; }; dfs(root); return ans; };
250
Count Univalue Subtrees
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the number of <strong>uni-value</strong> </em><span data-keyword="subtree"><em>subtrees</em></span>.</p> <p>A <strong>uni-value subtree</strong> means all nodes of the subtree have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0250.Count%20Univalue%20Subtrees/images/unival_e1.jpg" style="width: 450px; height: 258px;" /> <pre> <strong>Input:</strong> root = [5,1,5,5,5,null,5] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [5,5,5,5,5,null,5] <strong>Output:</strong> 6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the node in the tree will be in the range <code>[0, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def countUnivalSubtrees(self, root: Optional[TreeNode]) -> int: def dfs(root): if root is None: return True l, r = dfs(root.left), dfs(root.right) if not l or not r: return False a = root.val if root.left is None else root.left.val b = root.val if root.right is None else root.right.val if a == b == root.val: nonlocal ans ans += 1 return True return False ans = 0 dfs(root) return ans
250
Count Univalue Subtrees
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the number of <strong>uni-value</strong> </em><span data-keyword="subtree"><em>subtrees</em></span>.</p> <p>A <strong>uni-value subtree</strong> means all nodes of the subtree have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0250.Count%20Univalue%20Subtrees/images/unival_e1.jpg" style="width: 450px; height: 258px;" /> <pre> <strong>Input:</strong> root = [5,1,5,5,5,null,5] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [5,5,5,5,5,null,5] <strong>Output:</strong> 6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the node in the tree will be in the range <code>[0, 1000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function countUnivalSubtrees(root: TreeNode | null): number { let ans: number = 0; const dfs = (root: TreeNode | null): boolean => { if (root == null) { return true; } const l: boolean = dfs(root.left); const r: boolean = dfs(root.right); if (!l || !r) { return false; } if (root.left != null && root.left.val != root.val) { return false; } if (root.right != null && root.right.val != root.val) { return false; } ++ans; return true; }; dfs(root); return ans; }
251
Flatten 2D Vector
Medium
<p>Design an iterator to flatten a 2D vector. It should support the <code>next</code> and <code>hasNext</code> operations.</p> <p>Implement the <code>Vector2D</code> class:</p> <ul> <li><code>Vector2D(int[][] vec)</code> initializes the object with the 2D vector <code>vec</code>.</li> <li><code>next()</code> returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to <code>next</code> are valid.</li> <li><code>hasNext()</code> returns <code>true</code> if there are still some elements in the vector, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Vector2D&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[[1, 2], [3], [4]]], [], [], [], [], [], [], []] <strong>Output</strong> [null, 1, 2, 3, true, true, 4, false] <strong>Explanation</strong> Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]); vector2D.next(); // return 1 vector2D.next(); // return 2 vector2D.next(); // return 3 vector2D.hasNext(); // return True vector2D.hasNext(); // return True vector2D.next(); // return 4 vector2D.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= vec.length &lt;= 200</code></li> <li><code>0 &lt;= vec[i].length &lt;= 500</code></li> <li><code>-500 &lt;= vec[i][j] &lt;= 500</code></li> <li>At most <code>10<sup>5</sup></code> calls will be made to <code>next</code> and <code>hasNext</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> As an added challenge, try to code it using only <a href="http://www.cplusplus.com/reference/iterator/iterator/" target="_blank">iterators in C++</a> or <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html" target="_blank">iterators in Java</a>.</p>
Design; Array; Two Pointers; Iterator
C++
class Vector2D { public: Vector2D(vector<vector<int>>& vec) { this->vec = move(vec); } int next() { forward(); return vec[i][j++]; } bool hasNext() { forward(); return i < vec.size(); } private: int i = 0; int j = 0; vector<vector<int>> vec; void forward() { while (i < vec.size() && j >= vec[i].size()) { ++i; j = 0; } } }; /** * Your Vector2D object will be instantiated and called as such: * Vector2D* obj = new Vector2D(vec); * int param_1 = obj->next(); * bool param_2 = obj->hasNext(); */
251
Flatten 2D Vector
Medium
<p>Design an iterator to flatten a 2D vector. It should support the <code>next</code> and <code>hasNext</code> operations.</p> <p>Implement the <code>Vector2D</code> class:</p> <ul> <li><code>Vector2D(int[][] vec)</code> initializes the object with the 2D vector <code>vec</code>.</li> <li><code>next()</code> returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to <code>next</code> are valid.</li> <li><code>hasNext()</code> returns <code>true</code> if there are still some elements in the vector, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Vector2D&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[[1, 2], [3], [4]]], [], [], [], [], [], [], []] <strong>Output</strong> [null, 1, 2, 3, true, true, 4, false] <strong>Explanation</strong> Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]); vector2D.next(); // return 1 vector2D.next(); // return 2 vector2D.next(); // return 3 vector2D.hasNext(); // return True vector2D.hasNext(); // return True vector2D.next(); // return 4 vector2D.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= vec.length &lt;= 200</code></li> <li><code>0 &lt;= vec[i].length &lt;= 500</code></li> <li><code>-500 &lt;= vec[i][j] &lt;= 500</code></li> <li>At most <code>10<sup>5</sup></code> calls will be made to <code>next</code> and <code>hasNext</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> As an added challenge, try to code it using only <a href="http://www.cplusplus.com/reference/iterator/iterator/" target="_blank">iterators in C++</a> or <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html" target="_blank">iterators in Java</a>.</p>
Design; Array; Two Pointers; Iterator
Go
type Vector2D struct { i, j int vec [][]int } func Constructor(vec [][]int) Vector2D { return Vector2D{vec: vec} } func (this *Vector2D) Next() int { this.forward() ans := this.vec[this.i][this.j] this.j++ return ans } func (this *Vector2D) HasNext() bool { this.forward() return this.i < len(this.vec) } func (this *Vector2D) forward() { for this.i < len(this.vec) && this.j >= len(this.vec[this.i]) { this.i++ this.j = 0 } } /** * Your Vector2D object will be instantiated and called as such: * obj := Constructor(vec); * param_1 := obj.Next(); * param_2 := obj.HasNext(); */
251
Flatten 2D Vector
Medium
<p>Design an iterator to flatten a 2D vector. It should support the <code>next</code> and <code>hasNext</code> operations.</p> <p>Implement the <code>Vector2D</code> class:</p> <ul> <li><code>Vector2D(int[][] vec)</code> initializes the object with the 2D vector <code>vec</code>.</li> <li><code>next()</code> returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to <code>next</code> are valid.</li> <li><code>hasNext()</code> returns <code>true</code> if there are still some elements in the vector, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Vector2D&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[[1, 2], [3], [4]]], [], [], [], [], [], [], []] <strong>Output</strong> [null, 1, 2, 3, true, true, 4, false] <strong>Explanation</strong> Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]); vector2D.next(); // return 1 vector2D.next(); // return 2 vector2D.next(); // return 3 vector2D.hasNext(); // return True vector2D.hasNext(); // return True vector2D.next(); // return 4 vector2D.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= vec.length &lt;= 200</code></li> <li><code>0 &lt;= vec[i].length &lt;= 500</code></li> <li><code>-500 &lt;= vec[i][j] &lt;= 500</code></li> <li>At most <code>10<sup>5</sup></code> calls will be made to <code>next</code> and <code>hasNext</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> As an added challenge, try to code it using only <a href="http://www.cplusplus.com/reference/iterator/iterator/" target="_blank">iterators in C++</a> or <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html" target="_blank">iterators in Java</a>.</p>
Design; Array; Two Pointers; Iterator
Java
class Vector2D { private int i; private int j; private int[][] vec; public Vector2D(int[][] vec) { this.vec = vec; } public int next() { forward(); return vec[i][j++]; } public boolean hasNext() { forward(); return i < vec.length; } private void forward() { while (i < vec.length && j >= vec[i].length) { ++i; j = 0; } } } /** * Your Vector2D object will be instantiated and called as such: * Vector2D obj = new Vector2D(vec); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */
251
Flatten 2D Vector
Medium
<p>Design an iterator to flatten a 2D vector. It should support the <code>next</code> and <code>hasNext</code> operations.</p> <p>Implement the <code>Vector2D</code> class:</p> <ul> <li><code>Vector2D(int[][] vec)</code> initializes the object with the 2D vector <code>vec</code>.</li> <li><code>next()</code> returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to <code>next</code> are valid.</li> <li><code>hasNext()</code> returns <code>true</code> if there are still some elements in the vector, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Vector2D&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[[1, 2], [3], [4]]], [], [], [], [], [], [], []] <strong>Output</strong> [null, 1, 2, 3, true, true, 4, false] <strong>Explanation</strong> Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]); vector2D.next(); // return 1 vector2D.next(); // return 2 vector2D.next(); // return 3 vector2D.hasNext(); // return True vector2D.hasNext(); // return True vector2D.next(); // return 4 vector2D.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= vec.length &lt;= 200</code></li> <li><code>0 &lt;= vec[i].length &lt;= 500</code></li> <li><code>-500 &lt;= vec[i][j] &lt;= 500</code></li> <li>At most <code>10<sup>5</sup></code> calls will be made to <code>next</code> and <code>hasNext</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> As an added challenge, try to code it using only <a href="http://www.cplusplus.com/reference/iterator/iterator/" target="_blank">iterators in C++</a> or <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html" target="_blank">iterators in Java</a>.</p>
Design; Array; Two Pointers; Iterator
Python
class Vector2D: def __init__(self, vec: List[List[int]]): self.i = 0 self.j = 0 self.vec = vec def next(self) -> int: self.forward() ans = self.vec[self.i][self.j] self.j += 1 return ans def hasNext(self) -> bool: self.forward() return self.i < len(self.vec) def forward(self): while self.i < len(self.vec) and self.j >= len(self.vec[self.i]): self.i += 1 self.j = 0 # Your Vector2D object will be instantiated and called as such: # obj = Vector2D(vec) # param_1 = obj.next() # param_2 = obj.hasNext()
251
Flatten 2D Vector
Medium
<p>Design an iterator to flatten a 2D vector. It should support the <code>next</code> and <code>hasNext</code> operations.</p> <p>Implement the <code>Vector2D</code> class:</p> <ul> <li><code>Vector2D(int[][] vec)</code> initializes the object with the 2D vector <code>vec</code>.</li> <li><code>next()</code> returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to <code>next</code> are valid.</li> <li><code>hasNext()</code> returns <code>true</code> if there are still some elements in the vector, and <code>false</code> otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Vector2D&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[[1, 2], [3], [4]]], [], [], [], [], [], [], []] <strong>Output</strong> [null, 1, 2, 3, true, true, 4, false] <strong>Explanation</strong> Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]); vector2D.next(); // return 1 vector2D.next(); // return 2 vector2D.next(); // return 3 vector2D.hasNext(); // return True vector2D.hasNext(); // return True vector2D.next(); // return 4 vector2D.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= vec.length &lt;= 200</code></li> <li><code>0 &lt;= vec[i].length &lt;= 500</code></li> <li><code>-500 &lt;= vec[i][j] &lt;= 500</code></li> <li>At most <code>10<sup>5</sup></code> calls will be made to <code>next</code> and <code>hasNext</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> As an added challenge, try to code it using only <a href="http://www.cplusplus.com/reference/iterator/iterator/" target="_blank">iterators in C++</a> or <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html" target="_blank">iterators in Java</a>.</p>
Design; Array; Two Pointers; Iterator
TypeScript
class Vector2D { i: number; j: number; vec: number[][]; constructor(vec: number[][]) { this.i = 0; this.j = 0; this.vec = vec; } next(): number { this.forward(); return this.vec[this.i][this.j++]; } hasNext(): boolean { this.forward(); return this.i < this.vec.length; } forward(): void { while (this.i < this.vec.length && this.j >= this.vec[this.i].length) { ++this.i; this.j = 0; } } } /** * Your Vector2D object will be instantiated and called as such: * var obj = new Vector2D(vec) * var param_1 = obj.next() * var param_2 = obj.hasNext() */
252
Meeting Rooms
Easy
<p>Given an array of meeting time <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, determine if a person could attend all meetings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]] <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> intervals = [[7,10],[2,4]] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;&nbsp;end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> </ul>
Array; Sorting
C++
class Solution { public: bool canAttendMeetings(vector<vector<int>>& intervals) { ranges::sort(intervals, [](const auto& a, const auto& b) { return a[0] < b[0]; }); for (int i = 1; i < intervals.size(); ++i) { if (intervals[i - 1][1] > intervals[i][0]) { return false; } } return true; } };
252
Meeting Rooms
Easy
<p>Given an array of meeting time <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, determine if a person could attend all meetings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]] <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> intervals = [[7,10],[2,4]] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;&nbsp;end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> </ul>
Array; Sorting
Go
func canAttendMeetings(intervals [][]int) bool { sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] }) for i := 1; i < len(intervals); i++ { if intervals[i][0] < intervals[i-1][1] { return false } } return true }
252
Meeting Rooms
Easy
<p>Given an array of meeting time <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, determine if a person could attend all meetings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]] <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> intervals = [[7,10],[2,4]] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;&nbsp;end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> </ul>
Array; Sorting
Java
class Solution { public boolean canAttendMeetings(int[][] intervals) { Arrays.sort(intervals, (a, b) -> a[0] - b[0]); for (int i = 1; i < intervals.length; ++i) { if (intervals[i - 1][1] > intervals[i][0]) { return false; } } return true; } }
252
Meeting Rooms
Easy
<p>Given an array of meeting time <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, determine if a person could attend all meetings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]] <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> intervals = [[7,10],[2,4]] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;&nbsp;end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> </ul>
Array; Sorting
Python
class Solution: def canAttendMeetings(self, intervals: List[List[int]]) -> bool: intervals.sort() return all(a[1] <= b[0] for a, b in pairwise(intervals))
252
Meeting Rooms
Easy
<p>Given an array of meeting time <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, determine if a person could attend all meetings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]] <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> intervals = [[7,10],[2,4]] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;&nbsp;end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> </ul>
Array; Sorting
Rust
impl Solution { pub fn can_attend_meetings(mut intervals: Vec<Vec<i32>>) -> bool { intervals.sort_by(|a, b| a[0].cmp(&b[0])); for i in 1..intervals.len() { if intervals[i - 1][1] > intervals[i][0] { return false; } } true } }
252
Meeting Rooms
Easy
<p>Given an array of meeting time <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, determine if a person could attend all meetings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]] <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> intervals = [[7,10],[2,4]] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;&nbsp;end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> </ul>
Array; Sorting
TypeScript
function canAttendMeetings(intervals: number[][]): boolean { intervals.sort((a, b) => a[0] - b[0]); for (let i = 1; i < intervals.length; ++i) { if (intervals[i][0] < intervals[i - 1][1]) { return false; } } return true; }
253
Meeting Rooms II
Medium
<p>Given an array of meeting time intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of conference rooms required</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> intervals = [[7,10],[2,4]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Two Pointers; Prefix Sum; Sorting; Heap (Priority Queue)
C++
class Solution { public: int minMeetingRooms(vector<vector<int>>& intervals) { int m = 0; for (const auto& e : intervals) { m = max(m, e[1]); } vector<int> d(m + 1); for (const auto& e : intervals) { d[e[0]]++; d[e[1]]--; } int ans = 0, s = 0; for (int v : d) { s += v; ans = max(ans, s); } return ans; } };
253
Meeting Rooms II
Medium
<p>Given an array of meeting time intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of conference rooms required</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> intervals = [[7,10],[2,4]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Two Pointers; Prefix Sum; Sorting; Heap (Priority Queue)
Go
func minMeetingRooms(intervals [][]int) (ans int) { m := 0 for _, e := range intervals { m = max(m, e[1]) } d := make([]int, m+1) for _, e := range intervals { d[e[0]]++ d[e[1]]-- } s := 0 for _, v := range d { s += v ans = max(ans, s) } return }
253
Meeting Rooms II
Medium
<p>Given an array of meeting time intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of conference rooms required</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> intervals = [[7,10],[2,4]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Two Pointers; Prefix Sum; Sorting; Heap (Priority Queue)
Java
class Solution { public int minMeetingRooms(int[][] intervals) { int m = 0; for (var e : intervals) { m = Math.max(m, e[1]); } int[] d = new int[m + 1]; for (var e : intervals) { ++d[e[0]]; --d[e[1]]; } int ans = 0, s = 0; for (int v : d) { s += v; ans = Math.max(ans, s); } return ans; } }
253
Meeting Rooms II
Medium
<p>Given an array of meeting time intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of conference rooms required</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> intervals = [[7,10],[2,4]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Two Pointers; Prefix Sum; Sorting; Heap (Priority Queue)
Python
class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: m = max(e[1] for e in intervals) d = [0] * (m + 1) for l, r in intervals: d[l] += 1 d[r] -= 1 ans = s = 0 for v in d: s += v ans = max(ans, s) return ans
253
Meeting Rooms II
Medium
<p>Given an array of meeting time intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of conference rooms required</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> intervals = [[7,10],[2,4]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Two Pointers; Prefix Sum; Sorting; Heap (Priority Queue)
Rust
impl Solution { pub fn min_meeting_rooms(intervals: Vec<Vec<i32>>) -> i32 { let mut m = 0; for e in &intervals { m = m.max(e[1]); } let mut d = vec![0; (m + 1) as usize]; for e in intervals { d[e[0] as usize] += 1; d[e[1] as usize] -= 1; } let mut ans = 0; let mut s = 0; for v in d { s += v; ans = ans.max(s); } ans } }
253
Meeting Rooms II
Medium
<p>Given an array of meeting time intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of conference rooms required</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]] <strong>Output:</strong> 2 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> intervals = [[7,10],[2,4]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;intervals.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Two Pointers; Prefix Sum; Sorting; Heap (Priority Queue)
TypeScript
function minMeetingRooms(intervals: number[][]): number { const m = Math.max(...intervals.map(([_, r]) => r)); const d: number[] = Array(m + 1).fill(0); for (const [l, r] of intervals) { d[l]++; d[r]--; } let [ans, s] = [0, 0]; for (const v of d) { s += v; ans = Math.max(ans, s); } return ans; }
254
Factor Combinations
Medium
<p>Numbers can be regarded as the product of their factors.</p> <ul> <li>For example, <code>8 = 2 x 2 x 2 = 2 x 4</code>.</li> </ul> <p>Given an integer <code>n</code>, return <em>all possible combinations of its factors</em>. You may return the answer in <strong>any order</strong>.</p> <p><strong>Note</strong> that the factors should be in the range <code>[2, n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 12 <strong>Output:</strong> [[2,6],[3,4],[2,2,3]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 37 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>7</sup></code></li> </ul>
Backtracking
C++
class Solution { public: vector<vector<int>> getFactors(int n) { vector<int> t; vector<vector<int>> ans; function<void(int, int)> dfs = [&](int n, int i) { if (t.size()) { vector<int> cp = t; cp.emplace_back(n); ans.emplace_back(cp); } for (int j = i; j <= n / j; ++j) { if (n % j == 0) { t.emplace_back(j); dfs(n / j, j); t.pop_back(); } } }; dfs(n, 2); return ans; } };
254
Factor Combinations
Medium
<p>Numbers can be regarded as the product of their factors.</p> <ul> <li>For example, <code>8 = 2 x 2 x 2 = 2 x 4</code>.</li> </ul> <p>Given an integer <code>n</code>, return <em>all possible combinations of its factors</em>. You may return the answer in <strong>any order</strong>.</p> <p><strong>Note</strong> that the factors should be in the range <code>[2, n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 12 <strong>Output:</strong> [[2,6],[3,4],[2,2,3]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 37 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>7</sup></code></li> </ul>
Backtracking
Go
func getFactors(n int) [][]int { t := []int{} ans := [][]int{} var dfs func(n, i int) dfs = func(n, i int) { if len(t) > 0 { ans = append(ans, append(slices.Clone(t), n)) } for j := i; j <= n/j; j++ { if n%j == 0 { t = append(t, j) dfs(n/j, j) t = t[:len(t)-1] } } } dfs(n, 2) return ans }
254
Factor Combinations
Medium
<p>Numbers can be regarded as the product of their factors.</p> <ul> <li>For example, <code>8 = 2 x 2 x 2 = 2 x 4</code>.</li> </ul> <p>Given an integer <code>n</code>, return <em>all possible combinations of its factors</em>. You may return the answer in <strong>any order</strong>.</p> <p><strong>Note</strong> that the factors should be in the range <code>[2, n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 12 <strong>Output:</strong> [[2,6],[3,4],[2,2,3]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 37 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>7</sup></code></li> </ul>
Backtracking
Java
class Solution { private List<Integer> t = new ArrayList<>(); private List<List<Integer>> ans = new ArrayList<>(); public List<List<Integer>> getFactors(int n) { dfs(n, 2); return ans; } private void dfs(int n, int i) { if (!t.isEmpty()) { List<Integer> cp = new ArrayList<>(t); cp.add(n); ans.add(cp); } for (int j = i; j <= n / j; ++j) { if (n % j == 0) { t.add(j); dfs(n / j, j); t.remove(t.size() - 1); } } } }
254
Factor Combinations
Medium
<p>Numbers can be regarded as the product of their factors.</p> <ul> <li>For example, <code>8 = 2 x 2 x 2 = 2 x 4</code>.</li> </ul> <p>Given an integer <code>n</code>, return <em>all possible combinations of its factors</em>. You may return the answer in <strong>any order</strong>.</p> <p><strong>Note</strong> that the factors should be in the range <code>[2, n - 1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 12 <strong>Output:</strong> [[2,6],[3,4],[2,2,3]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 37 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>7</sup></code></li> </ul>
Backtracking
Python
class Solution: def getFactors(self, n: int) -> List[List[int]]: def dfs(n, i): if t: ans.append(t + [n]) j = i while j * j <= n: if n % j == 0: t.append(j) dfs(n // j, j) t.pop() j += 1 t = [] ans = [] dfs(n, 2) return ans
255
Verify Preorder Sequence in Binary Search Tree
Medium
<p>Given an array of <strong>unique</strong> integers <code>preorder</code>, return <code>true</code> <em>if it is the correct preorder traversal sequence of a binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0255.Verify%20Preorder%20Sequence%20in%20Binary%20Search%20Tree/images/preorder-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> preorder = [5,2,1,3,6] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> preorder = [5,2,6,1,3] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= preorder[i] &lt;= 10<sup>4</sup></code></li> <li>All the elements of <code>preorder</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it using only constant space complexity?</p>
Stack; Tree; Binary Search Tree; Recursion; Array; Binary Tree; Monotonic Stack
C++
class Solution { public: bool verifyPreorder(vector<int>& preorder) { stack<int> stk; int last = INT_MIN; for (int x : preorder) { if (x < last) return false; while (!stk.empty() && stk.top() < x) { last = stk.top(); stk.pop(); } stk.push(x); } return true; } };
255
Verify Preorder Sequence in Binary Search Tree
Medium
<p>Given an array of <strong>unique</strong> integers <code>preorder</code>, return <code>true</code> <em>if it is the correct preorder traversal sequence of a binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0255.Verify%20Preorder%20Sequence%20in%20Binary%20Search%20Tree/images/preorder-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> preorder = [5,2,1,3,6] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> preorder = [5,2,6,1,3] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= preorder[i] &lt;= 10<sup>4</sup></code></li> <li>All the elements of <code>preorder</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it using only constant space complexity?</p>
Stack; Tree; Binary Search Tree; Recursion; Array; Binary Tree; Monotonic Stack
Go
func verifyPreorder(preorder []int) bool { var stk []int last := math.MinInt32 for _, x := range preorder { if x < last { return false } for len(stk) > 0 && stk[len(stk)-1] < x { last = stk[len(stk)-1] stk = stk[0 : len(stk)-1] } stk = append(stk, x) } return true }
255
Verify Preorder Sequence in Binary Search Tree
Medium
<p>Given an array of <strong>unique</strong> integers <code>preorder</code>, return <code>true</code> <em>if it is the correct preorder traversal sequence of a binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0255.Verify%20Preorder%20Sequence%20in%20Binary%20Search%20Tree/images/preorder-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> preorder = [5,2,1,3,6] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> preorder = [5,2,6,1,3] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= preorder[i] &lt;= 10<sup>4</sup></code></li> <li>All the elements of <code>preorder</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it using only constant space complexity?</p>
Stack; Tree; Binary Search Tree; Recursion; Array; Binary Tree; Monotonic Stack
Java
class Solution { public boolean verifyPreorder(int[] preorder) { Deque<Integer> stk = new ArrayDeque<>(); int last = Integer.MIN_VALUE; for (int x : preorder) { if (x < last) { return false; } while (!stk.isEmpty() && stk.peek() < x) { last = stk.poll(); } stk.push(x); } return true; } }
255
Verify Preorder Sequence in Binary Search Tree
Medium
<p>Given an array of <strong>unique</strong> integers <code>preorder</code>, return <code>true</code> <em>if it is the correct preorder traversal sequence of a binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0255.Verify%20Preorder%20Sequence%20in%20Binary%20Search%20Tree/images/preorder-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> preorder = [5,2,1,3,6] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> preorder = [5,2,6,1,3] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= preorder[i] &lt;= 10<sup>4</sup></code></li> <li>All the elements of <code>preorder</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it using only constant space complexity?</p>
Stack; Tree; Binary Search Tree; Recursion; Array; Binary Tree; Monotonic Stack
Python
class Solution: def verifyPreorder(self, preorder: List[int]) -> bool: stk = [] last = -inf for x in preorder: if x < last: return False while stk and stk[-1] < x: last = stk.pop() stk.append(x) return True
256
Paint House
Medium
<p>There is a row of <code>n</code> houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.</p> <p>The cost of painting each house with a certain color is represented by an <code>n x 3</code> cost matrix <code>costs</code>.</p> <ul> <li>For example, <code>costs[0][0]</code> is the cost of painting house <code>0</code> with the color red; <code>costs[1][2]</code> is the cost of painting house 1 with color green, and so on...</li> </ul> <p>Return <em>the minimum cost to paint all houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> costs = [[17,2,17],[16,16,5],[14,3,19]] <strong>Output:</strong> 10 <strong>Explanation:</strong> Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> costs = [[7,6,2]] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>costs.length == n</code></li> <li><code>costs[i].length == 3</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= costs[i][j] &lt;= 20</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int minCost(vector<vector<int>>& costs) { int r = 0, g = 0, b = 0; for (auto& cost : costs) { int _r = r, _g = g, _b = b; r = min(_g, _b) + cost[0]; g = min(_r, _b) + cost[1]; b = min(_r, _g) + cost[2]; } return min(r, min(g, b)); } };
256
Paint House
Medium
<p>There is a row of <code>n</code> houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.</p> <p>The cost of painting each house with a certain color is represented by an <code>n x 3</code> cost matrix <code>costs</code>.</p> <ul> <li>For example, <code>costs[0][0]</code> is the cost of painting house <code>0</code> with the color red; <code>costs[1][2]</code> is the cost of painting house 1 with color green, and so on...</li> </ul> <p>Return <em>the minimum cost to paint all houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> costs = [[17,2,17],[16,16,5],[14,3,19]] <strong>Output:</strong> 10 <strong>Explanation:</strong> Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> costs = [[7,6,2]] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>costs.length == n</code></li> <li><code>costs[i].length == 3</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= costs[i][j] &lt;= 20</code></li> </ul>
Array; Dynamic Programming
Go
func minCost(costs [][]int) int { r, g, b := 0, 0, 0 for _, cost := range costs { _r, _g, _b := r, g, b r = min(_g, _b) + cost[0] g = min(_r, _b) + cost[1] b = min(_r, _g) + cost[2] } return min(r, min(g, b)) }
256
Paint House
Medium
<p>There is a row of <code>n</code> houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.</p> <p>The cost of painting each house with a certain color is represented by an <code>n x 3</code> cost matrix <code>costs</code>.</p> <ul> <li>For example, <code>costs[0][0]</code> is the cost of painting house <code>0</code> with the color red; <code>costs[1][2]</code> is the cost of painting house 1 with color green, and so on...</li> </ul> <p>Return <em>the minimum cost to paint all houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> costs = [[17,2,17],[16,16,5],[14,3,19]] <strong>Output:</strong> 10 <strong>Explanation:</strong> Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> costs = [[7,6,2]] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>costs.length == n</code></li> <li><code>costs[i].length == 3</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= costs[i][j] &lt;= 20</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int minCost(int[][] costs) { int r = 0, g = 0, b = 0; for (int[] cost : costs) { int _r = r, _g = g, _b = b; r = Math.min(_g, _b) + cost[0]; g = Math.min(_r, _b) + cost[1]; b = Math.min(_r, _g) + cost[2]; } return Math.min(r, Math.min(g, b)); } }
256
Paint House
Medium
<p>There is a row of <code>n</code> houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.</p> <p>The cost of painting each house with a certain color is represented by an <code>n x 3</code> cost matrix <code>costs</code>.</p> <ul> <li>For example, <code>costs[0][0]</code> is the cost of painting house <code>0</code> with the color red; <code>costs[1][2]</code> is the cost of painting house 1 with color green, and so on...</li> </ul> <p>Return <em>the minimum cost to paint all houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> costs = [[17,2,17],[16,16,5],[14,3,19]] <strong>Output:</strong> 10 <strong>Explanation:</strong> Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> costs = [[7,6,2]] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>costs.length == n</code></li> <li><code>costs[i].length == 3</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= costs[i][j] &lt;= 20</code></li> </ul>
Array; Dynamic Programming
JavaScript
/** * @param {number[][]} costs * @return {number} */ var minCost = function (costs) { let [a, b, c] = [0, 0, 0]; for (let [ca, cb, cc] of costs) { [a, b, c] = [Math.min(b, c) + ca, Math.min(a, c) + cb, Math.min(a, b) + cc]; } return Math.min(a, b, c); };
256
Paint House
Medium
<p>There is a row of <code>n</code> houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.</p> <p>The cost of painting each house with a certain color is represented by an <code>n x 3</code> cost matrix <code>costs</code>.</p> <ul> <li>For example, <code>costs[0][0]</code> is the cost of painting house <code>0</code> with the color red; <code>costs[1][2]</code> is the cost of painting house 1 with color green, and so on...</li> </ul> <p>Return <em>the minimum cost to paint all houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> costs = [[17,2,17],[16,16,5],[14,3,19]] <strong>Output:</strong> 10 <strong>Explanation:</strong> Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> costs = [[7,6,2]] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>costs.length == n</code></li> <li><code>costs[i].length == 3</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= costs[i][j] &lt;= 20</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def minCost(self, costs: List[List[int]]) -> int: a = b = c = 0 for ca, cb, cc in costs: a, b, c = min(b, c) + ca, min(a, c) + cb, min(a, b) + cc return min(a, b, c)
257
Binary Tree Paths
Easy
<p>Given the <code>root</code> of a binary tree, return <em>all root-to-leaf paths in <strong>any order</strong></em>.</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/0200-0299/0257.Binary%20Tree%20Paths/images/paths-tree.jpg" style="width: 207px; height: 293px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,5] <strong>Output:</strong> [&quot;1-&gt;2-&gt;5&quot;,&quot;1-&gt;3&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [&quot;1&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; String; 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<string> binaryTreePaths(TreeNode* root) { vector<string> ans; vector<string> t; function<void(TreeNode*)> dfs = [&](TreeNode* root) { if (!root) { return; } t.push_back(to_string(root->val)); if (!root->left && !root->right) { ans.push_back(join(t)); } else { dfs(root->left); dfs(root->right); } t.pop_back(); }; dfs(root); return ans; } string join(vector<string>& t, string sep = "->") { string ans; for (int i = 0; i < t.size(); ++i) { if (i > 0) { ans += sep; } ans += t[i]; } return ans; } };
257
Binary Tree Paths
Easy
<p>Given the <code>root</code> of a binary tree, return <em>all root-to-leaf paths in <strong>any order</strong></em>.</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/0200-0299/0257.Binary%20Tree%20Paths/images/paths-tree.jpg" style="width: 207px; height: 293px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,5] <strong>Output:</strong> [&quot;1-&gt;2-&gt;5&quot;,&quot;1-&gt;3&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [&quot;1&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; String; Backtracking; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func binaryTreePaths(root *TreeNode) (ans []string) { t := []string{} var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } t = append(t, strconv.Itoa(root.Val)) if root.Left == nil && root.Right == nil { ans = append(ans, strings.Join(t, "->")) } else { dfs(root.Left) dfs(root.Right) } t = t[:len(t)-1] } dfs(root) return }
257
Binary Tree Paths
Easy
<p>Given the <code>root</code> of a binary tree, return <em>all root-to-leaf paths in <strong>any order</strong></em>.</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/0200-0299/0257.Binary%20Tree%20Paths/images/paths-tree.jpg" style="width: 207px; height: 293px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,5] <strong>Output:</strong> [&quot;1-&gt;2-&gt;5&quot;,&quot;1-&gt;3&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [&quot;1&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; String; 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<String> ans = new ArrayList<>(); private List<String> t = new ArrayList<>(); public List<String> binaryTreePaths(TreeNode root) { dfs(root); return ans; } private void dfs(TreeNode root) { if (root == null) { return; } t.add(root.val + ""); if (root.left == null && root.right == null) { ans.add(String.join("->", t)); } else { dfs(root.left); dfs(root.right); } t.remove(t.size() - 1); } }
257
Binary Tree Paths
Easy
<p>Given the <code>root</code> of a binary tree, return <em>all root-to-leaf paths in <strong>any order</strong></em>.</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/0200-0299/0257.Binary%20Tree%20Paths/images/paths-tree.jpg" style="width: 207px; height: 293px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,5] <strong>Output:</strong> [&quot;1-&gt;2-&gt;5&quot;,&quot;1-&gt;3&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [&quot;1&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; String; 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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: def dfs(root: Optional[TreeNode]): if root is None: return t.append(str(root.val)) if root.left is None and root.right is None: ans.append("->".join(t)) else: dfs(root.left) dfs(root.right) t.pop() ans = [] t = [] dfs(root) return ans
257
Binary Tree Paths
Easy
<p>Given the <code>root</code> of a binary tree, return <em>all root-to-leaf paths in <strong>any order</strong></em>.</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/0200-0299/0257.Binary%20Tree%20Paths/images/paths-tree.jpg" style="width: 207px; height: 293px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,5] <strong>Output:</strong> [&quot;1-&gt;2-&gt;5&quot;,&quot;1-&gt;3&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [&quot;1&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; String; Backtracking; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function binaryTreePaths(root: TreeNode | null): string[] { const ans: string[] = []; const t: number[] = []; const dfs = (root: TreeNode | null) => { if (!root) { return; } t.push(root.val); if (!root.left && !root.right) { ans.push(t.join('->')); } else { dfs(root.left); dfs(root.right); } t.pop(); }; dfs(root); return ans; }
258
Add Digits
Easy
<p>Given an integer <code>num</code>, repeatedly add all its digits until the result has only one digit, and return it.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 38 <strong>Output:</strong> 2 <strong>Explanation:</strong> The process is 38 --&gt; 3 + 8 --&gt; 11 11 --&gt; 1 + 1 --&gt; 2 Since 2 has only one digit, return it. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it without any loop/recursion in <code>O(1)</code> runtime?</p>
Math; Number Theory; Simulation
C++
class Solution { public: int addDigits(int num) { return (num - 1) % 9 + 1; } };
258
Add Digits
Easy
<p>Given an integer <code>num</code>, repeatedly add all its digits until the result has only one digit, and return it.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 38 <strong>Output:</strong> 2 <strong>Explanation:</strong> The process is 38 --&gt; 3 + 8 --&gt; 11 11 --&gt; 1 + 1 --&gt; 2 Since 2 has only one digit, return it. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it without any loop/recursion in <code>O(1)</code> runtime?</p>
Math; Number Theory; Simulation
Go
func addDigits(num int) int { if num == 0 { return 0 } return (num-1)%9 + 1 }
258
Add Digits
Easy
<p>Given an integer <code>num</code>, repeatedly add all its digits until the result has only one digit, and return it.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 38 <strong>Output:</strong> 2 <strong>Explanation:</strong> The process is 38 --&gt; 3 + 8 --&gt; 11 11 --&gt; 1 + 1 --&gt; 2 Since 2 has only one digit, return it. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it without any loop/recursion in <code>O(1)</code> runtime?</p>
Math; Number Theory; Simulation
Java
class Solution { public int addDigits(int num) { return (num - 1) % 9 + 1; } }
258
Add Digits
Easy
<p>Given an integer <code>num</code>, repeatedly add all its digits until the result has only one digit, and return it.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 38 <strong>Output:</strong> 2 <strong>Explanation:</strong> The process is 38 --&gt; 3 + 8 --&gt; 11 11 --&gt; 1 + 1 --&gt; 2 Since 2 has only one digit, return it. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it without any loop/recursion in <code>O(1)</code> runtime?</p>
Math; Number Theory; Simulation
Python
class Solution: def addDigits(self, num: int) -> int: return 0 if num == 0 else (num - 1) % 9 + 1
258
Add Digits
Easy
<p>Given an integer <code>num</code>, repeatedly add all its digits until the result has only one digit, and return it.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 38 <strong>Output:</strong> 2 <strong>Explanation:</strong> The process is 38 --&gt; 3 + 8 --&gt; 11 11 --&gt; 1 + 1 --&gt; 2 Since 2 has only one digit, return it. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it without any loop/recursion in <code>O(1)</code> runtime?</p>
Math; Number Theory; Simulation
Rust
impl Solution { pub fn add_digits(mut num: i32) -> i32 { ((num - 1) % 9) + 1 } }
259
3Sum Smaller
Medium
<p>Given an array of <code>n</code> integers <code>nums</code> and an integer&nbsp;<code>target</code>, find the number of index triplets <code>i</code>, <code>j</code>, <code>k</code> with <code>0 &lt;= i &lt; j &lt; k &lt; n</code> that satisfy the condition <code>nums[i] + nums[j] + nums[k] &lt; target</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,0,1,3], target = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because there are two triplets which sums are less than 2: [-2,0,1] [-2,0,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0], target = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>0 &lt;= n &lt;= 3500</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>-100 &lt;= target &lt;= 100</code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
C++
class Solution { public: int threeSumSmaller(vector<int>& nums, int target) { ranges::sort(nums); int ans = 0, n = nums.size(); for (int i = 0; i + 2 < n; ++i) { int j = i + 1, k = n - 1; while (j < k) { int x = nums[i] + nums[j] + nums[k]; if (x < target) { ans += k - j; ++j; } else { --k; } } } return ans; } };
259
3Sum Smaller
Medium
<p>Given an array of <code>n</code> integers <code>nums</code> and an integer&nbsp;<code>target</code>, find the number of index triplets <code>i</code>, <code>j</code>, <code>k</code> with <code>0 &lt;= i &lt; j &lt; k &lt; n</code> that satisfy the condition <code>nums[i] + nums[j] + nums[k] &lt; target</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,0,1,3], target = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because there are two triplets which sums are less than 2: [-2,0,1] [-2,0,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0], target = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>0 &lt;= n &lt;= 3500</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>-100 &lt;= target &lt;= 100</code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
Go
func threeSumSmaller(nums []int, target int) (ans int) { sort.Ints(nums) n := len(nums) for i := 0; i < n-2; i++ { j, k := i+1, n-1 for j < k { x := nums[i] + nums[j] + nums[k] if x < target { ans += k - j j++ } else { k-- } } } return }
259
3Sum Smaller
Medium
<p>Given an array of <code>n</code> integers <code>nums</code> and an integer&nbsp;<code>target</code>, find the number of index triplets <code>i</code>, <code>j</code>, <code>k</code> with <code>0 &lt;= i &lt; j &lt; k &lt; n</code> that satisfy the condition <code>nums[i] + nums[j] + nums[k] &lt; target</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,0,1,3], target = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because there are two triplets which sums are less than 2: [-2,0,1] [-2,0,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0], target = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>0 &lt;= n &lt;= 3500</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>-100 &lt;= target &lt;= 100</code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
Java
class Solution { public int threeSumSmaller(int[] nums, int target) { Arrays.sort(nums); int ans = 0, n = nums.length; for (int i = 0; i + 2 < n; ++i) { int j = i + 1, k = n - 1; while (j < k) { int x = nums[i] + nums[j] + nums[k]; if (x < target) { ans += k - j; ++j; } else { --k; } } } return ans; } }
259
3Sum Smaller
Medium
<p>Given an array of <code>n</code> integers <code>nums</code> and an integer&nbsp;<code>target</code>, find the number of index triplets <code>i</code>, <code>j</code>, <code>k</code> with <code>0 &lt;= i &lt; j &lt; k &lt; n</code> that satisfy the condition <code>nums[i] + nums[j] + nums[k] &lt; target</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,0,1,3], target = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because there are two triplets which sums are less than 2: [-2,0,1] [-2,0,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0], target = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>0 &lt;= n &lt;= 3500</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>-100 &lt;= target &lt;= 100</code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
JavaScript
/** * @param {number[]} nums * @param {number} target * @return {number} */ var threeSumSmaller = function (nums, target) { nums.sort((a, b) => a - b); const n = nums.length; let ans = 0; for (let i = 0; i < n - 2; ++i) { let [j, k] = [i + 1, n - 1]; while (j < k) { const x = nums[i] + nums[j] + nums[k]; if (x < target) { ans += k - j; ++j; } else { --k; } } } return ans; };
259
3Sum Smaller
Medium
<p>Given an array of <code>n</code> integers <code>nums</code> and an integer&nbsp;<code>target</code>, find the number of index triplets <code>i</code>, <code>j</code>, <code>k</code> with <code>0 &lt;= i &lt; j &lt; k &lt; n</code> that satisfy the condition <code>nums[i] + nums[j] + nums[k] &lt; target</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,0,1,3], target = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because there are two triplets which sums are less than 2: [-2,0,1] [-2,0,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0], target = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>0 &lt;= n &lt;= 3500</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>-100 &lt;= target &lt;= 100</code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
Python
class Solution: def threeSumSmaller(self, nums: List[int], target: int) -> int: nums.sort() ans, n = 0, len(nums) for i in range(n - 2): j, k = i + 1, n - 1 while j < k: x = nums[i] + nums[j] + nums[k] if x < target: ans += k - j j += 1 else: k -= 1 return ans
259
3Sum Smaller
Medium
<p>Given an array of <code>n</code> integers <code>nums</code> and an integer&nbsp;<code>target</code>, find the number of index triplets <code>i</code>, <code>j</code>, <code>k</code> with <code>0 &lt;= i &lt; j &lt; k &lt; n</code> that satisfy the condition <code>nums[i] + nums[j] + nums[k] &lt; target</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,0,1,3], target = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because there are two triplets which sums are less than 2: [-2,0,1] [-2,0,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0], target = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>0 &lt;= n &lt;= 3500</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>-100 &lt;= target &lt;= 100</code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
TypeScript
function threeSumSmaller(nums: number[], target: number): number { nums.sort((a, b) => a - b); const n = nums.length; let ans = 0; for (let i = 0; i < n - 2; ++i) { let [j, k] = [i + 1, n - 1]; while (j < k) { const x = nums[i] + nums[j] + nums[k]; if (x < target) { ans += k - j; ++j; } else { --k; } } } return ans; }
260
Single Number III
Medium
<p>Given an integer array <code>nums</code>, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in <strong>any order</strong>.</p> <p>You must write an&nbsp;algorithm that runs in linear runtime complexity and uses&nbsp;only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,2,5] <strong>Output:</strong> [3,5] <strong>Explanation: </strong> [5, 3] is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0] <strong>Output:</strong> [-1,0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [1,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>Each integer in <code>nums</code> will appear twice, only two integers will appear once.</li> </ul>
Bit Manipulation; Array
C++
class Solution { public: vector<int> singleNumber(vector<int>& nums) { long long xs = 0; for (int& x : nums) { xs ^= x; } int lb = xs & -xs; int a = 0; for (int& x : nums) { if (x & lb) { a ^= x; } } int b = xs ^ a; return {a, b}; } };
260
Single Number III
Medium
<p>Given an integer array <code>nums</code>, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in <strong>any order</strong>.</p> <p>You must write an&nbsp;algorithm that runs in linear runtime complexity and uses&nbsp;only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,2,5] <strong>Output:</strong> [3,5] <strong>Explanation: </strong> [5, 3] is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0] <strong>Output:</strong> [-1,0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [1,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>Each integer in <code>nums</code> will appear twice, only two integers will appear once.</li> </ul>
Bit Manipulation; Array
C#
public class Solution { public int[] SingleNumber(int[] nums) { int xs = nums.Aggregate(0, (a, b) => a ^ b); int lb = xs & -xs; int a = 0; foreach(int x in nums) { if ((x & lb) != 0) { a ^= x; } } int b = xs ^ a; return new int[] {a, b}; } }
260
Single Number III
Medium
<p>Given an integer array <code>nums</code>, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in <strong>any order</strong>.</p> <p>You must write an&nbsp;algorithm that runs in linear runtime complexity and uses&nbsp;only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,2,5] <strong>Output:</strong> [3,5] <strong>Explanation: </strong> [5, 3] is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0] <strong>Output:</strong> [-1,0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [1,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>Each integer in <code>nums</code> will appear twice, only two integers will appear once.</li> </ul>
Bit Manipulation; Array
Go
func singleNumber(nums []int) []int { xs := 0 for _, x := range nums { xs ^= x } lb := xs & -xs a := 0 for _, x := range nums { if x&lb != 0 { a ^= x } } b := xs ^ a return []int{a, b} }
260
Single Number III
Medium
<p>Given an integer array <code>nums</code>, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in <strong>any order</strong>.</p> <p>You must write an&nbsp;algorithm that runs in linear runtime complexity and uses&nbsp;only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,2,5] <strong>Output:</strong> [3,5] <strong>Explanation: </strong> [5, 3] is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0] <strong>Output:</strong> [-1,0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [1,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>Each integer in <code>nums</code> will appear twice, only two integers will appear once.</li> </ul>
Bit Manipulation; Array
Java
class Solution { public int[] singleNumber(int[] nums) { int xs = 0; for (int x : nums) { xs ^= x; } int lb = xs & -xs; int a = 0; for (int x : nums) { if ((x & lb) != 0) { a ^= x; } } int b = xs ^ a; return new int[] {a, b}; } }
260
Single Number III
Medium
<p>Given an integer array <code>nums</code>, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in <strong>any order</strong>.</p> <p>You must write an&nbsp;algorithm that runs in linear runtime complexity and uses&nbsp;only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,2,5] <strong>Output:</strong> [3,5] <strong>Explanation: </strong> [5, 3] is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0] <strong>Output:</strong> [-1,0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [1,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>Each integer in <code>nums</code> will appear twice, only two integers will appear once.</li> </ul>
Bit Manipulation; Array
JavaScript
/** * @param {number[]} nums * @return {number[]} */ var singleNumber = function (nums) { const xs = nums.reduce((a, b) => a ^ b); const lb = xs & -xs; let a = 0; for (const x of nums) { if (x & lb) { a ^= x; } } const b = xs ^ a; return [a, b]; };
260
Single Number III
Medium
<p>Given an integer array <code>nums</code>, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in <strong>any order</strong>.</p> <p>You must write an&nbsp;algorithm that runs in linear runtime complexity and uses&nbsp;only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,2,5] <strong>Output:</strong> [3,5] <strong>Explanation: </strong> [5, 3] is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0] <strong>Output:</strong> [-1,0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [1,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>Each integer in <code>nums</code> will appear twice, only two integers will appear once.</li> </ul>
Bit Manipulation; Array
Python
class Solution: def singleNumber(self, nums: List[int]) -> List[int]: xs = reduce(xor, nums) a = 0 lb = xs & -xs for x in nums: if x & lb: a ^= x b = xs ^ a return [a, b]
260
Single Number III
Medium
<p>Given an integer array <code>nums</code>, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in <strong>any order</strong>.</p> <p>You must write an&nbsp;algorithm that runs in linear runtime complexity and uses&nbsp;only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,2,5] <strong>Output:</strong> [3,5] <strong>Explanation: </strong> [5, 3] is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0] <strong>Output:</strong> [-1,0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [1,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>Each integer in <code>nums</code> will appear twice, only two integers will appear once.</li> </ul>
Bit Manipulation; Array
Rust
impl Solution { pub fn single_number(nums: Vec<i32>) -> Vec<i32> { let xs = nums.iter().fold(0, |r, v| r ^ v); let lb = xs & -xs; let mut a = 0; for x in &nums { if (x & lb) != 0 { a ^= x; } } let b = xs ^ a; vec![a, b] } }
260
Single Number III
Medium
<p>Given an integer array <code>nums</code>, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in <strong>any order</strong>.</p> <p>You must write an&nbsp;algorithm that runs in linear runtime complexity and uses&nbsp;only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,2,5] <strong>Output:</strong> [3,5] <strong>Explanation: </strong> [5, 3] is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0] <strong>Output:</strong> [-1,0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> [1,0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>Each integer in <code>nums</code> will appear twice, only two integers will appear once.</li> </ul>
Bit Manipulation; Array
TypeScript
function singleNumber(nums: number[]): number[] { const xs = nums.reduce((a, b) => a ^ b); const lb = xs & -xs; let a = 0; for (const x of nums) { if (x & lb) { a ^= x; } } const b = xs ^ a; return [a, b]; }
261
Graph Valid Tree
Medium
<p>You have a graph of <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given an integer n and a list of <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p> <p>Return <code>true</code> <em>if the edges of the given graph make up a valid tree, and</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0261.Graph%20Valid%20Tree/images/tree1-graph.jpg" style="width: 222px; height: 302px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0261.Graph%20Valid%20Tree/images/tree2-graph.jpg" style="width: 382px; height: 222px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2000</code></li> <li><code>0 &lt;= edges.length &lt;= 5000</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>There are no self-loops or repeated edges.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
C++
class Solution { public: bool validTree(int n, vector<vector<int>>& edges) { vector<int> p(n); iota(p.begin(), p.end(), 0); function<int(int)> find = [&](int x) { if (p[x] != x) { p[x] = find(p[x]); } return p[x]; }; for (auto& e : edges) { int pa = find(e[0]), pb = find(e[1]); if (pa == pb) { return false; } p[pa] = pb; --n; } return n == 1; } };
261
Graph Valid Tree
Medium
<p>You have a graph of <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given an integer n and a list of <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p> <p>Return <code>true</code> <em>if the edges of the given graph make up a valid tree, and</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0261.Graph%20Valid%20Tree/images/tree1-graph.jpg" style="width: 222px; height: 302px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0261.Graph%20Valid%20Tree/images/tree2-graph.jpg" style="width: 382px; height: 222px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2000</code></li> <li><code>0 &lt;= edges.length &lt;= 5000</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>There are no self-loops or repeated edges.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
Go
func validTree(n int, edges [][]int) bool { p := make([]int, n) for i := range p { p[i] = i } var find func(int) int find = func(x int) int { if p[x] != x { p[x] = find(p[x]) } return p[x] } for _, e := range edges { pa, pb := find(e[0]), find(e[1]) if pa == pb { return false } p[pa] = pb n-- } return n == 1 }
261
Graph Valid Tree
Medium
<p>You have a graph of <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given an integer n and a list of <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p> <p>Return <code>true</code> <em>if the edges of the given graph make up a valid tree, and</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0261.Graph%20Valid%20Tree/images/tree1-graph.jpg" style="width: 222px; height: 302px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0261.Graph%20Valid%20Tree/images/tree2-graph.jpg" style="width: 382px; height: 222px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2000</code></li> <li><code>0 &lt;= edges.length &lt;= 5000</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>There are no self-loops or repeated edges.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
Java
class Solution { private int[] p; public boolean validTree(int n, int[][] edges) { p = new int[n]; for (int i = 0; i < n; ++i) { p[i] = i; } for (var e : edges) { int pa = find(e[0]), pb = find(e[1]); if (pa == pb) { return false; } p[pa] = pb; --n; } return n == 1; } private int find(int x) { if (p[x] != x) { p[x] = find(p[x]); } return p[x]; } }
261
Graph Valid Tree
Medium
<p>You have a graph of <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given an integer n and a list of <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p> <p>Return <code>true</code> <em>if the edges of the given graph make up a valid tree, and</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0261.Graph%20Valid%20Tree/images/tree1-graph.jpg" style="width: 222px; height: 302px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0261.Graph%20Valid%20Tree/images/tree2-graph.jpg" style="width: 382px; height: 222px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2000</code></li> <li><code>0 &lt;= edges.length &lt;= 5000</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>There are no self-loops or repeated edges.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
JavaScript
/** * @param {number} n * @param {number[][]} edges * @return {boolean} */ var validTree = function (n, edges) { const p = Array.from({ length: n }, (_, i) => i); const find = x => { if (p[x] !== x) { p[x] = find(p[x]); } return p[x]; }; for (const [a, b] of edges) { const pa = find(a); const pb = find(b); if (pa === pb) { return false; } p[pa] = pb; --n; } return n === 1; };
261
Graph Valid Tree
Medium
<p>You have a graph of <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given an integer n and a list of <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p> <p>Return <code>true</code> <em>if the edges of the given graph make up a valid tree, and</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0261.Graph%20Valid%20Tree/images/tree1-graph.jpg" style="width: 222px; height: 302px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0261.Graph%20Valid%20Tree/images/tree2-graph.jpg" style="width: 382px; height: 222px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2000</code></li> <li><code>0 &lt;= edges.length &lt;= 5000</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>There are no self-loops or repeated edges.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
Python
class Solution: def validTree(self, n: int, edges: List[List[int]]) -> bool: def find(x: int) -> int: if p[x] != x: p[x] = find(p[x]) return p[x] p = list(range(n)) for a, b in edges: pa, pb = find(a), find(b) if pa == pb: return False p[pa] = pb n -= 1 return n == 1
262
Trips and Users
Hard
<p>Table: <code>Trips</code></p> <pre> +-------------+----------+ | Column Name | Type | +-------------+----------+ | id | int | | client_id | int | | driver_id | int | | city_id | int | | status | enum | | request_at | varchar | +-------------+----------+ id is the primary key (column with unique values) for this table. The table holds all taxi trips. Each trip has a unique id, while client_id and driver_id are foreign keys to the users_id at the Users table. Status is an ENUM (category) type of (&#39;completed&#39;, &#39;cancelled_by_driver&#39;, &#39;cancelled_by_client&#39;). </pre> <p> </p> <p>Table: <code>Users</code></p> <pre> +-------------+----------+ | Column Name | Type | +-------------+----------+ | users_id | int | | banned | enum | | role | enum | +-------------+----------+ users_id is the primary key (column with unique values) for this table. The table holds all users. Each user has a unique users_id, and role is an ENUM type of (&#39;client&#39;, &#39;driver&#39;, &#39;partner&#39;). banned is an ENUM (category) type of (&#39;Yes&#39;, &#39;No&#39;). </pre> <p> </p> <p>The <strong>cancellation rate</strong> is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day.</p> <p>Write a solution to find the <strong>cancellation rate</strong> of requests with unbanned users (<strong>both client and driver must not be banned</strong>) each day between <code>&quot;2013-10-01&quot;</code> and <code>&quot;2013-10-03&quot;</code> with <strong>at least</strong> one trip. Round <code>Cancellation Rate</code> to <strong>two decimal</strong> points.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Trips table: +----+-----------+-----------+---------+---------------------+------------+ | id | client_id | driver_id | city_id | status | request_at | +----+-----------+-----------+---------+---------------------+------------+ | 1 | 1 | 10 | 1 | completed | 2013-10-01 | | 2 | 2 | 11 | 1 | cancelled_by_driver | 2013-10-01 | | 3 | 3 | 12 | 6 | completed | 2013-10-01 | | 4 | 4 | 13 | 6 | cancelled_by_client | 2013-10-01 | | 5 | 1 | 10 | 1 | completed | 2013-10-02 | | 6 | 2 | 11 | 6 | completed | 2013-10-02 | | 7 | 3 | 12 | 6 | completed | 2013-10-02 | | 8 | 2 | 12 | 12 | completed | 2013-10-03 | | 9 | 3 | 10 | 12 | completed | 2013-10-03 | | 10 | 4 | 13 | 12 | cancelled_by_driver | 2013-10-03 | +----+-----------+-----------+---------+---------------------+------------+ Users table: +----------+--------+--------+ | users_id | banned | role | +----------+--------+--------+ | 1 | No | client | | 2 | Yes | client | | 3 | No | client | | 4 | No | client | | 10 | No | driver | | 11 | No | driver | | 12 | No | driver | | 13 | No | driver | +----------+--------+--------+ <strong>Output:</strong> +------------+-------------------+ | Day | Cancellation Rate | +------------+-------------------+ | 2013-10-01 | 0.33 | | 2013-10-02 | 0.00 | | 2013-10-03 | 0.50 | +------------+-------------------+ <strong>Explanation:</strong> On 2013-10-01: - There were 4 requests in total, 2 of which were canceled. - However, the request with Id=2 was made by a banned client (User_Id=2), so it is ignored in the calculation. - Hence there are 3 unbanned requests in total, 1 of which was canceled. - The Cancellation Rate is (1 / 3) = 0.33 On 2013-10-02: - There were 3 requests in total, 0 of which were canceled. - The request with Id=6 was made by a banned client, so it is ignored. - Hence there are 2 unbanned requests in total, 0 of which were canceled. - The Cancellation Rate is (0 / 2) = 0.00 On 2013-10-03: - There were 3 requests in total, 1 of which was canceled. - The request with Id=8 was made by a banned client, so it is ignored. - Hence there are 2 unbanned request in total, 1 of which were canceled. - The Cancellation Rate is (1 / 2) = 0.50 </pre>
Database
Python
import pandas as pd def trips_and_users(trips: pd.DataFrame, users: pd.DataFrame) -> pd.DataFrame: # 1) temporal filtering trips = trips[trips["request_at"].between("2013-10-01", "2013-10-03")].rename( columns={"request_at": "Day"} ) # 2) filtering based not banned # 2.1) mappning the column 'banned' to `client_id` and `driver_id` df_client = ( pd.merge(trips, users, left_on="client_id", right_on="users_id", how="left") .drop(["users_id", "role"], axis=1) .rename(columns={"banned": "banned_client"}) ) df_driver = ( pd.merge(trips, users, left_on="driver_id", right_on="users_id", how="left") .drop(["users_id", "role"], axis=1) .rename(columns={"banned": "banned_driver"}) ) df = pd.merge( df_client, df_driver, left_on=["id", "driver_id", "client_id", "city_id", "status", "Day"], right_on=["id", "driver_id", "client_id", "city_id", "status", "Day"], how="left", ) # 2.2) filtering based on not banned df = df[(df["banned_client"] == "No") & (df["banned_driver"] == "No")] # 3) counting the cancelled and total trips per day df["status_cancelled"] = df["status"].str.contains("cancelled") df = df[["Day", "status_cancelled"]] df = df.groupby("Day").agg( {"status_cancelled": [("total_cancelled", "sum"), ("total", "count")]} ) df.columns = df.columns.droplevel() df = df.reset_index() # 4) calculating the ratio df["Cancellation Rate"] = (df["total_cancelled"] / df["total"]).round(2) return df[["Day", "Cancellation Rate"]]
262
Trips and Users
Hard
<p>Table: <code>Trips</code></p> <pre> +-------------+----------+ | Column Name | Type | +-------------+----------+ | id | int | | client_id | int | | driver_id | int | | city_id | int | | status | enum | | request_at | varchar | +-------------+----------+ id is the primary key (column with unique values) for this table. The table holds all taxi trips. Each trip has a unique id, while client_id and driver_id are foreign keys to the users_id at the Users table. Status is an ENUM (category) type of (&#39;completed&#39;, &#39;cancelled_by_driver&#39;, &#39;cancelled_by_client&#39;). </pre> <p> </p> <p>Table: <code>Users</code></p> <pre> +-------------+----------+ | Column Name | Type | +-------------+----------+ | users_id | int | | banned | enum | | role | enum | +-------------+----------+ users_id is the primary key (column with unique values) for this table. The table holds all users. Each user has a unique users_id, and role is an ENUM type of (&#39;client&#39;, &#39;driver&#39;, &#39;partner&#39;). banned is an ENUM (category) type of (&#39;Yes&#39;, &#39;No&#39;). </pre> <p> </p> <p>The <strong>cancellation rate</strong> is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day.</p> <p>Write a solution to find the <strong>cancellation rate</strong> of requests with unbanned users (<strong>both client and driver must not be banned</strong>) each day between <code>&quot;2013-10-01&quot;</code> and <code>&quot;2013-10-03&quot;</code> with <strong>at least</strong> one trip. Round <code>Cancellation Rate</code> to <strong>two decimal</strong> points.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Trips table: +----+-----------+-----------+---------+---------------------+------------+ | id | client_id | driver_id | city_id | status | request_at | +----+-----------+-----------+---------+---------------------+------------+ | 1 | 1 | 10 | 1 | completed | 2013-10-01 | | 2 | 2 | 11 | 1 | cancelled_by_driver | 2013-10-01 | | 3 | 3 | 12 | 6 | completed | 2013-10-01 | | 4 | 4 | 13 | 6 | cancelled_by_client | 2013-10-01 | | 5 | 1 | 10 | 1 | completed | 2013-10-02 | | 6 | 2 | 11 | 6 | completed | 2013-10-02 | | 7 | 3 | 12 | 6 | completed | 2013-10-02 | | 8 | 2 | 12 | 12 | completed | 2013-10-03 | | 9 | 3 | 10 | 12 | completed | 2013-10-03 | | 10 | 4 | 13 | 12 | cancelled_by_driver | 2013-10-03 | +----+-----------+-----------+---------+---------------------+------------+ Users table: +----------+--------+--------+ | users_id | banned | role | +----------+--------+--------+ | 1 | No | client | | 2 | Yes | client | | 3 | No | client | | 4 | No | client | | 10 | No | driver | | 11 | No | driver | | 12 | No | driver | | 13 | No | driver | +----------+--------+--------+ <strong>Output:</strong> +------------+-------------------+ | Day | Cancellation Rate | +------------+-------------------+ | 2013-10-01 | 0.33 | | 2013-10-02 | 0.00 | | 2013-10-03 | 0.50 | +------------+-------------------+ <strong>Explanation:</strong> On 2013-10-01: - There were 4 requests in total, 2 of which were canceled. - However, the request with Id=2 was made by a banned client (User_Id=2), so it is ignored in the calculation. - Hence there are 3 unbanned requests in total, 1 of which was canceled. - The Cancellation Rate is (1 / 3) = 0.33 On 2013-10-02: - There were 3 requests in total, 0 of which were canceled. - The request with Id=6 was made by a banned client, so it is ignored. - Hence there are 2 unbanned requests in total, 0 of which were canceled. - The Cancellation Rate is (0 / 2) = 0.00 On 2013-10-03: - There were 3 requests in total, 1 of which was canceled. - The request with Id=8 was made by a banned client, so it is ignored. - Hence there are 2 unbanned request in total, 1 of which were canceled. - The Cancellation Rate is (1 / 2) = 0.50 </pre>
Database
SQL
# Write your MySQL query statement below SELECT request_at AS Day, ROUND(AVG(status != 'completed'), 2) AS 'Cancellation Rate' FROM Trips AS t JOIN Users AS u1 ON (t.client_id = u1.users_id AND u1.banned = 'No') JOIN Users AS u2 ON (t.driver_id = u2.users_id AND u2.banned = 'No') WHERE request_at BETWEEN '2013-10-01' AND '2013-10-03' GROUP BY request_at;
263
Ugly Number
Easy
<p>An <strong>ugly number</strong> is a <em>positive</em> integer which does not have a prime factor other than 2, 3, and 5.</p> <p>Given an integer <code>n</code>, return <code>true</code> <em>if</em> <code>n</code> <em>is an <strong>ugly number</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 6 <strong>Output:</strong> true <strong>Explanation:</strong> 6 = 2 &times; 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation:</strong> 1 has no prime factors. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 14 <strong>Output:</strong> false <strong>Explanation:</strong> 14 is not ugly since it includes the prime factor 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math
C++
class Solution { public: bool isUgly(int n) { if (n < 1) return false; while (n % 2 == 0) { n /= 2; } while (n % 3 == 0) { n /= 3; } while (n % 5 == 0) { n /= 5; } return n == 1; } };
263
Ugly Number
Easy
<p>An <strong>ugly number</strong> is a <em>positive</em> integer which does not have a prime factor other than 2, 3, and 5.</p> <p>Given an integer <code>n</code>, return <code>true</code> <em>if</em> <code>n</code> <em>is an <strong>ugly number</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 6 <strong>Output:</strong> true <strong>Explanation:</strong> 6 = 2 &times; 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation:</strong> 1 has no prime factors. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 14 <strong>Output:</strong> false <strong>Explanation:</strong> 14 is not ugly since it includes the prime factor 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math
Go
func isUgly(n int) bool { if n < 1 { return false } for _, x := range []int{2, 3, 5} { for n%x == 0 { n /= x } } return n == 1 }
263
Ugly Number
Easy
<p>An <strong>ugly number</strong> is a <em>positive</em> integer which does not have a prime factor other than 2, 3, and 5.</p> <p>Given an integer <code>n</code>, return <code>true</code> <em>if</em> <code>n</code> <em>is an <strong>ugly number</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 6 <strong>Output:</strong> true <strong>Explanation:</strong> 6 = 2 &times; 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation:</strong> 1 has no prime factors. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 14 <strong>Output:</strong> false <strong>Explanation:</strong> 14 is not ugly since it includes the prime factor 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math
Java
class Solution { public boolean isUgly(int n) { if (n < 1) return false; while (n % 2 == 0) { n /= 2; } while (n % 3 == 0) { n /= 3; } while (n % 5 == 0) { n /= 5; } return n == 1; } }
263
Ugly Number
Easy
<p>An <strong>ugly number</strong> is a <em>positive</em> integer which does not have a prime factor other than 2, 3, and 5.</p> <p>Given an integer <code>n</code>, return <code>true</code> <em>if</em> <code>n</code> <em>is an <strong>ugly number</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 6 <strong>Output:</strong> true <strong>Explanation:</strong> 6 = 2 &times; 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation:</strong> 1 has no prime factors. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 14 <strong>Output:</strong> false <strong>Explanation:</strong> 14 is not ugly since it includes the prime factor 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math
JavaScript
/** * @param {number} n * @return {boolean} */ var isUgly = function (n) { if (n < 1) return false; while (n % 2 === 0) { n /= 2; } while (n % 3 === 0) { n /= 3; } while (n % 5 === 0) { n /= 5; } return n === 1; };
263
Ugly Number
Easy
<p>An <strong>ugly number</strong> is a <em>positive</em> integer which does not have a prime factor other than 2, 3, and 5.</p> <p>Given an integer <code>n</code>, return <code>true</code> <em>if</em> <code>n</code> <em>is an <strong>ugly number</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 6 <strong>Output:</strong> true <strong>Explanation:</strong> 6 = 2 &times; 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation:</strong> 1 has no prime factors. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 14 <strong>Output:</strong> false <strong>Explanation:</strong> 14 is not ugly since it includes the prime factor 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math
PHP
class Solution { /** * @param Integer $n * @return Boolean */ function isUgly($n) { while ($n) { if ($n % 2 == 0) { $n = $n / 2; } elseif ($n % 3 == 0) { $n = $n / 3; } elseif ($n % 5 == 0) { $n = $n / 5; } else { break; } } return $n == 1; } }
263
Ugly Number
Easy
<p>An <strong>ugly number</strong> is a <em>positive</em> integer which does not have a prime factor other than 2, 3, and 5.</p> <p>Given an integer <code>n</code>, return <code>true</code> <em>if</em> <code>n</code> <em>is an <strong>ugly number</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 6 <strong>Output:</strong> true <strong>Explanation:</strong> 6 = 2 &times; 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation:</strong> 1 has no prime factors. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 14 <strong>Output:</strong> false <strong>Explanation:</strong> 14 is not ugly since it includes the prime factor 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math
Python
class Solution: def isUgly(self, n: int) -> bool: if n < 1: return False for x in [2, 3, 5]: while n % x == 0: n //= x return n == 1
264
Ugly Number II
Medium
<p>An <strong>ugly number</strong> is a positive integer whose prime factors are limited to <code>2</code>, <code>3</code>, and <code>5</code>.</p> <p>Given an integer <code>n</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>ugly number</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 12 <strong>Explanation:</strong> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1690</code></li> </ul>
Hash Table; Math; Dynamic Programming; Heap (Priority Queue)
C++
class Solution { public: int nthUglyNumber(int n) { priority_queue<long, vector<long>, greater<long>> q; q.push(1l); unordered_set<long> vis{{1l}}; long ans = 1; vector<int> f = {2, 3, 5}; while (n--) { ans = q.top(); q.pop(); for (int& v : f) { long nxt = ans * v; if (!vis.count(nxt)) { vis.insert(nxt); q.push(nxt); } } } return (int) ans; } };
264
Ugly Number II
Medium
<p>An <strong>ugly number</strong> is a positive integer whose prime factors are limited to <code>2</code>, <code>3</code>, and <code>5</code>.</p> <p>Given an integer <code>n</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>ugly number</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 12 <strong>Explanation:</strong> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1690</code></li> </ul>
Hash Table; Math; Dynamic Programming; Heap (Priority Queue)
C#
public class Solution { public int NthUglyNumber(int n) { int[] dp = new int[n]; dp[0] = 1; int p2 = 0, p3 = 0, p5 = 0; for (int i = 1; i < n; ++i) { int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; dp[i] = Math.Min(next2, Math.Min(next3, next5)); if (dp[i] == next2) { ++p2; } if (dp[i] == next3) { ++p3; } if (dp[i] == next5) { ++p5; } } return dp[n - 1]; } }
264
Ugly Number II
Medium
<p>An <strong>ugly number</strong> is a positive integer whose prime factors are limited to <code>2</code>, <code>3</code>, and <code>5</code>.</p> <p>Given an integer <code>n</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>ugly number</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 12 <strong>Explanation:</strong> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1690</code></li> </ul>
Hash Table; Math; Dynamic Programming; Heap (Priority Queue)
Go
func nthUglyNumber(n int) int { h := IntHeap([]int{1}) heap.Init(&h) ans := 1 vis := map[int]bool{1: true} for n > 0 { ans = heap.Pop(&h).(int) for _, v := range []int{2, 3, 5} { nxt := ans * v if !vis[nxt] { vis[nxt] = true heap.Push(&h, nxt) } } n-- } return ans } type IntHeap []int func (h IntHeap) Len() int { return len(h) } func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) } func (h *IntHeap) Pop() any { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x }
264
Ugly Number II
Medium
<p>An <strong>ugly number</strong> is a positive integer whose prime factors are limited to <code>2</code>, <code>3</code>, and <code>5</code>.</p> <p>Given an integer <code>n</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>ugly number</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 12 <strong>Explanation:</strong> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1690</code></li> </ul>
Hash Table; Math; Dynamic Programming; Heap (Priority Queue)
Java
class Solution { public int nthUglyNumber(int n) { Set<Long> vis = new HashSet<>(); PriorityQueue<Long> q = new PriorityQueue<>(); int[] f = new int[] {2, 3, 5}; q.offer(1L); vis.add(1L); long ans = 0; while (n-- > 0) { ans = q.poll(); for (int v : f) { long next = ans * v; if (vis.add(next)) { q.offer(next); } } } return (int) ans; } }
264
Ugly Number II
Medium
<p>An <strong>ugly number</strong> is a positive integer whose prime factors are limited to <code>2</code>, <code>3</code>, and <code>5</code>.</p> <p>Given an integer <code>n</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>ugly number</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 12 <strong>Explanation:</strong> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1690</code></li> </ul>
Hash Table; Math; Dynamic Programming; Heap (Priority Queue)
JavaScript
/** * @param {number} n * @return {number} */ var nthUglyNumber = function (n) { let dp = [1]; let p2 = 0, p3 = 0, p5 = 0; for (let i = 1; i < n; ++i) { const next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; dp[i] = Math.min(next2, Math.min(next3, next5)); if (dp[i] == next2) ++p2; if (dp[i] == next3) ++p3; if (dp[i] == next5) ++p5; dp.push(dp[i]); } return dp[n - 1]; };
264
Ugly Number II
Medium
<p>An <strong>ugly number</strong> is a positive integer whose prime factors are limited to <code>2</code>, <code>3</code>, and <code>5</code>.</p> <p>Given an integer <code>n</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>ugly number</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 12 <strong>Explanation:</strong> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1690</code></li> </ul>
Hash Table; Math; Dynamic Programming; Heap (Priority Queue)
Python
class Solution: def nthUglyNumber(self, n: int) -> int: h = [1] vis = {1} ans = 1 for _ in range(n): ans = heappop(h) for v in [2, 3, 5]: nxt = ans * v if nxt not in vis: vis.add(nxt) heappush(h, nxt) return ans
265
Paint House II
Hard
<p>There are a row of <code>n</code> houses, each house can be painted with one of the <code>k</code> colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.</p> <p>The cost of painting each house with a certain color is represented by an <code>n x k</code> cost matrix costs.</p> <ul> <li>For example, <code>costs[0][0]</code> is the cost of painting house <code>0</code> with color <code>0</code>; <code>costs[1][2]</code> is the cost of painting house <code>1</code> with color <code>2</code>, and so on...</li> </ul> <p>Return <em>the minimum cost to paint all houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> costs = [[1,5,3],[2,9,4]] <strong>Output:</strong> 5 <strong>Explanation:</strong> Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> costs = [[1,3],[2,4]] <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>costs.length == n</code></li> <li><code>costs[i].length == k</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>2 &lt;= k &lt;= 20</code></li> <li><code>1 &lt;= costs[i][j] &lt;= 20</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(nk)</code> runtime?</p>
Array; Dynamic Programming
C++
class Solution { public: int minCostII(vector<vector<int>>& costs) { int n = costs.size(), k = costs[0].size(); vector<int> f = costs[0]; for (int i = 1; i < n; ++i) { vector<int> g = costs[i]; for (int j = 0; j < k; ++j) { int t = INT_MAX; for (int h = 0; h < k; ++h) { if (h != j) { t = min(t, f[h]); } } g[j] += t; } f = move(g); } return *min_element(f.begin(), f.end()); } };
265
Paint House II
Hard
<p>There are a row of <code>n</code> houses, each house can be painted with one of the <code>k</code> colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.</p> <p>The cost of painting each house with a certain color is represented by an <code>n x k</code> cost matrix costs.</p> <ul> <li>For example, <code>costs[0][0]</code> is the cost of painting house <code>0</code> with color <code>0</code>; <code>costs[1][2]</code> is the cost of painting house <code>1</code> with color <code>2</code>, and so on...</li> </ul> <p>Return <em>the minimum cost to paint all houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> costs = [[1,5,3],[2,9,4]] <strong>Output:</strong> 5 <strong>Explanation:</strong> Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> costs = [[1,3],[2,4]] <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>costs.length == n</code></li> <li><code>costs[i].length == k</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>2 &lt;= k &lt;= 20</code></li> <li><code>1 &lt;= costs[i][j] &lt;= 20</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(nk)</code> runtime?</p>
Array; Dynamic Programming
Go
func minCostII(costs [][]int) int { n, k := len(costs), len(costs[0]) f := cp(costs[0]) for i := 1; i < n; i++ { g := cp(costs[i]) for j := 0; j < k; j++ { t := math.MaxInt32 for h := 0; h < k; h++ { if h != j && t > f[h] { t = f[h] } } g[j] += t } f = g } return slices.Min(f) } func cp(arr []int) []int { t := make([]int, len(arr)) copy(t, arr) return t }
265
Paint House II
Hard
<p>There are a row of <code>n</code> houses, each house can be painted with one of the <code>k</code> colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.</p> <p>The cost of painting each house with a certain color is represented by an <code>n x k</code> cost matrix costs.</p> <ul> <li>For example, <code>costs[0][0]</code> is the cost of painting house <code>0</code> with color <code>0</code>; <code>costs[1][2]</code> is the cost of painting house <code>1</code> with color <code>2</code>, and so on...</li> </ul> <p>Return <em>the minimum cost to paint all houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> costs = [[1,5,3],[2,9,4]] <strong>Output:</strong> 5 <strong>Explanation:</strong> Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> costs = [[1,3],[2,4]] <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>costs.length == n</code></li> <li><code>costs[i].length == k</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>2 &lt;= k &lt;= 20</code></li> <li><code>1 &lt;= costs[i][j] &lt;= 20</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(nk)</code> runtime?</p>
Array; Dynamic Programming
Java
class Solution { public int minCostII(int[][] costs) { int n = costs.length, k = costs[0].length; int[] f = costs[0].clone(); for (int i = 1; i < n; ++i) { int[] g = costs[i].clone(); for (int j = 0; j < k; ++j) { int t = Integer.MAX_VALUE; for (int h = 0; h < k; ++h) { if (h != j) { t = Math.min(t, f[h]); } } g[j] += t; } f = g; } return Arrays.stream(f).min().getAsInt(); } }
265
Paint House II
Hard
<p>There are a row of <code>n</code> houses, each house can be painted with one of the <code>k</code> colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.</p> <p>The cost of painting each house with a certain color is represented by an <code>n x k</code> cost matrix costs.</p> <ul> <li>For example, <code>costs[0][0]</code> is the cost of painting house <code>0</code> with color <code>0</code>; <code>costs[1][2]</code> is the cost of painting house <code>1</code> with color <code>2</code>, and so on...</li> </ul> <p>Return <em>the minimum cost to paint all houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> costs = [[1,5,3],[2,9,4]] <strong>Output:</strong> 5 <strong>Explanation:</strong> Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> costs = [[1,3],[2,4]] <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>costs.length == n</code></li> <li><code>costs[i].length == k</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>2 &lt;= k &lt;= 20</code></li> <li><code>1 &lt;= costs[i][j] &lt;= 20</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(nk)</code> runtime?</p>
Array; Dynamic Programming
Python
class Solution: def minCostII(self, costs: List[List[int]]) -> int: n, k = len(costs), len(costs[0]) f = costs[0][:] for i in range(1, n): g = costs[i][:] for j in range(k): t = min(f[h] for h in range(k) if h != j) g[j] += t f = g return min(f)
266
Palindrome Permutation
Easy
<p>Given a string <code>s</code>, return <code>true</code> <em>if a permutation of the string could form a </em><span data-keyword="palindrome-string"><em><strong>palindrome</strong></em></span><em> and </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;code&quot; <strong>Output:</strong> false </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aab&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;carerac&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5000</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String
C++
class Solution { public: bool canPermutePalindrome(string s) { vector<int> cnt(26); for (char& c : s) { ++cnt[c - 'a']; } int odd = 0; for (int x : cnt) { odd += x & 1; } return odd < 2; } };
266
Palindrome Permutation
Easy
<p>Given a string <code>s</code>, return <code>true</code> <em>if a permutation of the string could form a </em><span data-keyword="palindrome-string"><em><strong>palindrome</strong></em></span><em> and </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;code&quot; <strong>Output:</strong> false </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aab&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;carerac&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5000</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String
Go
func canPermutePalindrome(s string) bool { cnt := [26]int{} for _, c := range s { cnt[c-'a']++ } odd := 0 for _, x := range cnt { odd += x & 1 } return odd < 2 }
266
Palindrome Permutation
Easy
<p>Given a string <code>s</code>, return <code>true</code> <em>if a permutation of the string could form a </em><span data-keyword="palindrome-string"><em><strong>palindrome</strong></em></span><em> and </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;code&quot; <strong>Output:</strong> false </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aab&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;carerac&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5000</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String
Java
class Solution { public boolean canPermutePalindrome(String s) { int[] cnt = new int[26]; for (char c : s.toCharArray()) { ++cnt[c - 'a']; } int odd = 0; for (int x : cnt) { odd += x & 1; } return odd < 2; } }
266
Palindrome Permutation
Easy
<p>Given a string <code>s</code>, return <code>true</code> <em>if a permutation of the string could form a </em><span data-keyword="palindrome-string"><em><strong>palindrome</strong></em></span><em> and </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;code&quot; <strong>Output:</strong> false </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aab&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;carerac&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5000</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String
JavaScript
/** * @param {string} s * @return {boolean} */ var canPermutePalindrome = function (s) { const cnt = new Map(); for (const c of s) { cnt.set(c, (cnt.get(c) || 0) + 1); } return [...cnt.values()].filter(v => v % 2 === 1).length < 2; };
266
Palindrome Permutation
Easy
<p>Given a string <code>s</code>, return <code>true</code> <em>if a permutation of the string could form a </em><span data-keyword="palindrome-string"><em><strong>palindrome</strong></em></span><em> and </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;code&quot; <strong>Output:</strong> false </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aab&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;carerac&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5000</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String
Python
class Solution: def canPermutePalindrome(self, s: str) -> bool: return sum(v & 1 for v in Counter(s).values()) < 2
266
Palindrome Permutation
Easy
<p>Given a string <code>s</code>, return <code>true</code> <em>if a permutation of the string could form a </em><span data-keyword="palindrome-string"><em><strong>palindrome</strong></em></span><em> and </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;code&quot; <strong>Output:</strong> false </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aab&quot; <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;carerac&quot; <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5000</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String
TypeScript
function canPermutePalindrome(s: string): boolean { const cnt: number[] = Array(26).fill(0); for (const c of s) { ++cnt[c.charCodeAt(0) - 97]; } return cnt.filter(c => c % 2 === 1).length < 2; }
267
Palindrome Permutation II
Medium
<p>Given a string s, return <em>all the palindromic permutations (without duplicates) of it</em>.</p> <p>You may return the answer in <strong>any order</strong>. If <code>s</code> has no palindromic permutation, return an empty list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "aabb" <strong>Output:</strong> ["abba","baab"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abc" <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 16</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Hash Table; String; Backtracking
C++
class Solution { public: int n; vector<string> ans; unordered_map<char, int> cnt; vector<string> generatePalindromes(string s) { n = s.size(); for (char c : s) ++cnt[c]; string mid = ""; for (auto& [k, v] : cnt) { if (v & 1) { if (mid != "") { return ans; } mid += k; } } dfs(mid); return ans; } void dfs(string t) { if (t.size() == n) { ans.push_back(t); return; } for (auto& [k, v] : cnt) { if (v > 1) { v -= 2; dfs(k + t + k); v += 2; } } } };
267
Palindrome Permutation II
Medium
<p>Given a string s, return <em>all the palindromic permutations (without duplicates) of it</em>.</p> <p>You may return the answer in <strong>any order</strong>. If <code>s</code> has no palindromic permutation, return an empty list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "aabb" <strong>Output:</strong> ["abba","baab"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abc" <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 16</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Hash Table; String; Backtracking
Go
func generatePalindromes(s string) []string { cnt := map[byte]int{} for i := range s { cnt[s[i]]++ } mid := "" ans := []string{} for k, v := range cnt { if v%2 == 1 { if mid != "" { return ans } mid = string(k) } } var dfs func(t string) dfs = func(t string) { if len(t) == len(s) { ans = append(ans, t) return } for k, v := range cnt { if v > 1 { cnt[k] -= 2 c := string(k) dfs(c + t + c) cnt[k] += 2 } } } dfs(mid) return ans }
267
Palindrome Permutation II
Medium
<p>Given a string s, return <em>all the palindromic permutations (without duplicates) of it</em>.</p> <p>You may return the answer in <strong>any order</strong>. If <code>s</code> has no palindromic permutation, return an empty list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "aabb" <strong>Output:</strong> ["abba","baab"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abc" <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 16</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Hash Table; String; Backtracking
Java
class Solution { private List<String> ans = new ArrayList<>(); private int[] cnt = new int[26]; private int n; public List<String> generatePalindromes(String s) { n = s.length(); for (char c : s.toCharArray()) { ++cnt[c - 'a']; } String mid = ""; for (int i = 0; i < 26; ++i) { if (cnt[i] % 2 == 1) { if (!"".equals(mid)) { return ans; } mid = String.valueOf((char) (i + 'a')); } } dfs(mid); return ans; } private void dfs(String t) { if (t.length() == n) { ans.add(t); return; } for (int i = 0; i < 26; ++i) { if (cnt[i] > 1) { String c = String.valueOf((char) (i + 'a')); cnt[i] -= 2; dfs(c + t + c); cnt[i] += 2; } } } }
267
Palindrome Permutation II
Medium
<p>Given a string s, return <em>all the palindromic permutations (without duplicates) of it</em>.</p> <p>You may return the answer in <strong>any order</strong>. If <code>s</code> has no palindromic permutation, return an empty list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "aabb" <strong>Output:</strong> ["abba","baab"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "abc" <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 16</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Hash Table; String; Backtracking
Python
class Solution: def generatePalindromes(self, s: str) -> List[str]: def dfs(t): if len(t) == len(s): ans.append(t) return for c, v in cnt.items(): if v > 1: cnt[c] -= 2 dfs(c + t + c) cnt[c] += 2 cnt = Counter(s) mid = '' for c, v in cnt.items(): if v & 1: if mid: return [] mid = c cnt[c] -= 1 ans = [] dfs(mid) return ans
268
Missing Number
Easy
<p>Given an array <code>nums</code> containing <code>n</code> distinct numbers in the range <code>[0, n]</code>, return <em>the only number in the range that is missing from the array.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 3</code> since there are 3 numbers, so all numbers are in the range <code>[0,3]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 2</code> since there are 2 numbers, so all numbers are in the range <code>[0,2]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [9,6,4,2,3,5,7,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 9</code> since there are 9 numbers, so all numbers are in the range <code>[0,9]</code>. 8 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <div class="simple-translate-system-theme" id="simple-translate"> <div> <div class="simple-translate-button isShow" style="background-image: url(&quot;moz-extension://8a9ffb6b-7e69-4e93-aae1-436a1448eff6/icons/512.png&quot;); height: 22px; width: 22px; top: 318px; left: 36px;">&nbsp;</div> <div class="simple-translate-panel " style="width: 300px; height: 200px; top: 0px; left: 0px; font-size: 13px;"> <div class="simple-translate-result-wrapper" style="overflow: hidden;"> <div class="simple-translate-move" draggable="true">&nbsp;</div> <div class="simple-translate-result-contents"> <p class="simple-translate-result" dir="auto">&nbsp;</p> <p class="simple-translate-candidate" dir="auto">&nbsp;</p> </div> </div> </div> </div> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= n</code></li> <li>All the numbers of <code>nums</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you implement a solution using only <code>O(1)</code> extra space complexity and <code>O(n)</code> runtime complexity?</p>
Bit Manipulation; Array; Hash Table; Math; Binary Search; Sorting
C++
class Solution { public: int missingNumber(vector<int>& nums) { int n = nums.size(); int ans = n; for (int i = 0; i < n; ++i) { ans ^= (i ^ nums[i]); } return ans; } };
268
Missing Number
Easy
<p>Given an array <code>nums</code> containing <code>n</code> distinct numbers in the range <code>[0, n]</code>, return <em>the only number in the range that is missing from the array.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 3</code> since there are 3 numbers, so all numbers are in the range <code>[0,3]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 2</code> since there are 2 numbers, so all numbers are in the range <code>[0,2]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [9,6,4,2,3,5,7,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 9</code> since there are 9 numbers, so all numbers are in the range <code>[0,9]</code>. 8 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <div class="simple-translate-system-theme" id="simple-translate"> <div> <div class="simple-translate-button isShow" style="background-image: url(&quot;moz-extension://8a9ffb6b-7e69-4e93-aae1-436a1448eff6/icons/512.png&quot;); height: 22px; width: 22px; top: 318px; left: 36px;">&nbsp;</div> <div class="simple-translate-panel " style="width: 300px; height: 200px; top: 0px; left: 0px; font-size: 13px;"> <div class="simple-translate-result-wrapper" style="overflow: hidden;"> <div class="simple-translate-move" draggable="true">&nbsp;</div> <div class="simple-translate-result-contents"> <p class="simple-translate-result" dir="auto">&nbsp;</p> <p class="simple-translate-candidate" dir="auto">&nbsp;</p> </div> </div> </div> </div> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= n</code></li> <li>All the numbers of <code>nums</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you implement a solution using only <code>O(1)</code> extra space complexity and <code>O(n)</code> runtime complexity?</p>
Bit Manipulation; Array; Hash Table; Math; Binary Search; Sorting
Go
func missingNumber(nums []int) (ans int) { n := len(nums) ans = n for i, v := range nums { ans ^= (i ^ v) } return }
268
Missing Number
Easy
<p>Given an array <code>nums</code> containing <code>n</code> distinct numbers in the range <code>[0, n]</code>, return <em>the only number in the range that is missing from the array.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 3</code> since there are 3 numbers, so all numbers are in the range <code>[0,3]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 2</code> since there are 2 numbers, so all numbers are in the range <code>[0,2]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [9,6,4,2,3,5,7,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 9</code> since there are 9 numbers, so all numbers are in the range <code>[0,9]</code>. 8 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <div class="simple-translate-system-theme" id="simple-translate"> <div> <div class="simple-translate-button isShow" style="background-image: url(&quot;moz-extension://8a9ffb6b-7e69-4e93-aae1-436a1448eff6/icons/512.png&quot;); height: 22px; width: 22px; top: 318px; left: 36px;">&nbsp;</div> <div class="simple-translate-panel " style="width: 300px; height: 200px; top: 0px; left: 0px; font-size: 13px;"> <div class="simple-translate-result-wrapper" style="overflow: hidden;"> <div class="simple-translate-move" draggable="true">&nbsp;</div> <div class="simple-translate-result-contents"> <p class="simple-translate-result" dir="auto">&nbsp;</p> <p class="simple-translate-candidate" dir="auto">&nbsp;</p> </div> </div> </div> </div> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= n</code></li> <li>All the numbers of <code>nums</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you implement a solution using only <code>O(1)</code> extra space complexity and <code>O(n)</code> runtime complexity?</p>
Bit Manipulation; Array; Hash Table; Math; Binary Search; Sorting
Java
class Solution { public int missingNumber(int[] nums) { int n = nums.length; int ans = n; for (int i = 0; i < n; ++i) { ans ^= (i ^ nums[i]); } return ans; } }
268
Missing Number
Easy
<p>Given an array <code>nums</code> containing <code>n</code> distinct numbers in the range <code>[0, n]</code>, return <em>the only number in the range that is missing from the array.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 3</code> since there are 3 numbers, so all numbers are in the range <code>[0,3]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 2</code> since there are 2 numbers, so all numbers are in the range <code>[0,2]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [9,6,4,2,3,5,7,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 9</code> since there are 9 numbers, so all numbers are in the range <code>[0,9]</code>. 8 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <div class="simple-translate-system-theme" id="simple-translate"> <div> <div class="simple-translate-button isShow" style="background-image: url(&quot;moz-extension://8a9ffb6b-7e69-4e93-aae1-436a1448eff6/icons/512.png&quot;); height: 22px; width: 22px; top: 318px; left: 36px;">&nbsp;</div> <div class="simple-translate-panel " style="width: 300px; height: 200px; top: 0px; left: 0px; font-size: 13px;"> <div class="simple-translate-result-wrapper" style="overflow: hidden;"> <div class="simple-translate-move" draggable="true">&nbsp;</div> <div class="simple-translate-result-contents"> <p class="simple-translate-result" dir="auto">&nbsp;</p> <p class="simple-translate-candidate" dir="auto">&nbsp;</p> </div> </div> </div> </div> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= n</code></li> <li>All the numbers of <code>nums</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you implement a solution using only <code>O(1)</code> extra space complexity and <code>O(n)</code> runtime complexity?</p>
Bit Manipulation; Array; Hash Table; Math; Binary Search; Sorting
JavaScript
/** * @param {number[]} nums * @return {number} */ var missingNumber = function (nums) { const n = nums.length; let ans = n; for (let i = 0; i < n; ++i) { ans ^= i ^ nums[i]; } return ans; };