Datasets:

QID
int64
1
2.85k
titleSlug
stringlengths
3
77
Hints
sequence
Code
stringlengths
80
1.34k
Body
stringlengths
190
4.55k
Difficulty
stringclasses
3 values
Topics
sequence
Definitions
stringclasses
14 values
Solutions
sequence
225
implement-stack-using-queues
[]
var MyStack = function() { }; /** * @param {number} x * @return {void} */ MyStack.prototype.push = function(x) { }; /** * @return {number} */ MyStack.prototype.pop = function() { }; /** * @return {number} */ MyStack.prototype.top = function() { }; /** * @return {boolean} */ MyStack.prototype.empty = function() { }; /** * Your MyStack object will be instantiated and called as such: * var obj = new MyStack() * obj.push(x) * var param_2 = obj.pop() * var param_3 = obj.top() * var param_4 = obj.empty() */
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty). Implement the MyStack class: void push(int x) Pushes element x to the top of the stack. int pop() Removes the element on the top of the stack and returns it. int top() Returns the element on the top of the stack. boolean empty() Returns true if the stack is empty, false otherwise. Notes: You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid. Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.   Example 1: Input ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 2, 2, false] Explanation MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False   Constraints: 1 <= x <= 9 At most 100 calls will be made to push, pop, top, and empty. All the calls to pop and top are valid.   Follow-up: Can you implement the stack using only one queue?
Easy
[ "stack", "design", "queue" ]
[ "const MyStack = function() {\n this.stack = []\n};\n\n\nMyStack.prototype.push = function(x) {\n this.stack.push(x)\n};\n\n\nMyStack.prototype.pop = function() {\n return this.stack.pop()\n};\n\n\nMyStack.prototype.top = function() {\n return this.stack.length === 0 ? null : this.stack[this.stack.length - 1]\n};\n\n\nMyStack.prototype.empty = function() {\n return this.stack.length === 0\n};" ]
226
invert-binary-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {TreeNode} */ var invertTree = function(root) { };
Given the root of a binary tree, invert the tree, and return its root.   Example 1: Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1] Example 2: Input: root = [2,1,3] Output: [2,3,1] Example 3: Input: root = [] Output: []   Constraints: The number of nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100
Easy
[ "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * 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) * } */
[ "const invertTree = function (root) {\n if (root) {\n ;[root.left, root.right] = [invertTree(root.right), invertTree(root.left)]\n }\n return root\n}", "const invertTree = function (root) {\n if (!root) return root\n let queue = [root]\n while (queue.length) {\n let node = queue.shift()\n if (node.left) {\n queue.push(node.left)\n }\n if (node.right) {\n queue.push(node.right)\n }\n let left = node.left\n node.left = node.right\n node.right = left\n }\n return root\n}\n\n// anoother\n\n\n\nconst invertTree = function(root) {\n if(root == null) return root\n let tmp = root.left\n root.left = invertTree(root.right)\n root.right = invertTree(tmp)\n return root\n};" ]
227
basic-calculator-ii
[]
/** * @param {string} s * @return {number} */ var calculate = function(s) { };
Given a string s which represents an expression, evaluate this expression and return its value.  The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().   Example 1: Input: s = "3+2*2" Output: 7 Example 2: Input: s = " 3/2 " Output: 1 Example 3: Input: s = " 3+5 / 2 " Output: 5   Constraints: 1 <= s.length <= 3 * 105 s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces. s represents a valid expression. All the integers in the expression are non-negative integers in the range [0, 231 - 1]. The answer is guaranteed to fit in a 32-bit integer.
Medium
[ "math", "string", "stack" ]
[ "const calculate = function(s) {\n const stk = []\n let op = '+', num = 0\n s = s.trim()\n const isDigit = ch => ch >= '0' && ch <= '9'\n for(let i = 0, n = s.length; i < n; i++) {\n const ch = s[i]\n if(ch === ' ') continue\n if(isDigit(ch)) {\n num = (+num) * 10 + (+ch)\n } \n if(!isDigit(ch) || i === n - 1) {\n if(op === '-') stk.push(-num)\n else if(op === '+') stk.push(num)\n else if(op === '*') stk.push(stk.pop() * num)\n else if(op === '/') stk.push(~~(stk.pop() / num))\n \n op = ch\n num = 0\n }\n }\n let res = 0 \n for(const e of stk) res += e\n\n return res\n};", "const calculate = function(s) {\n const stack = [], n = s.length\n let op = '+', num = 0\n for(let i = 0; i < n; i++) {\n const isNumber = s[i] >= '0' && s[i] <= '9'\n if(isNumber) num = num * 10 + (+s[i])\n if((!isNumber && s[i] !== ' ') || i === n - 1) {\n if(op === '+') stack.push(num)\n else if(op === '-') stack.push(-num)\n else if(op === '*') stack.push(stack.pop() * num)\n else if(op === '/') stack.push(~~(stack.pop() / num))\n op = s[i]\n num = 0\n }\n }\n \n return stack.reduce((ac, e) => ac + e, 0)\n};", "const calculate = function(s) {\n if(s == null || s.length === 0) return 0\n let sum = 0, num = 0, op = '+', tmp = 0\n const stack = []\n for(let i = 0; i < s.length; i++) {\n const ch = s[i]\n const isInt = ch => ch >= '0' && ch <= '9'\n if(isInt(ch)) {\n num = num * 10 + (+ch)\n }\n if((!isInt(ch) && ch !== ' ') || i === s.length - 1) {\n if(op === '+') {\n sum += tmp\n tmp = num\n }\n else if(op === '-') {\n sum += tmp\n tmp = - num\n }\n else if(op === '*') {\n tmp *= num\n }\n else if(op === '/') {\n tmp = ~~(tmp / num)\n }\n op = ch\n num = 0\n }\n\n }\n\n return sum + tmp\n}" ]
228
summary-ranges
[]
/** * @param {number[]} nums * @return {string[]} */ var summaryRanges = function(nums) { };
You are given a sorted unique integer array nums. A range [a,b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums. Each range [a,b] in the list should be output as: "a->b" if a != b "a" if a == b   Example 1: Input: nums = [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: The ranges are: [0,2] --> "0->2" [4,5] --> "4->5" [7,7] --> "7" Example 2: Input: nums = [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] Explanation: The ranges are: [0,0] --> "0" [2,4] --> "2->4" [6,6] --> "6" [8,9] --> "8->9"   Constraints: 0 <= nums.length <= 20 -231 <= nums[i] <= 231 - 1 All the values of nums are unique. nums is sorted in ascending order.
Easy
[ "array" ]
[ "const summaryRanges = function(nums) {\n if (nums == null || nums.length === 0) return []\n const res = []\n if (nums.length === 1) return [`${nums[0]}`]\n let start = nums[0]\n let end = nums[0]\n let endVal = end\n for (let i = 1, len = nums.length; i < len; i++) {\n let cur = nums[i]\n if (cur - end > 1) {\n endVal = end\n insert(res, start, end)\n start = cur\n end = cur\n } else {\n end = cur\n }\n }\n if (endVal !== end) {\n insert(res, start, end)\n }\n return res\n}\n\nfunction insert(arr, start, end) {\n if (start === end) {\n arr.push(`${start}`)\n } else {\n arr.push(`${start}->${end}`)\n }\n}", "const summaryRanges = nums => {\n if (!nums || nums.length === 0) {\n return [];\n }\n const returnArray = [];\n let tempIdx = 0;\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] + 1 !== nums[i + 1]) {\n if (tempIdx === i) {\n returnArray.push(nums[tempIdx].toString());\n } else {\n returnArray.push(nums[tempIdx].toString() + \"->\" + nums[i].toString());\n }\n tempIdx = i + 1;\n }\n }\n\n return returnArray;\n};" ]
229
majority-element-ii
[ "How many majority elements could it possibly have?\r\n<br/>\r\nDo you have a better hint? <a href=\"mailto:[email protected]?subject=Hints for Majority Element II\" target=\"_blank\">Suggest it</a>!" ]
/** * @param {number[]} nums * @return {number[]} */ var majorityElement = function(nums) { };
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.   Example 1: Input: nums = [3,2,3] Output: [3] Example 2: Input: nums = [1] Output: [1] Example 3: Input: nums = [1,2] Output: [1,2]   Constraints: 1 <= nums.length <= 5 * 104 -109 <= nums[i] <= 109   Follow up: Could you solve the problem in linear time and in O(1) space?
Medium
[ "array", "hash-table", "sorting", "counting" ]
[ "const majorityElement = function(nums) {\n const res = []\n const hash = {}\n const len = nums.length\n const limit = Math.floor(len / 3)\n nums.forEach(el => {\n if(hash.hasOwnProperty(''+el)) {\n hash[el] += 1\n } else {\n hash[el] = 1\n }\n })\n Object.keys(hash).forEach(el => {\n if(hash[el] > limit) res.push(+el)\n })\n \n return res\n};" ]
230
kth-smallest-element-in-a-bst
[ "Try to utilize the property of a BST.", "Try in-order traversal. (Credits to @chan13)", "What if you could modify the BST node's structure?", "The optimal runtime complexity is O(height of BST)." ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} k * @return {number} */ var kthSmallest = function(root, k) { };
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.   Example 1: Input: root = [3,1,4,null,2], k = 1 Output: 1 Example 2: Input: root = [5,3,6,2,4,null,null,1], k = 3 Output: 3   Constraints: The number of nodes in the tree is n. 1 <= k <= n <= 104 0 <= Node.val <= 104   Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
Medium
[ "tree", "depth-first-search", "binary-search-tree", "binary-tree" ]
/** * 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) * } */
[ "const kthSmallest = function (root, k) {\n const st = []\n while (root !== null) {\n st.push(root)\n root = root.left\n }\n while (k !== 0) {\n const n = st.pop()\n k--\n if (k === 0) return n.val\n let right = n.right\n while (right !== null) {\n st.push(right)\n right = right.left\n }\n }\n return -1\n}" ]
231
power-of-two
[]
/** * @param {number} n * @return {boolean} */ var isPowerOfTwo = function(n) { };
Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x.   Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n = 16 Output: true Explanation: 24 = 16 Example 3: Input: n = 3 Output: false   Constraints: -231 <= n <= 231 - 1   Follow up: Could you solve it without loops/recursion?
Easy
[ "math", "bit-manipulation", "recursion" ]
[ "const isPowerOfTwo = function(n) {\n let tmp = 0\n let idx = 0\n while(tmp <= n) {\n if((tmp = Math.pow(2, idx)) === n) {\n return true\n } else {\n idx += 1\n }\n }\n return false\n};", "const isPowerOfTwo = function(n) {\n return Math.log2(n)%1 === 0\n};", "const isPowerOfTwo = n => n < 1 ? false : Number.MAX_VALUE % n === 0", "const isPowerOfTwo = x => x > 0 ? !(x & (x - 1)) : false;" ]
232
implement-queue-using-stacks
[]
var MyQueue = function() { }; /** * @param {number} x * @return {void} */ MyQueue.prototype.push = function(x) { }; /** * @return {number} */ MyQueue.prototype.pop = function() { }; /** * @return {number} */ MyQueue.prototype.peek = function() { }; /** * @return {boolean} */ MyQueue.prototype.empty = function() { }; /** * Your MyQueue object will be instantiated and called as such: * var obj = new MyQueue() * obj.push(x) * var param_2 = obj.pop() * var param_3 = obj.peek() * var param_4 = obj.empty() */
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). Implement the MyQueue class: void push(int x) Pushes element x to the back of the queue. int pop() Removes the element from the front of the queue and returns it. int peek() Returns the element at the front of the queue. boolean empty() Returns true if the queue is empty, false otherwise. Notes: You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid. Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.   Example 1: Input ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 1, 1, false] Explanation MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false   Constraints: 1 <= x <= 9 At most 100 calls will be made to push, pop, peek, and empty. All the calls to pop and peek are valid.   Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.
Easy
[ "stack", "design", "queue" ]
[ "var MyQueue = function() {\n this.input = []\n this.output = []\n};\n\n\nMyQueue.prototype.push = function(x) {\n this.input.push(x)\n};\n\n\nMyQueue.prototype.pop = function() {\n if(this.output.length === 0) {\n while(this.input.length) {\n this.output.push(this.input.pop())\n }\n }\n return this.output.pop()\n};\n\n\nMyQueue.prototype.peek = function() {\n return this.output[this.output.length - 1] || this.input[0]\n};\n\n\nMyQueue.prototype.empty = function() {\n return this.input.length === 0 && this.output.length === 0\n};" ]
233
number-of-digit-one
[ "Beware of overflow." ]
/** * @param {number} n * @return {number} */ var countDigitOne = function(n) { };
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.   Example 1: Input: n = 13 Output: 6 Example 2: Input: n = 0 Output: 0   Constraints: 0 <= n <= 109
Hard
[ "math", "dynamic-programming", "recursion" ]
[ "const countDigitOne = function(n) {\n let count = 0\n for (let m = 1; m <= n; m *= 10) {\n const a = Math.floor(n / m)\n const b = n % m\n if (a % 10 > 1) {\n count += (Math.floor(a / 10) + 1) * m\n } else if (a % 10 === 1) {\n count += Math.floor(a / 10) * m + b + 1\n } else {\n count += Math.floor(a / 10) * m\n }\n }\n return count\n}", "const countDigitOne = function (n) {\n if (n <= 0) return 0\n let ones = 0\n for (let i = 1, q = n; i <= n; i *= 10, q = (q / 10) >> 0) {\n const pre = (n / (i * 10)) >> 0,\n cur = q % 10,\n suf = n % i\n ones += pre * i\n ones += 1 < cur ? i : 1 == cur ? suf + 1 : 0\n }\n return ones\n}", "const countDigitOne = function(n) {\n let res = 0, factor = 1, lower = 0, cur = 0, higher = 0\n while(~~(n / factor) !== 0) {\n lower = n - (~~(n / factor)) * factor\n cur = (~~(n / factor)) % 10\n higher = ~~(n / (factor * 10))\n switch(cur) {\n case 0:\n res += higher * factor\n break\n case 1:\n res += higher * factor + lower + 1\n break\n default:\n res += (higher + 1) * factor\n break\n }\n factor *= 10\n }\n \n return res\n};" ]
234
palindrome-linked-list
[]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {boolean} */ var isPalindrome = function(head) { };
Given the head of a singly linked list, return true if it is a palindrome or false otherwise.   Example 1: Input: head = [1,2,2,1] Output: true Example 2: Input: head = [1,2] Output: false   Constraints: The number of nodes in the list is in the range [1, 105]. 0 <= Node.val <= 9   Follow up: Could you do it in O(n) time and O(1) space?
Easy
[ "linked-list", "two-pointers", "stack", "recursion" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "const isPalindrome = function(head) {\n const arr = [] \n while(head != null) {\n arr.push(head.val)\n head = head.next\n }\n let start = 0\n let end = arr.length - 1\n while(start < end) {\n if(arr[start] !== arr[end]) {\n return false\n }\n start++\n end--\n }\n return true\n};" ]
235
lowest-common-ancestor-of-a-binary-search-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @param {TreeNode} p * @param {TreeNode} q * @return {TreeNode} */ var lowestCommonAncestor = function(root, p, q) { };
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”   Example 1: Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6. Example 2: Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [2,1], p = 2, q = 1 Output: 2   Constraints: The number of nodes in the tree is in the range [2, 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the BST.
Medium
[ "tree", "depth-first-search", "binary-search-tree", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */
[ "const lowestCommonAncestor = function(root, p, q) {\n if(root == null || root == p || root == q) return root\n const left = lowestCommonAncestor(root.left, p, q)\n const right = lowestCommonAncestor(root.right, p, q)\n if(left && right) return root\n return left || right\n};", "const lowestCommonAncestor = function(root, p, q) {\n while((root.val - p.val) * (root.val - q.val) > 0) {\n root = root.val > p.val ? root.left : root.right\n }\n return root\n};" ]
236
lowest-common-ancestor-of-a-binary-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @param {TreeNode} p * @param {TreeNode} q * @return {TreeNode} */ var lowestCommonAncestor = function(root, p, q) { };
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”   Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [1,2], p = 1, q = 2 Output: 1   Constraints: The number of nodes in the tree is in the range [2, 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the tree.
Medium
[ "tree", "depth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */
[ "const lowestCommonAncestor = function(root, p, q) {\n const arr = []\n traverse(root, [], arr)\n let pii\n let qii\n // in same path\n for(let i = 0; i < arr.length; i++) {\n let pi = arr[i].indexOf(p.val)\n let qi = arr[i].indexOf(q.val)\n if(pi !== -1) pii = [i, pi]\n if(qi !== -1) qii = [i, qi]\n if(pi !== -1 && qi !== -1) {\n return new TreeNode( pi <= qi ? p.val : q.val )\n }\n }\n\n const len = Math.min(arr[pii[0]].length, arr[qii[0]].length)\n const pp = arr[pii[0]]\n const qp = arr[qii[0]]\n for(let i = 0; i < len; i++) {\n if(pp[i] !== qp[i]) return new TreeNode(pp[i - 1])\n }\n};\n\nfunction traverse(node, path = [], arr) {\n if(node == null) return\n path.push(node.val)\n if(node.left === null && node.right === null) {\n arr.push(path.slice(0))\n return\n }\n traverse(node.left, path.slice(0), arr)\n traverse(node.right, path.slice(0), arr)\n}", "const lowestCommonAncestor = function(root, p, q) {\n if(root === null || root === p || root === q) return root;\n const left = lowestCommonAncestor(root.left, p, q);\n const right = lowestCommonAncestor(root.right, p, q);\n if(left && right) return root;\n return left ? left : right;\n};", "const lowestCommonAncestor = function(root, p, q) {\n if(root == null || root === p || root === q) return root\n const left = lowestCommonAncestor(root.left, p, q)\n const right = lowestCommonAncestor(root.right, p, q)\n if(left && right) return root\n return left || right\n};" ]
237
delete-node-in-a-linked-list
[]
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} node * @return {void} Do not return anything, modify node in-place instead. */ var deleteNode = function(node) { };
There is a singly-linked list head and we want to delete a node node in it. You are given the node to be deleted node. You will not be given access to the first node of head. All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: The value of the given node should not exist in the linked list. The number of nodes in the linked list should decrease by one. All the values before node should be in the same order. All the values after node should be in the same order. Custom testing: For the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list. We will build the linked list and pass the node to your function. The output will be the entire list after calling your function.   Example 1: Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. Example 2: Input: head = [4,5,1,9], node = 1 Output: [4,5,9] Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.   Constraints: The number of the nodes in the given list is in the range [2, 1000]. -1000 <= Node.val <= 1000 The value of each node in the list is unique. The node to be deleted is in the list and is not a tail node.
Medium
[ "linked-list" ]
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */
[ "const deleteNode = function(node) {\n if (node.next !== null) {\n node.val = node.next.val;\n node.next = node.next.next;\n }\n};" ]
238
product-of-array-except-self
[]
/** * @param {number[]} nums * @return {number[]} */ var productExceptSelf = function(nums) { };
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation.   Example 1: Input: nums = [1,2,3,4] Output: [24,12,8,6] Example 2: Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0]   Constraints: 2 <= nums.length <= 105 -30 <= nums[i] <= 30 The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.   Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
Medium
[ "array", "prefix-sum" ]
[ "const productExceptSelf = function(nums) {\n const zeroIdx = new Set();\n const p = nums.reduce((ac, el, idx) => {\n if (el === 0) {\n zeroIdx.add(idx);\n return ac;\n } else {\n return ac * el;\n }\n }, 1);\n const res = [];\n for (let i = 0; i < nums.length; i++) {\n if (zeroIdx.size > 1) {\n res.push(0);\n } else if (zeroIdx.size === 1) {\n res.push(i === [...zeroIdx.values()][0] ? p : 0);\n } else {\n res.push(p / nums[i]);\n }\n }\n return res;\n};" ]
239
sliding-window-maximum
[ "How about using a data structure such as deque (double-ended queue)?", "The queue size need not be the same as the window’s size.", "Remove redundant elements and the queue should store only elements that need to be considered." ]
/** * @param {number[]} nums * @param {number} k * @return {number[]} */ var maxSlidingWindow = function(nums, k) { };
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.   Example 1: Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [3,3,5,5,6,7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Example 2: Input: nums = [1], k = 1 Output: [1]   Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 1 <= k <= nums.length
Hard
[ "array", "queue", "sliding-window", "heap-priority-queue", "monotonic-queue" ]
[ "const maxSlidingWindow = function(nums, k) {\n const n = nums.length\n const stk = []\n const res = []\n \n for(let i = 0; i < n; i++) {\n while(stk.length && stk[0] < i - k + 1) {\n stk.shift()\n }\n while(stk.length && nums[stk[stk.length - 1]] <= nums[i]) {\n stk.pop()\n }\n stk.push(i)\n if(i >= k - 1) {\n res.push(nums[stk[0]])\n }\n }\n \n return res\n};", "var maxSlidingWindow = function (nums, k) {\n if (k === 0) return []\n const deque = new Deque()\n for (let i = 0; i < k - 1; i++) {\n while (!deque.isEmpty() && deque.last().val <= nums[i]) deque.pop()\n deque.enqueue({ val: nums[i], idx: i })\n }\n const result = []\n for (let i = k - 1; i < nums.length; i++) {\n if (!deque.isEmpty() && deque.first().idx <= i - k) deque.dequeue()\n while (!deque.isEmpty() && deque.last().val <= nums[i]) deque.pop()\n deque.enqueue({ val: nums[i], idx: i })\n result.push(deque.first().val)\n }\n return result\n}\n\nclass Deque {\n constructor() {\n this.head = new Node()\n this.tail = this.head\n }\n\n isEmpty() {\n return this.head.next === null\n }\n\n first() {\n return this.head.next.value\n }\n\n last() {\n return this.tail.value\n }\n\n dequeue() {\n this.head = this.head.next\n this.head.prev = null\n }\n\n enqueue(value) {\n this.tail.next = new Node(value)\n this.tail.next.prev = this.tail\n this.tail = this.tail.next\n }\n\n pop() {\n this.tail = this.tail.prev\n this.tail.next = null\n }\n}\n\nclass Node {\n constructor(value) {\n this.value = value\n this.next = null\n this.prev = null\n }\n}" ]
240
search-a-2d-matrix-ii
[]
/** * @param {number[][]} matrix * @param {number} target * @return {boolean} */ var searchMatrix = function(matrix, target) { };
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom.   Example 1: Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 Output: true Example 2: Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 Output: false   Constraints: m == matrix.length n == matrix[i].length 1 <= n, m <= 300 -109 <= matrix[i][j] <= 109 All the integers in each row are sorted in ascending order. All the integers in each column are sorted in ascending order. -109 <= target <= 109
Medium
[ "array", "binary-search", "divide-and-conquer", "matrix" ]
[ "const searchMatrix = function(matrix, target) {\n if (matrix == null || matrix.length == 0) {\n return false;\n }\n\n const length = matrix.length;\n for (let i = 0; i < length; i++) {\n const row = matrix.shift();\n let left = 0,\n right = row.length - 1;\n\n while (left <= right) {\n const mid = left + parseInt((right - left) / 2);\n\n if (row[mid] == target) {\n return true;\n } else if (row[mid] > target) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n }\n\n return false;\n};" ]
241
different-ways-to-add-parentheses
[]
/** * @param {string} expression * @return {number[]} */ var diffWaysToCompute = function(expression) { };
Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order. The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104.   Example 1: Input: expression = "2-1-1" Output: [0,2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2 Example 2: Input: expression = "2*3-4*5" Output: [-34,-14,-10,-10,10] Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10   Constraints: 1 <= expression.length <= 20 expression consists of digits and the operator '+', '-', and '*'. All the integer values in the input expression are in the range [0, 99].
Medium
[ "math", "string", "dynamic-programming", "recursion", "memoization" ]
[ "const diffWaysToCompute = function(input) {\n const res = [];\n let left;\n let right;\n for (let i = 0; i < input.length; i++) {\n if (input[i] < \"0\") {\n left = diffWaysToCompute(input.slice(0, i));\n right = diffWaysToCompute(input.slice(i + 1));\n for (let rl of left) {\n for (let rr of right) {\n switch (input[i]) {\n case \"+\":\n res.push(rl + rr);\n break;\n case \"-\":\n res.push(rl - rr);\n break;\n case \"*\":\n res.push(rl * rr);\n break;\n default:\n break;\n }\n }\n }\n }\n }\n if (res.length === 0) {\n res.push(+input);\n }\n return res;\n};" ]
242
valid-anagram
[]
/** * @param {string} s * @param {string} t * @return {boolean} */ var isAnagram = function(s, t) { };
Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.   Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false   Constraints: 1 <= s.length, t.length <= 5 * 104 s and t consist of lowercase English letters.   Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Easy
[ "hash-table", "string", "sorting" ]
[ "const isAnagram = function(s, t) {\n if (s.length !== t.length) return false;\n const sh = strHash(s);\n const th = strHash(t);\n for (let key in sh) {\n if (sh.hasOwnProperty(key) && sh[key] !== th[key]) {\n return false;\n }\n }\n return true;\n};\n\nfunction strHash(str) {\n let res = {};\n for (let i = 0; i < str.length; i++) {\n if (res.hasOwnProperty(str[i])) {\n res[str[i]] += 1;\n } else {\n res[str[i]] = 1;\n }\n }\n return res;\n}" ]
257
binary-tree-paths
[]
/** * 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 {string[]} */ var binaryTreePaths = function(root) { };
Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children.   Example 1: Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"] Example 2: Input: root = [1] Output: ["1"]   Constraints: The number of nodes in the tree is in the range [1, 100]. -100 <= Node.val <= 100
Easy
[ "string", "backtracking", "tree", "depth-first-search", "binary-tree" ]
/** * 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) * } */
[ "const binaryTreePaths = function(root) {\n const res = [];\n traverse(root, res, []);\n return res;\n};\n\nfunction traverse(node, res, p) {\n if (node === null) return;\n p.push(node.val);\n if (node.left === null && node.right === null) {\n res.push(p.join(\"->\"));\n }\n if (node.left) {\n traverse(node.left, res, p.slice(0));\n }\n if (node.right) {\n traverse(node.right, res, p.slice(0));\n }\n}" ]
258
add-digits
[ "A naive implementation of the above process is trivial. Could you come up with other methods?", "What are all the possible results?", "How do they occur, periodically or randomly?", "You may find this <a href=\"https://en.wikipedia.org/wiki/Digital_root\" target=\"_blank\">Wikipedia article</a> useful." ]
/** * @param {number} num * @return {number} */ var addDigits = function(num) { };
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.   Example 1: Input: num = 38 Output: 2 Explanation: The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. Example 2: Input: num = 0 Output: 0   Constraints: 0 <= num <= 231 - 1   Follow up: Could you do it without any loop/recursion in O(1) runtime?
Easy
[ "math", "simulation", "number-theory" ]
[ "const addDigits = function(num) {\n let arr = (\"\" + num).split(\"\");\n let res = num;\n\n while (arr.length > 1) {\n res = arr.reduce((ac, el) => +ac + +el, 0);\n arr = (\"\" + res).split(\"\");\n }\n return +res;\n};", "const addDigits = function(num) {\n return 1 + (num - 1) % 9;\n};\n\nconsole.log(addDigits(0));\nconsole.log(addDigits(38));" ]
260
single-number-iii
[]
/** * @param {number[]} nums * @return {number[]} */ var singleNumber = function(nums) { };
Given an integer array nums, 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 any order. You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.   Example 1: Input: nums = [1,2,1,3,2,5] Output: [3,5] Explanation: [5, 3] is also a valid answer. Example 2: Input: nums = [-1,0] Output: [-1,0] Example 3: Input: nums = [0,1] Output: [1,0]   Constraints: 2 <= nums.length <= 3 * 104 -231 <= nums[i] <= 231 - 1 Each integer in nums will appear twice, only two integers will appear once.
Medium
[ "array", "bit-manipulation" ]
[ "const singleNumber = function(nums) {\n const hash = {};\n nums.forEach((el, idx) => {\n if (hash.hasOwnProperty(el)) {\n hash[el] += 1;\n delete hash[el];\n } else {\n hash[el] = 1;\n }\n });\n return Object.keys(hash).map(el => +el);\n};", "const singleNumber = function(nums) {\n const s = new Set()\n for(let el of nums) {\n if(s.has(el)) s.delete(el)\n else s.add(el)\n }\n return Array.from(s)\n};", "const singleNumber = function (nums) {\n const res = Array(2).fill(0)\n const x = nums.reduce((acc, v) => acc ^ v, 0)\n const partition = x & ~(x - 1)\n for (let i = 0; i < nums.length; i++) {\n if (partition & nums[i]) {\n res[1] ^= nums[i]\n } else {\n res[0] ^= nums[i]\n }\n }\n return res\n}" ]
263
ugly-number
[]
/** * @param {number} n * @return {boolean} */ var isUgly = function(n) { };
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return true if n is an ugly number.   Example 1: Input: n = 6 Output: true Explanation: 6 = 2 × 3 Example 2: Input: n = 1 Output: true Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. Example 3: Input: n = 14 Output: false Explanation: 14 is not ugly since it includes the prime factor 7.   Constraints: -231 <= n <= 231 - 1
Easy
[ "math" ]
[ "const isUgly = function(num) {\n if (num < 1) return false\n while (num >= 2) {\n if (num % 2 === 0) num = num / 2\n else if (num % 3 === 0) num = num / 3\n else if (num % 5 === 0) num = num / 5\n else return false\n }\n return true\n}" ]
264
ugly-number-ii
[ "The naive approach is to call <code>isUgly</code> for every number until you reach the n<sup>th</sup> one. Most numbers are <i>not</i> ugly. Try to focus your effort on generating only the ugly ones.", "An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.", "The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L<sub>1</sub>, L<sub>2</sub>, and L<sub>3</sub>.", "Assume you have U<sub>k</sub>, the k<sup>th</sup> ugly number. Then U<sub>k+1</sub> must be Min(L<sub>1</sub> * 2, L<sub>2</sub> * 3, L<sub>3</sub> * 5)." ]
/** * @param {number} n * @return {number} */ var nthUglyNumber = function(n) { };
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return the nth ugly number.   Example 1: Input: n = 10 Output: 12 Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. Example 2: Input: n = 1 Output: 1 Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.   Constraints: 1 <= n <= 1690
Medium
[ "hash-table", "math", "dynamic-programming", "heap-priority-queue" ]
[ "const nthUglyNumber = function (n) {\n if (n <= 0) return false\n if (n === 1) return true\n let t2 = 0,\n t3 = 0,\n t5 = 0\n const k = Array(n).fill(1)\n k[0] = 1\n for (let i = 1; i < n; i++) {\n k[i] = Math.min(k[t2] * 2, k[t3] * 3, k[t5] * 5)\n if (k[i] == k[t2] * 2) t2++\n if (k[i] == k[t3] * 3) t3++\n if (k[i] == k[t5] * 5) t5++\n }\n return k[n - 1]\n}" ]
268
missing-number
[]
/** * @param {number[]} nums * @return {number} */ var missingNumber = function(nums) { };
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.   Example 1: Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. Example 2: Input: nums = [0,1] Output: 2 Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. Example 3: Input: nums = [9,6,4,2,3,5,7,0,1] Output: 8 Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.   Constraints: n == nums.length 1 <= n <= 104 0 <= nums[i] <= n All the numbers of nums are unique.   Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
Easy
[ "array", "hash-table", "math", "binary-search", "bit-manipulation", "sorting" ]
[ "const missingNumber = function(nums) {\n const n = nums.length\n let xor = 0 ^ nums[0]\n for(let i = 1; i < n; i++) xor = xor ^ i ^ nums[i]\n return xor ^ n\n};", "const missingNumber = function(nums) {\n const len = nums.length;\n return (len * (len + 1)) / 2 - sum(nums);\n};\n\nfunction sum(arr) {\n return arr.reduce((ac, el) => ac + el, 0);\n}", "var missingNumber = function(nums) {\n const n = nums.length\n const sum = nums.reduce((ac, e) => ac + e, 0)\n const target = (n + 1) * n / 2\n return target - sum\n};" ]
273
integer-to-english-words
[ "Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.", "Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.", "There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)" ]
/** * @param {number} num * @return {string} */ var numberToWords = function(num) { };
Convert a non-negative integer num to its English words representation.   Example 1: Input: num = 123 Output: "One Hundred Twenty Three" Example 2: Input: num = 12345 Output: "Twelve Thousand Three Hundred Forty Five" Example 3: Input: num = 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"   Constraints: 0 <= num <= 231 - 1
Hard
[ "math", "string", "recursion" ]
[ "const numberToWords = function(num) {\n if (num === 0) return \"Zero\";\n if (num <= 20) return translations.get(num);\n const result = [];\n\n for (let [value, translation] of translations) {\n const times = Math.floor(num / value);\n if (times === 0) continue;\n num -= times * value;\n if (times === 1 && value >= 100) {\n result.push(\"One\", translation);\n continue;\n }\n if (times === 1) {\n result.push(translation);\n continue;\n }\n result.push(numberToWords(times), translation);\n }\n return result.join(\" \");\n};\n\nconst translations = new Map([\n [1000000000, \"Billion\"],\n [1000000, \"Million\"],\n [1000, \"Thousand\"],\n [100, \"Hundred\"],\n [90, \"Ninety\"],\n [80, \"Eighty\"],\n [70, \"Seventy\"],\n [60, \"Sixty\"],\n [50, \"Fifty\"],\n [40, \"Forty\"],\n [30, \"Thirty\"],\n [20, \"Twenty\"],\n [19, \"Nineteen\"],\n [18, \"Eighteen\"],\n [17, \"Seventeen\"],\n [16, \"Sixteen\"],\n [15, \"Fifteen\"],\n [14, \"Fourteen\"],\n [13, \"Thirteen\"],\n [12, \"Twelve\"],\n [11, \"Eleven\"],\n [10, \"Ten\"],\n [9, \"Nine\"],\n [8, \"Eight\"],\n [7, \"Seven\"],\n [6, \"Six\"],\n [5, \"Five\"],\n [4, \"Four\"],\n [3, \"Three\"],\n [2, \"Two\"],\n [1, \"One\"]\n]);" ]
274
h-index
[ "An easy approach is to sort the array first.", "What are the possible values of h-index?", "A faster approach is to use extra space." ]
/** * @param {number[]} citations * @return {number} */ var hIndex = function(citations) { };
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher's h-index. According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times.   Example 1: Input: citations = [3,0,6,1,5] Output: 3 Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. Example 2: Input: citations = [1,3,1] Output: 1   Constraints: n == citations.length 1 <= n <= 5000 0 <= citations[i] <= 1000
Medium
[ "array", "sorting", "counting-sort" ]
[ "const hIndex = function(citations) {\n const n = citations.length\n const arr = Array(n + 1).fill(0)\n for(let e of citations) {\n if(e >= n) arr[n]++\n else arr[e]++\n }\n for(let i = n, sum = 0; i >= 0; i--) {\n sum += arr[i]\n if(sum >= i) return i\n }\n return 0\n};", "const hIndex = function(citations) {\n citations = citations.sort((a, b) => b - a)\n\n for (let i = 0, len = citations.length; i < len; i++) {\n if (i >= citations[i]) return i\n }\n\n return citations.length\n}", "const hIndex = function(citations) {\n const buckets = Array(citations.length + 1).fill(0)\n citations.forEach(citation => {\n buckets[citation >= citations.length ? citations.length : citation]++\n })\n for (let i = citations.length, count = 0; i >= 0; i--) {\n count += buckets[i]\n if (count >= i) return i\n }\n return 0\n}" ]
275
h-index-ii
[ "Expected runtime complexity is in <i>O</i>(log <i>n</i>) and the input is sorted." ]
/** * @param {number[]} citations * @return {number} */ var hIndex = function(citations) { };
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in ascending order, return the researcher's h-index. According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. You must write an algorithm that runs in logarithmic time.   Example 1: Input: citations = [0,1,3,5,6] Output: 3 Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. Example 2: Input: citations = [1,2,100] Output: 2   Constraints: n == citations.length 1 <= n <= 105 0 <= citations[i] <= 1000 citations is sorted in ascending order.
Medium
[ "array", "binary-search" ]
[ "const hIndex = function(citations) {\n let left = 0,\n len = citations.length,\n right = len - 1,\n mid\n while (left <= right) {\n mid = left + ((right - left) >> 1)\n if (citations[mid] >= len - mid) right = mid - 1\n else left = mid + 1\n }\n return len - left\n}", "const hIndex = function(citations) {\n const len = citations.length\n let lo = 0,\n hi = len - 1\n while (lo <= hi) {\n let med = lo + ((hi - lo) >> 1)\n if (citations[med] === len - med) {\n return len - med\n } else if (citations[med] < len - med) {\n lo = med + 1\n } else {\n hi = med - 1\n }\n }\n return len - lo\n}" ]
278
first-bad-version
[]
/** * Definition for isBadVersion() * * @param {integer} version number * @return {boolean} whether the version is bad * isBadVersion = function(version) { * ... * }; */ /** * @param {function} isBadVersion() * @return {function} */ var solution = function(isBadVersion) { /** * @param {integer} n Total versions * @return {integer} The first bad version */ return function(n) { }; };
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.   Example 1: Input: n = 5, bad = 4 Output: 4 Explanation: call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version. Example 2: Input: n = 1, bad = 1 Output: 1   Constraints: 1 <= bad <= n <= 231 - 1
Easy
[ "binary-search", "interactive" ]
/** * Definition for isBadVersion() * * @param {integer} version number * @return {boolean} whether the version is bad * isBadVersion = function(version) { * ... * }; */
[ "const solution = function(isBadVersion) {\n \n return function(n) {\n let left = 1;\n let right = n;\n while (left < right) {\n let mid = left + Math.floor( (right - left) / 2 );\n if (isBadVersion(mid)) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n return left;\n };\n};" ]
279
perfect-squares
[]
/** * @param {number} n * @return {number} */ var numSquares = function(n) { };
Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.   Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9.   Constraints: 1 <= n <= 104
Medium
[ "math", "dynamic-programming", "breadth-first-search" ]
[ "const numSquares = function(n) {\n const dp = new Array(n+1).fill(Number.MAX_VALUE)\n dp[0] = 0\n for(let i = 1; i <= n; i++) {\n let min = Number.MAX_VALUE\n let j = 1\n while(i - j*j >= 0) {\n min = Math.min(min, dp[i-j*j] + 1)\n ++j\n }\n dp[i] = min\n }\n return dp[n]\n};", "const numSquares = function (n) {\n if (n <= 0) return 0\n // cntPerfectSquares[i] = the least number of perfect square numbers\n const cntPerfectSquares = [0]\n // While cntPerfectSquares.length <= n, we need to incrementally\n // calculate the next result until we get the result for n.\n while (cntPerfectSquares.length <= n) {\n const m = cntPerfectSquares.length\n let cntSquares = Number.MAX_VALUE\n for (let i = 1; i * i <= m; i++) {\n cntSquares = Math.min(cntSquares, cntPerfectSquares[m - i * i] + 1)\n }\n cntPerfectSquares.push(cntSquares)\n }\n return cntPerfectSquares[n]\n}", "const numSquares = function (n) {\n // Based on Lagrange's Four Square theorem, there\n // are only 4 possible results: 1, 2, 3, 4.\n // If n is a perfect square, return 1.\n if (is_square(n)) {\n return 1\n }\n // The result is 4 if and only if n can be written in the\n // form of 4^k*(8*m + 7). Please refer to\n // Legendre's three-square theorem.\n while ((n & 3) === 0) {\n // n%4 == 0\n n >>= 2\n }\n if ((n & 7) === 7) {\n // n%8 == 7\n return 4\n }\n // Check whether 2 is the result.\n let sqrt_n = Math.sqrt(n) >> 0\n for (let i = 1; i <= sqrt_n; i++) {\n if (is_square(n - i * i)) {\n return 2\n }\n }\n return 3\n function is_square(n) {\n const sqrt_n = Math.sqrt(n) >> 0\n return sqrt_n * sqrt_n == n\n }\n}" ]
282
expression-add-operators
[ "Note that a number can contain multiple digits.", "Since the question asks us to find <b>all</b> of the valid expressions, we need a way to iterate over all of them. (<b>Hint:</b> Recursion!)", "We can keep track of the expression string and evaluate it at the very end. But that would take a lot of time. Can we keep track of the expression's value as well so as to avoid the evaluation at the very end of recursion?", "Think carefully about the multiply operator. It has a higher precedence than the addition and subtraction operators. \r\n\r\n<br> 1 + 2 = 3 <br>\r\n1 + 2 - 4 --> 3 - 4 --> -1 <br>\r\n1 + 2 - 4 * 12 --> -1 * 12 --> -12 (WRONG!) <br>\r\n1 + 2 - 4 * 12 --> -1 - (-4) + (-4 * 12) --> 3 + (-48) --> -45 (CORRECT!)", "We simply need to keep track of the last operand in our expression and reverse it's effect on the expression's value while considering the multiply operator." ]
/** * @param {string} num * @param {number} target * @return {string[]} */ var addOperators = function(num, target) { };
Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value. Note that operands in the returned expressions should not contain leading zeros.   Example 1: Input: num = "123", target = 6 Output: ["1*2*3","1+2+3"] Explanation: Both "1*2*3" and "1+2+3" evaluate to 6. Example 2: Input: num = "232", target = 8 Output: ["2*3+2","2+3*2"] Explanation: Both "2*3+2" and "2+3*2" evaluate to 8. Example 3: Input: num = "3456237490", target = 9191 Output: [] Explanation: There are no expressions that can be created from "3456237490" to evaluate to 9191.   Constraints: 1 <= num.length <= 10 num consists of only digits. -231 <= target <= 231 - 1
Hard
[ "math", "string", "backtracking" ]
[ "const addOperators = function(num, target) {\n let res = [];\n let n = num.length;\n function recursive(k, str, add, mul, last) {\n let sum = add + mul * last;\n if (k === n) {\n if (sum === target) {\n res.push(str);\n }\n return;\n }\n let x = num[k] - \"0\";\n if (last !== 0) {\n recursive(k + 1, str + num[k], add, mul, last * 10 + x);\n }\n recursive(k + 1, str + \"*\" + num[k], add, mul * last, x);\n recursive(k + 1, str + \"+\" + num[k], sum, 1, x);\n recursive(k + 1, str + \"-\" + num[k], sum, -1, x);\n }\n if (n) recursive(1, num[0], 0, 1, num[0] - \"0\");\n return res;\n};" ]
283
move-zeroes
[ "<b>In-place</b> means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually.", "A <b>two-pointer</b> approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array." ]
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var moveZeroes = function(nums) { };
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array.   Example 1: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] Example 2: Input: nums = [0] Output: [0]   Constraints: 1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1   Follow up: Could you minimize the total number of operations done?
Easy
[ "array", "two-pointers" ]
[ "const moveZeroes = function(nums) {\n const len = nums.length;\n let l = len;\n for (let i = 0; i < l; ) {\n if (nums[i] === 0) {\n nums.splice(i, 1);\n nums.push(0);\n l -= 1;\n } else {\n i += 1;\n }\n }\n};" ]
284
peeking-iterator
[ "Think of \"looking ahead\". You want to cache the next element.", "Is one variable sufficient? Why or why not?", "Test your design with call order of <code>peek()</code> before <code>next()</code> vs <code>next()</code> before <code>peek()</code>.", "For a clean implementation, check out <a href=\"https://github.com/google/guava/blob/703ef758b8621cfbab16814f01ddcc5324bdea33/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Iterators.java#L1125\" target=\"_blank\">Google's guava library source code</a>." ]
/** * // This is the Iterator's API interface. * // You should not implement it, or speculate about its implementation. * function Iterator() { * @ return {number} * this.next = function() { // return the next number of the iterator * ... * }; * * @return {boolean} * this.hasNext = function() { // return true if it still has numbers * ... * }; * }; */ /** * @param {Iterator} iterator */ var PeekingIterator = function(iterator) { }; /** * @return {number} */ PeekingIterator.prototype.peek = function() { }; /** * @return {number} */ PeekingIterator.prototype.next = function() { }; /** * @return {boolean} */ PeekingIterator.prototype.hasNext = function() { }; /** * Your PeekingIterator object will be instantiated and called as such: * var obj = new PeekingIterator(arr) * var param_1 = obj.peek() * var param_2 = obj.next() * var param_3 = obj.hasNext() */
Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations. Implement the PeekingIterator class: PeekingIterator(Iterator<int> nums) Initializes the object with the given integer iterator iterator. int next() Returns the next element in the array and moves the pointer to the next element. boolean hasNext() Returns true if there are still elements in the array. int peek() Returns the next element in the array without moving the pointer. Note: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions.   Example 1: Input ["PeekingIterator", "next", "peek", "next", "next", "hasNext"] [[[1, 2, 3]], [], [], [], [], []] Output [null, 1, 2, 2, 3, false] Explanation PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3] peekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3]. peekingIterator.peek(); // return 2, the pointer does not move [1,2,3]. peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3] peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3] peekingIterator.hasNext(); // return False   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 1000 All the calls to next and peek are valid. At most 1000 calls will be made to next, hasNext, and peek.   Follow up: How would you extend your design to be generic and work with all types, not just integer?
Medium
[ "array", "design", "iterator" ]
null
[]
287
find-the-duplicate-number
[]
/** * @param {number[]} nums * @return {number} */ var findDuplicate = function(nums) { };
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and uses only constant extra space.   Example 1: Input: nums = [1,3,4,2,2] Output: 2 Example 2: Input: nums = [3,1,3,4,2] Output: 3   Constraints: 1 <= n <= 105 nums.length == n + 1 1 <= nums[i] <= n All the integers in nums appear only once except for precisely one integer which appears two or more times.   Follow up: How can we prove that at least one duplicate number must exist in nums? Can you solve the problem in linear runtime complexity?
Medium
[ "array", "two-pointers", "binary-search", "bit-manipulation" ]
[ "const findDuplicate = function(nums) {\n const n = nums.length;\n let ans = 0;\n let bit_max = 31;\n while (((n - 1) >> bit_max) == 0) {\n bit_max -= 1;\n }\n for (let bit = 0; bit <= bit_max; ++bit) {\n let x = 0, y = 0;\n for (let i = 0; i < n; ++i) {\n if ((nums[i] & (1 << bit)) != 0) {\n x += 1;\n }\n if (i >= 1 && ((i & (1 << bit)) != 0)) {\n y += 1;\n }\n }\n if (x > y) {\n ans |= 1 << bit;\n }\n }\n return ans;\n};", "const findDuplicate = function(nums) {\n const len = nums.length\n if(len > 0) {\n let slow = nums[0]\n let fast = nums[nums[0]]\n while(slow !== fast) {\n slow = nums[slow]\n fast = nums[nums[fast]]\n }\n slow = 0\n while(slow !== fast) {\n slow = nums[slow]\n fast = nums[fast]\n }\n return slow\n }\n return -1;\n};", "const findDuplicate = function(nums) {\n let n = nums.length - 1,\n res = 0\n for (let p = 0; p < 32; ++p) {\n let bit = 1 << p,\n a = 0,\n b = 0\n for (let i = 0; i <= n; ++i) {\n if (i > 0 && (i & bit) > 0) ++a\n if ((nums[i] & bit) > 0) ++b\n }\n if (b > a) res += bit\n }\n return res\n}", "const findDuplicate = function(nums) {\n const hash = {};\n for (let i = 0; i < nums.length; i++) {\n if (hash.hasOwnProperty(nums[i])) {\n return nums[i];\n } else {\n hash[nums[i]] = 1;\n }\n }\n};" ]
289
game-of-life
[]
/** * @param {number[][]} board * @return {void} Do not return anything, modify board in-place instead. */ var gameOfLife = function(board) { };
According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by over-population. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.   Example 1: Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] Example 2: Input: board = [[1,1],[1,0]] Output: [[1,1],[1,1]]   Constraints: m == board.length n == board[i].length 1 <= m, n <= 25 board[i][j] is 0 or 1.   Follow up: Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
Medium
[ "array", "matrix", "simulation" ]
[ "const gameOfLife = function(board) {\n const DIRECTIONS = [\n [1, 0],\n [1, 1],\n [0, 1],\n [-1, 1],\n [-1, 0],\n [-1, -1],\n [0, -1],\n [1, -1]\n ];\n\n const isValid = function(x, y) {\n if (x >= 0 && y >= 0 && x < board.length && y < board[0].length)\n return true;\n else return false;\n };\n\n const getAliveNeighbors = function(x, y) {\n let aliveNeighs = 0;\n for (let dir of DIRECTIONS) {\n let newX = x + dir[0];\n let newY = y + dir[1];\n if (!isValid(newX, newY)) continue;\n if (board[newX][newY] === 1 || board[newX][newY] === -1) {\n aliveNeighs++;\n }\n }\n\n return aliveNeighs;\n };\n\n for (let row = 0; row < board.length; row++) {\n for (let col = 0; col < board[0].length; col++) {\n let aliveNeighbors = getAliveNeighbors(row, col);\n if (board[row][col] === 0) {\n if (aliveNeighbors === 3) board[row][col] = 2;\n else board[row][col] = 0;\n } else {\n if (aliveNeighbors === 2 || aliveNeighbors === 3) board[row][col] = 1;\n else board[row][col] = -1;\n }\n }\n }\n\n for (let row = 0; row < board.length; row++) {\n for (let col = 0; col < board[0].length; col++) {\n if (board[row][col] > 0) board[row][col] = 1;\n else board[row][col] = 0;\n }\n }\n};" ]
290
word-pattern
[]
/** * @param {string} pattern * @param {string} s * @return {boolean} */ var wordPattern = function(pattern, s) { };
Given a pattern and a string s, find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.   Example 1: Input: pattern = "abba", s = "dog cat cat dog" Output: true Example 2: Input: pattern = "abba", s = "dog cat cat fish" Output: false Example 3: Input: pattern = "aaaa", s = "dog cat cat dog" Output: false   Constraints: 1 <= pattern.length <= 300 pattern contains only lower-case English letters. 1 <= s.length <= 3000 s contains only lowercase English letters and spaces ' '. s does not contain any leading or trailing spaces. All the words in s are separated by a single space.
Easy
[ "hash-table", "string" ]
[ "const wordPattern = function(pattern, str) {\n const pm = {}\n const sm = {}\n const sa = str.trim().split(' ')\n if(pattern.length !== sa.length) return false\n for(let i = 0; i< pattern.length; i++) {\n if(!pm.hasOwnProperty(pattern[i])) {\n pm[pattern[i]] = sa[i]\n }\n if(!sm.hasOwnProperty(sa[i])) {\n sm[sa[i]] = pattern[i]\n }\n\n if( !(pm[pattern[i]] === sa[i] && sm[sa[i]] === pattern[i] ) ) {\n return false \n }\n \n }\n return true\n};" ]
292
nim-game
[ "If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?" ]
/** * @param {number} n * @return {boolean} */ var canWinNim = function(n) { };
You are playing the following Nim Game with your friend: Initially, there is a heap of stones on the table. You and your friend will alternate taking turns, and you go first. On each turn, the person whose turn it is will remove 1 to 3 stones from the heap. The one who removes the last stone is the winner. Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.   Example 1: Input: n = 4 Output: false Explanation: These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. Example 2: Input: n = 1 Output: true Example 3: Input: n = 2 Output: true   Constraints: 1 <= n <= 231 - 1
Easy
[ "math", "brainteaser", "game-theory" ]
[ "const canWinNim = function(n) {\n return n % 4 !== 0 ; \n};" ]
295
find-median-from-data-stream
[]
var MedianFinder = function() { }; /** * @param {number} num * @return {void} */ MedianFinder.prototype.addNum = function(num) { }; /** * @return {number} */ MedianFinder.prototype.findMedian = function() { }; /** * Your MedianFinder object will be instantiated and called as such: * var obj = new MedianFinder() * obj.addNum(num) * var param_2 = obj.findMedian() */
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. For example, for arr = [2,3,4], the median is 3. For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5. Implement the MedianFinder class: MedianFinder() initializes the MedianFinder object. void addNum(int num) adds the integer num from the data stream to the data structure. double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"] [[], [1], [2], [], [3], []] Output [null, null, null, 1.5, null, 2.0] Explanation MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0   Constraints: -105 <= num <= 105 There will be at least one element in the data structure before calling findMedian. At most 5 * 104 calls will be made to addNum and findMedian.   Follow up: If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution? If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
Hard
[ "two-pointers", "design", "sorting", "heap-priority-queue", "data-stream" ]
[ "const MedianFinder = function() {\n this.arr = [];\n};\n\nMedianFinder.prototype.addNum = function(num) {\n const bs = n => {\n let start = 0;\n let end = this.arr.length;\n while (start < end) {\n let mid = ~~((start + end) / 2);\n if (n > this.arr[mid]) start = mid + 1;\n else end = mid;\n }\n this.arr.splice(start, 0, n);\n };\n if (this.arr.length === 0) this.arr.push(num);\n else bs(num);\n};\n\n\nMedianFinder.prototype.findMedian = function() {\n const mid = ~~(this.arr.length / 2);\n return this.arr.length % 2 === 0\n ? (this.arr[mid - 1] + this.arr[mid]) / 2\n : this.arr[mid];\n};", "const MedianFinder = function() {\n this.minPQ = new PriorityQueue()\n this.maxPQ = new PriorityQueue((a, b) => a < b)\n};\n\n\nMedianFinder.prototype.addNum = function(num) {\n this.minPQ.push(num)\n this.maxPQ.push(this.minPQ.pop())\n if(this.minPQ.size() < this.maxPQ.size()) {\n this.minPQ.push(this.maxPQ.pop())\n }\n};\n\n\nMedianFinder.prototype.findMedian = function() {\n if(this.minPQ.size() > this.maxPQ.size()) return this.minPQ.peek()\n else return (this.minPQ.peek() + this.maxPQ.peek()) / 2\n};\n\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}" ]
297
serialize-and-deserialize-binary-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * Encodes a tree to a single string. * * @param {TreeNode} root * @return {string} */ var serialize = function(root) { }; /** * Decodes your encoded data to tree. * * @param {string} data * @return {TreeNode} */ var deserialize = function(data) { }; /** * Your functions will be called as such: * deserialize(serialize(root)); */
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.   Example 1: Input: root = [1,2,3,null,null,4,5] Output: [1,2,3,null,null,4,5] Example 2: Input: root = [] Output: []   Constraints: The number of nodes in the tree is in the range [0, 104]. -1000 <= Node.val <= 1000
Hard
[ "string", "tree", "depth-first-search", "breadth-first-search", "design", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */
[ "const serialize = function(root) {\n return rserialize(root, \"\");\n};\n\nfunction rserialize(root, str) {\n if (root === null) {\n str += \"null,\";\n } else {\n str += root.val + \",\";\n str = rserialize(root.left, str);\n str = rserialize(root.right, str);\n }\n\n return str;\n}\n\nconst deserialize = function(data) {\n let data_array = data.split(\",\").filter(el => el !== \"\");\n return rdeserialize(data_array);\n};\n\nfunction rdeserialize(l) {\n if (l[0] === \"null\") {\n l.shift();\n return null;\n }\n const root = new TreeNode(+l[0]);\n l.shift();\n root.left = rdeserialize(l);\n root.right = rdeserialize(l);\n return root;\n}" ]
299
bulls-and-cows
[]
/** * @param {string} secret * @param {string} guess * @return {string} */ var getHint = function(secret, guess) { };
You are playing the Bulls and Cows game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: The number of "bulls", which are digits in the guess that are in the correct position. The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls. Given the secret number secret and your friend's guess guess, return the hint for your friend's guess. The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.   Example 1: Input: secret = "1807", guess = "7810" Output: "1A3B" Explanation: Bulls are connected with a '|' and cows are underlined: "1807" | "7810" Example 2: Input: secret = "1123", guess = "0111" Output: "1A1B" Explanation: Bulls are connected with a '|' and cows are underlined: "1123" "1123" | or | "0111" "0111" Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.   Constraints: 1 <= secret.length, guess.length <= 1000 secret.length == guess.length secret and guess consist of digits only.
Medium
[ "hash-table", "string", "counting" ]
[ "const getHint = function(secret, guess) {\n let x = 0, y = 0\n const arr = Array(10).fill(0)\n for(let i = 0; i < guess.length; i++) {\n const ch = guess[i], e = secret[i]\n if(secret[i] === ch) {\n x++\n } else {\n if(arr[+ch] < 0) y++\n if(arr[+e] > 0) y++\n arr[+ch]++\n arr[+e]-- \n }\n }\n\n return `${x}A${y}B`\n};", "const getHint = function(secret, guess) {\n let bulls = 0\n let cows = 0\n const h = {}\n for(let i = 0, len = secret.length; i < len; i++) {\n if(secret[i] === guess[i]) {\n bulls++\n } else {\n if(!h.hasOwnProperty(secret[i])) h[secret[i]] = 0\n h[secret[i]]++\n }\n }\n \n for(let i = 0, len = secret.length; i < len; i++) {\n if(secret[i] !== guess[i]) {\n if(h.hasOwnProperty(guess[i]) && h[guess[i]] > 0) {\n cows++\n h[guess[i]]--\n }\n }\n }\n\n return `${bulls}A${cows}B`\n};" ]
300
longest-increasing-subsequence
[]
/** * @param {number[]} nums * @return {number} */ var lengthOfLIS = function(nums) { };
Given an integer array nums, return the length of the longest strictly increasing subsequence.   Example 1: Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Example 2: Input: nums = [0,1,0,3,2,3] Output: 4 Example 3: Input: nums = [7,7,7,7,7,7,7] Output: 1   Constraints: 1 <= nums.length <= 2500 -104 <= nums[i] <= 104   Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?
Medium
[ "array", "binary-search", "dynamic-programming" ]
[ "const lengthOfLIS = function(nums) {\n const stack = []\n for(let e of nums) {\n if(stack.length === 0 || e > stack[stack.length - 1]) {\n stack.push(e)\n continue\n }\n let l = 0, r = stack.length - 1, mid\n while(l < r) {\n const mid = l + ((r - l) >> 1)\n if(e > stack[mid]) l = mid + 1\n else r = mid\n }\n stack[l] = e\n }\n return stack.length\n};", "const lengthOfLIS = function(nums) {\n if (nums.length === 0) {\n return 0\n }\n const dp = new Array(nums.length).fill(0)\n dp[0] = 1\n let maxans = 1\n for(let i = 1; i < dp.length; i++) {\n let maxval = 0\n for(let j = 0; j < i; j++) {\n if(nums[i] > nums[j]) {\n maxval = Math.max(maxval, dp[j])\n }\n }\n dp[i] = maxval + 1\n maxans = Math.max(maxans, dp[i])\n }\n return maxans\n};", "const lengthOfLIS = function(nums) {\n const n = nums.length\n const tails = []\n let res = 0\n for(let e of nums) {\n let i = 0, j = res\n while(i !== j) {\n const mid = i + ((j - i) >> 1)\n if(tails[mid] < e) i = mid + 1\n else j = mid\n }\n tails[i] = e\n if(i === res) res++\n }\n return res\n};", "const lengthOfLIS = function(nums) {\n const n = nums.length, stack = []\n let res = 0\n stack.push(nums[0])\n for(let i = 1; i < n; i++) {\n const cur = nums[i]\n if(cur > stack[stack.length - 1]) {\n stack.push(cur)\n } else {\n let l = 0, r = stack.length - 1\n while(l < r) {\n let mid = ~~((l + r) / 2)\n if(stack[mid] < cur) {\n l = mid + 1\n } else {\n r = mid\n }\n }\n stack[l] = cur\n }\n }\n \n return stack.length\n};" ]
301
remove-invalid-parentheses
[ "Since we do not know which brackets can be removed, we try all the options! We can use recursion.", "In the recursion, for each bracket, we can either use it or remove it.", "Recursion will generate all the valid parentheses strings but we want the ones with the least number of parentheses deleted.", "We can count the number of invalid brackets to be deleted and only generate the valid strings in the recusrion." ]
/** * @param {string} s * @return {string[]} */ var removeInvalidParentheses = function(s) { };
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return a list of unique strings that are valid with the minimum number of removals. You may return the answer in any order.   Example 1: Input: s = "()())()" Output: ["(())()","()()()"] Example 2: Input: s = "(a)())()" Output: ["(a())()","(a)()()"] Example 3: Input: s = ")(" Output: [""]   Constraints: 1 <= s.length <= 25 s consists of lowercase English letters and parentheses '(' and ')'. There will be at most 20 parentheses in s.
Hard
[ "string", "backtracking", "breadth-first-search" ]
[ "const removeInvalidParentheses = function(s) {\n const res = []\n helper(s, 0, 0, ['(', ')'])\n return res\n\n function helper(str, lastI, lastJ, pair) {\n let openNum = 0, closeNum = 0\n for(let i = lastI; i < str.length; i++) {\n if(str[i] === pair[0]) openNum++\n if(str[i] === pair[1]) closeNum++\n if(closeNum > openNum) {\n for(let j = lastJ; j <= i; j++) {\n if(str[j] === pair[1] && (j === lastJ || str[j - 1] !== pair[1])) {\n helper(str.slice(0, j) + str.slice(j + 1), i, j, pair)\n }\n }\n return\n }\n }\n let rev = str.split('').reverse().join('')\n if(pair[0] === '(') {\n helper(rev, 0, 0, [')', '('])\n } else {\n res.push(rev)\n }\n }\n};", "const removeInvalidParentheses = function(s) {\n const ans = [];\n remove(s, ans, 0, 0, [\"(\", \")\"]);\n return ans;\n};\n\nfunction remove(s, ans, last_i, last_j, par) {\n for (let stack = 0, i = last_i; i < s.length; i++) {\n if (s.charAt(i) === par[0]) stack++;\n if (s.charAt(i) === par[1]) stack--;\n if (stack >= 0) continue;\n for (let j = last_j; j <= i; j++) {\n if (\n s.charAt(j) === par[1] &&\n (j === last_j || s.charAt(j - 1) != par[1])\n ) {\n remove(s.slice(0, j) + s.slice(j + 1), ans, i, j, par);\n }\n }\n return;\n }\n const reversed = s\n .split(\"\")\n .reverse()\n .join(\"\");\n if (par[0] === \"(\") {\n remove(reversed, ans, 0, 0, [\")\", \"(\"]);\n } else {\n ans.push(reversed);\n }\n}" ]
303
range-sum-query-immutable
[]
/** * @param {number[]} nums */ var NumArray = function(nums) { }; /** * @param {number} left * @param {number} right * @return {number} */ NumArray.prototype.sumRange = function(left, right) { }; /** * Your NumArray object will be instantiated and called as such: * var obj = new NumArray(nums) * var param_1 = obj.sumRange(left,right) */
Given an integer array nums, handle multiple queries of the following type: Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. Implement the NumArray class: NumArray(int[] nums) Initializes the object with the integer array nums. int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).   Example 1: Input ["NumArray", "sumRange", "sumRange", "sumRange"] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] Output [null, 1, -1, -3] Explanation NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3   Constraints: 1 <= nums.length <= 104 -105 <= nums[i] <= 105 0 <= left <= right < nums.length At most 104 calls will be made to sumRange.
Easy
[ "array", "design", "prefix-sum" ]
null
[]
304
range-sum-query-2d-immutable
[]
/** * @param {number[][]} matrix */ var NumMatrix = function(matrix) { }; /** * @param {number} row1 * @param {number} col1 * @param {number} row2 * @param {number} col2 * @return {number} */ NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) { }; /** * Your NumMatrix object will be instantiated and called as such: * var obj = new NumMatrix(matrix) * var param_1 = obj.sumRegion(row1,col1,row2,col2) */
Given a 2D matrix matrix, handle multiple queries of the following type: Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). Implement the NumMatrix class: NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix. int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). You must design an algorithm where sumRegion works on O(1) time complexity.   Example 1: Input ["NumMatrix", "sumRegion", "sumRegion", "sumRegion"] [[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]] Output [null, 8, 11, 12] Explanation NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)   Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 200 -104 <= matrix[i][j] <= 104 0 <= row1 <= row2 < m 0 <= col1 <= col2 < n At most 104 calls will be made to sumRegion.
Medium
[ "array", "design", "matrix", "prefix-sum" ]
[ "const NumMatrix = function(matrix) {\n const dp = [];\n if (matrix.length == 0 || matrix[0].length == 0) return;\n for (let i = 0; i <= matrix.length; i++) {\n let t = new Array(matrix[0].length + 1).fill(0);\n dp.push(t);\n }\n\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix[0].length; j++) {\n dp[i + 1][j + 1] = dp[i][j + 1] + dp[i + 1][j] + matrix[i][j] - dp[i][j];\n }\n }\n\n this.cache = dp;\n};\n\n\nNumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {\n const dp = this.cache;\n return (\n dp[row2 + 1][col2 + 1] -\n dp[row1][col2 + 1] -\n dp[row2 + 1][col1] +\n dp[row1][col1]\n );\n};", "const NumMatrix = function(matrix) {\n const m = matrix.length, n = matrix[0].length\n const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n for(let i = 1; i <= m; i++) {\n for(let j = 1; j <= n; j++) {\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + matrix[i - 1][j - 1]\n }\n }\n this.dp = dp\n};\n\n\nNumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {\n const dp = this.dp\n return dp[row2 + 1][col2 + 1] - dp[row2 + 1][col1] - dp[row1][col2 + 1] + dp[row1][col1]\n};" ]
306
additive-number
[]
/** * @param {string} num * @return {boolean} */ var isAdditiveNumber = function(num) { };
An additive number is a string whose digits can form an additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return true if it is an additive number or false otherwise. Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.   Example 1: Input: "112358" Output: true Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 Example 2: Input: "199100199" Output: true Explanation: The additive sequence is: 1, 99, 100, 199.  1 + 99 = 100, 99 + 100 = 199   Constraints: 1 <= num.length <= 35 num consists only of digits.   Follow up: How would you handle overflow for very large input integers?
Medium
[ "string", "backtracking" ]
[ "const isAdditiveNumber = function(num) {\n const n = num.length\n for (let i = 1; i <= (n / 2) >> 0; ++i) {\n if (num.charAt(0) === '0' && i > 1) return false\n const x1 = +num.slice(0, i)\n for (let j = 1; Math.max(j, i) <= n - i - j; ++j) {\n if (num.charAt(i) == '0' && j > 1) break\n const x2 = +num.slice(i, i + j)\n if (isValid(x1, x2, j + i, num)) return true\n }\n }\n return false\n}\n\nfunction isValid(x1, x2, start, num) {\n if (start === num.length) return true\n x2 = x2 + x1\n x1 = x2 - x1\n const sum = x2 + ''\n return num.startsWith(sum, start) && isValid(x1, x2, start + sum.length, num)\n}" ]
307
range-sum-query-mutable
[]
/** * @param {number[]} nums */ var NumArray = function(nums) { }; /** * @param {number} index * @param {number} val * @return {void} */ NumArray.prototype.update = function(index, val) { }; /** * @param {number} left * @param {number} right * @return {number} */ NumArray.prototype.sumRange = function(left, right) { }; /** * Your NumArray object will be instantiated and called as such: * var obj = new NumArray(nums) * obj.update(index,val) * var param_2 = obj.sumRange(left,right) */
Given an integer array nums, handle multiple queries of the following types: Update the value of an element in nums. Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. Implement the NumArray class: NumArray(int[] nums) Initializes the object with the integer array nums. void update(int index, int val) Updates the value of nums[index] to be val. int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).   Example 1: Input ["NumArray", "sumRange", "update", "sumRange"] [[[1, 3, 5]], [0, 2], [1, 2], [0, 2]] Output [null, 9, null, 8] Explanation NumArray numArray = new NumArray([1, 3, 5]); numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9 numArray.update(1, 2); // nums = [1, 2, 5] numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8   Constraints: 1 <= nums.length <= 3 * 104 -100 <= nums[i] <= 100 0 <= index < nums.length -100 <= val <= 100 0 <= left <= right < nums.length At most 3 * 104 calls will be made to update and sumRange.
Medium
[ "array", "design", "binary-indexed-tree", "segment-tree" ]
[ "const lowBit = (x) => x & -x\nclass FenwickTree {\n constructor(n) {\n if (n < 1) return\n this.sum = Array(n + 1).fill(0)\n }\n update(i, delta) {\n if (i < 1) return\n while (i < this.sum.length) {\n this.sum[i] += delta\n i += lowBit(i)\n }\n }\n query(i) {\n if (i < 1) return 0\n let sum = 0\n while (i > 0) {\n sum += this.sum[i]\n i -= lowBit(i)\n }\n return sum\n }\n}\n\n\nvar NumArray = function(nums) {\n this.nums = nums\n const n = nums.length\n this.bit = new FenwickTree(n)\n for(let i = 1; i <= n; i++) {\n this.bit.update(i, nums[i - 1])\n }\n};\n\n\nNumArray.prototype.update = function(index, val) {\n const delta = val - this.nums[index]\n this.nums[index] = val\n this.bit.update(index + 1, delta)\n};\n\n\nNumArray.prototype.sumRange = function(left, right) {\n return this.bit.query(right + 1) - this.bit.query(left)\n};", "const NumArray = function(nums) {\n this.arr = nums\n};\n\n\nNumArray.prototype.update = function(i, val) {\n this.arr[i] = val\n};\n\n\nNumArray.prototype.sumRange = function(i, j) {\n let sum = 0;\n for (let k = i; k <= j; k++) {\n sum += this.arr[k];\n }\n return sum;\n};" ]
309
best-time-to-buy-and-sell-stock-with-cooldown
[]
/** * @param {number[]} prices * @return {number} */ var maxProfit = function(prices) { };
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).   Example 1: Input: prices = [1,2,3,0,2] Output: 3 Explanation: transactions = [buy, sell, cooldown, buy, sell] Example 2: Input: prices = [1] Output: 0   Constraints: 1 <= prices.length <= 5000 0 <= prices[i] <= 1000
Medium
[ "array", "dynamic-programming" ]
[ "const maxProfit = function(prices) {\n if (prices === null || prices.length < 1) {\n return 0;\n }\n\n const length = prices.length;\n // buy[i]: max profit if the first \"i\" days end with a \"buy\" day\n const buy = Array(length + 1).fill(0); \n // buy[i]: max profit if the first \"i\" days end with a \"sell\" day\n const sell = Array(length + 1).fill(0); \n\n buy[1] = -prices[0];\n\n for (let i = 2; i <= length; i++) {\n const price = prices[i - 1];\n buy[i] = Math.max(buy[i - 1], sell[i - 2] - price);\n sell[i] = Math.max(sell[i - 1], buy[i - 1] + price);\n }\n\n // sell[length] >= buy[length]\n return sell[length];\n};" ]
310
minimum-height-trees
[ "How many MHTs can a graph have at most?" ]
/** * @param {number} n * @param {number[][]} edges * @return {number[]} */ var findMinHeightTrees = function(n, edges) { };
A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))  are called minimum height trees (MHTs). Return a list of all MHTs' root labels. You can return the answer in any order. The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.   Example 1: Input: n = 4, edges = [[1,0],[1,2],[1,3]] Output: [1] Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT. Example 2: Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]] Output: [3,4]   Constraints: 1 <= n <= 2 * 104 edges.length == n - 1 0 <= ai, bi < n ai != bi All the pairs (ai, bi) are distinct. The given input is guaranteed to be a tree and there will be no repeated edges.
Medium
[ "depth-first-search", "breadth-first-search", "graph", "topological-sort" ]
[ "const findMinHeightTrees = function (n, edges) {\n const graph = {}\n\n for(const [u, v] of edges) {\n if(graph[u] == null) graph[u] = new Set()\n if(graph[v] == null) graph[v] = new Set()\n graph[u].add(v)\n graph[v].add(u)\n }\n\n let q = []\n for(let i = 0; i < n; i++) {\n if(graph[i].size === 1) q.push(i)\n }\n\n while(n > 2) {\n const size = q.length, nxt = []\n n -= size\n for(let i = 0; i < size; i++) {\n const cur = q[i]\n for(const e of (graph[cur] || [])) {\n graph[e].delete(cur)\n if(graph[e].size === 1) nxt.push(e)\n }\n }\n\n q = nxt\n }\n\n return q\n}", " const findMinHeightTrees = function(n, edges) {\n if(n === 1) return [0]\n const res = [], graph = {}\n for(const [u, v] of edges) {\n if(graph[u] == null) graph[u] = new Set()\n if(graph[v] == null) graph[v] = new Set()\n graph[u].add(v)\n graph[v].add(u)\n }\n\n let leaves = []\n Object.keys(graph).forEach(k => {\n if(graph[k].size === 1) leaves.push(+k)\n })\n while(n > 2) {\n const newLeaves = []\n const size = leaves.length\n for (let i = 0; i < size; i++) {\n const cur = leaves.pop()\n for (const next of graph[cur]) {\n graph[next].delete(cur)\n if(graph[next].size === 1) newLeaves.push(next)\n }\n }\n n -= size\n leaves = newLeaves\n }\n \n return leaves\n};", "const findMinHeightTrees = function(n, edges) {\n if (n === 1) {\n return [0];\n }\n const adj = [];\n for (let i = 0; i < n; i++) {\n adj.push([]);\n }\n for (let edge of edges) {\n adj[edge[0]].push(edge[1]);\n adj[edge[1]].push(edge[0]);\n }\n let leaves = [];\n for (let i = 0; i < n; i++) {\n if (adj[i].length === 1) {\n leaves.push(i);\n }\n }\n\n while (n > 2) {\n n -= leaves.length;\n let newLeaves = [];\n for (let i of leaves) {\n let j = adj[i].shift();\n let idx = adj[j].indexOf(i);\n adj[j].splice(idx, 1);\n if (adj[j].length === 1) newLeaves.push(j);\n }\n leaves = newLeaves;\n }\n\n return leaves;\n};" ]
312
burst-balloons
[]
/** * @param {number[]} nums * @return {number} */ var maxCoins = function(nums) { };
You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it. Return the maximum coins you can collect by bursting the balloons wisely.   Example 1: Input: nums = [3,1,5,8] Output: 167 Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 Example 2: Input: nums = [1,5] Output: 10   Constraints: n == nums.length 1 <= n <= 300 0 <= nums[i] <= 100
Hard
[ "array", "dynamic-programming" ]
[ "function maxCoins(arr) {\n const len = arr.length\n const nums = Array(len + 2).fill(0);\n let n = 1;\n for (const x of arr) if (x > 0) nums[n++] = x;\n nums[0] = nums[n++] = 1;\n\n const dp = Array.from({ length: n }, () => Array(n).fill(0));\n for (let k = 2; k < n; k++) {\n for (let left = 0; left < n - k; left++) {\n let right = left + k;\n for (let i = left + 1; i < right; i++) {\n dp[left][right] = Math.max(\n dp[left][right],\n nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right],\n );\n }\n }\n }\n\n return dp[0][n - 1];\n}", "const maxCoins = iNums => {\n const nums = new Array(iNums.length + 2);\n let n = 1;\n for (let x of iNums) if (x > 0) nums[n++] = x;\n nums[0] = nums[n++] = 1;\n\n const memo = Array.from({ length: n }, () => new Array(n));\n return burst(memo, nums, 0, n - 1);\n};\n\nfunction burst(memo, nums, left, right) {\n if (left + 1 === right) return 0;\n if (memo[left][right] > 0) return memo[left][right];\n let ans = 0;\n for (let i = left + 1; i < right; ++i)\n ans = Math.max(\n ans,\n nums[left] * nums[i] * nums[right] +\n burst(memo, nums, left, i) +\n burst(memo, nums, i, right)\n );\n memo[left][right] = ans;\n return ans;\n}" ]
313
super-ugly-number
[]
/** * @param {number} n * @param {number[]} primes * @return {number} */ var nthSuperUglyNumber = function(n, primes) { };
A super ugly number is a positive integer whose prime factors are in the array primes. Given an integer n and an array of integers primes, return the nth super ugly number. The nth super ugly number is guaranteed to fit in a 32-bit signed integer.   Example 1: Input: n = 12, primes = [2,7,13,19] Output: 32 Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19]. Example 2: Input: n = 1, primes = [2,3,5] Output: 1 Explanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].   Constraints: 1 <= n <= 105 1 <= primes.length <= 100 2 <= primes[i] <= 1000 primes[i] is guaranteed to be a prime number. All the values of primes are unique and sorted in ascending order.
Medium
[ "array", "math", "dynamic-programming" ]
[ "const nthSuperUglyNumber = function(n, primes) {\n if (n === 1) return 1\n const indexes = new Array(primes.length).fill(0)\n const arr = [1]\n for (let i = 1; i <= n - 1; i++) {\n arr[i] = +Infinity\n for (let j = 0; j < primes.length; j++) {\n arr[i] = Math.min(arr[i], arr[indexes[j]] * primes[j])\n }\n for (let j = 0; j < primes.length; j++) {\n if (arr[i] === arr[indexes[j]] * primes[j]) {\n indexes[j]++\n }\n }\n }\n return arr[n - 1]\n}", "const nthSuperUglyNumber = function(n, primes) {\n const ugly = Array(n).fill(0)\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n \n for(let i = 0; i < primes.length; i++) pq.push([primes[i], 1, primes[i]])\n ugly[0] = 1\n for(let i = 1; i < n; i++) {\n ugly[i] = pq.peek()[0]\n while(pq.peek()[0] === ugly[i]) {\n const next = pq.pop()\n pq.push([next[2] * ugly[next[1]], next[1] + 1, next[2]])\n }\n }\n \n return ugly[n - 1]\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}" ]
315
count-of-smaller-numbers-after-self
[]
/** * @param {number[]} nums * @return {number[]} */ var countSmaller = function(nums) { };
Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].   Example 1: Input: nums = [5,2,6,1] Output: [2,1,1,0] Explanation: To the right of 5 there are 2 smaller elements (2 and 1). To the right of 2 there is only 1 smaller element (1). To the right of 6 there is 1 smaller element (1). To the right of 1 there is 0 smaller element. Example 2: Input: nums = [-1] Output: [0] Example 3: Input: nums = [-1,-1] Output: [0,0]   Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104
Hard
[ "array", "binary-search", "divide-and-conquer", "binary-indexed-tree", "segment-tree", "merge-sort", "ordered-set" ]
[ "const countSmaller = function(nums) {\n const numsAndIndexes = nums.map((x, i) => [x, i])\n const output = [...new Array(nums.length)].map(_ => 0)\n mergeSort(numsAndIndexes, output)\n return output\n}\n\nfunction mergeSort(arr, output) {\n if (arr.length <= 1) return arr\n const middle = Math.floor(arr.length / 2)\n const left = mergeSort(arr.slice(0, middle), output),\n right = mergeSort(arr.slice(middle), output)\n const sorted = []\n let i = 0,\n j = 0\n while (i < left.length || j < right.length) {\n if (i >= left.length) {\n sorted.push(right[j])\n j++\n } else if (j >= right.length) {\n sorted.push(left[i])\n i++\n } else {\n if (left[i][0] > right[j][0]) {\n sorted.push(left[i])\n output[left[i][1]] += right.length - j\n i++\n } else {\n sorted.push(right[j])\n j++\n }\n }\n }\n\n return sorted\n}", "class Node {\n constructor(v, s) {\n this.val = v\n this.sum = s\n this.left = null\n this.right = null\n this.dup = 1\n }\n}\n\nconst countSmaller = function(nums) {\n const ans = new Array(nums.length).fill(0)\n let root = null\n for (let i = nums.length - 1; i >= 0; i--) {\n root = insert(nums[i], root, ans, i, 0)\n }\n return ans\n}\n\nfunction insert(num, node, ans, i, preSum) {\n if (node == null) {\n node = new Node(num, 0)\n ans[i] = preSum\n } else if (node.val == num) {\n node.dup++\n ans[i] = preSum + node.sum\n } else if (node.val > num) {\n node.sum++\n node.left = insert(num, node.left, ans, i, preSum)\n } else {\n node.right = insert(num, node.right, ans, i, preSum + node.dup + node.sum)\n }\n return node\n}", "const countSmaller = function(nums) {\n \n const arr = []\n const n = nums.length\n for(let i = 0; i < n; i++) {\n arr.push([nums[i], i])\n }\n \n const res = Array(n).fill(0)\n cntSmaller(arr, 0, n - 1, res)\n \n return res\n \n function cntSmaller(arr, l, r, res) {\n if(l >= r) return\n \n const mid = ~~((l + r) / 2)\n cntSmaller(arr, l, mid, res)\n cntSmaller(arr, mid + 1, r, res)\n let leftPos = l, rightPos = mid + 1, cnt = 0\n const merged = []\n while(leftPos < mid + 1 && rightPos <= r) {\n if(arr[leftPos][0] > arr[rightPos][0]) {\n cnt++\n merged.push(arr[rightPos])\n rightPos++\n } else {\n res[arr[leftPos][1]] += cnt\n merged.push(arr[leftPos])\n leftPos++\n }\n }\n \n while(leftPos < mid + 1) {\n res[arr[leftPos][1]] += cnt\n merged.push(arr[leftPos])\n leftPos++\n }\n \n while(rightPos <= r) {\n merged.push(arr[rightPos])\n rightPos++\n }\n \n for(let i = l; i <= r; i++) {\n arr[i] = merged[i - l]\n }\n \n }\n};" ]
316
remove-duplicate-letters
[ "Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i." ]
/** * @param {string} s * @return {string} */ var removeDuplicateLetters = function(s) { };
Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.   Example 1: Input: s = "bcabc" Output: "abc" Example 2: Input: s = "cbacdcbc" Output: "acdb"   Constraints: 1 <= s.length <= 104 s consists of lowercase English letters.   Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
Medium
[ "string", "stack", "greedy", "monotonic-stack" ]
[ "const removeDuplicateLetters = function(s) {\n const last = {}\n for (let i = 0; i < s.length; i++) last[s.charAt(i)] = i\n const added = {}\n const stack = []\n for (let i = 0; i < s.length; i++) {\n const char = s.charAt(i)\n if (added[char]) continue\n while (stack.length && char < stack[0] && last[stack[0]] > i) {\n added[stack[0]] = false\n stack.shift()\n }\n stack.unshift(char)\n added[char] = true\n }\n return stack.reverse().join('')\n}", "const removeDuplicateLetters = function(s) {\n const m = new Array(26)\n const a = 'a'.charCodeAt(0)\n for (let i = 0; i < s.length; i++) {\n const k = s.charCodeAt(i) - a\n m[k] = m[k] ? m[k] + 1 : 1\n }\n const aChNo = []\n const visited = {}\n for (let i = 0; i < s.length; i++) {\n const k = s.charCodeAt(i) - a\n m[k]--\n if (visited[k]) continue\n while (aChNo.length > 0) {\n const last = aChNo[aChNo.length - 1] - a\n if (last > k && m[last] > 0) {\n visited[last] = 0\n aChNo.pop()\n } else break\n }\n visited[k] = 1\n aChNo.push(k + a)\n }\n return String.fromCharCode(...aChNo)\n}", "const removeDuplicateLetters = function(s) {\n const last = {}\n for (let i = 0; i < s.length; i++) last[s.charAt(i)] = i\n const added = {}\n const stack = []\n for (let i = 0; i < s.length; i++) {\n const char = s.charAt(i)\n if (added[char]) continue\n while (stack.length && char < stack[stack.length - 1] && last[stack[stack.length - 1]] > i) {\n added[stack[stack.length - 1]] = false\n stack.pop()\n }\n stack.push(char)\n added[char] = true\n }\n return stack.join('')\n}" ]
318
maximum-product-of-word-lengths
[]
/** * @param {string[]} words * @return {number} */ var maxProduct = function(words) { };
Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.   Example 1: Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"] Output: 16 Explanation: The two words can be "abcw", "xtfn". Example 2: Input: words = ["a","ab","abc","d","cd","bcd","abcd"] Output: 4 Explanation: The two words can be "ab", "cd". Example 3: Input: words = ["a","aa","aaa","aaaa"] Output: 0 Explanation: No such pair of words.   Constraints: 2 <= words.length <= 1000 1 <= words[i].length <= 1000 words[i] consists only of lowercase English letters.
Medium
[ "array", "string", "bit-manipulation" ]
[ "const maxProduct = function(words) {\n if (words == null || words.length === 0) return 0;\n let len = words.length;\n let value = [];\n for (let i = 0; i < len; i++) {\n let tmp = words[i];\n value[i] = 0;\n for (let j = 0; j < tmp.length; j++) {\n value[i] |= 1 << (tmp.charAt(j).charCodeAt(0) - \"a\".charCodeAt(0));\n }\n }\n let maxProductNum = 0;\n for (let i = 0; i < len; i++)\n for (let j = i + 1; j < len; j++) {\n if (\n (value[i] & value[j]) === 0 &&\n words[i].length * words[j].length > maxProductNum\n )\n maxProductNum = words[i].length * words[j].length;\n }\n return maxProductNum;\n};" ]
319
bulb-switcher
[]
/** * @param {number} n * @return {number} */ var bulbSwitch = function(n) { };
There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Return the number of bulbs that are on after n rounds.   Example 1: Input: n = 3 Output: 1 Explanation: At first, the three bulbs are [off, off, off]. After the first round, the three bulbs are [on, on, on]. After the second round, the three bulbs are [on, off, on]. After the third round, the three bulbs are [on, off, off]. So you should return 1 because there is only one bulb is on. Example 2: Input: n = 0 Output: 0 Example 3: Input: n = 1 Output: 1   Constraints: 0 <= n <= 109
Medium
[ "math", "brainteaser" ]
[ "const bulbSwitch = function(n) {\n return Math.floor(Math.sqrt(n));\n};" ]
321
create-maximum-number
[]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @param {number} k * @return {number[]} */ var maxNumber = function(nums1, nums2, k) { };
You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k. Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved. Return an array of the k digits representing the answer.   Example 1: Input: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5 Output: [9,8,6,5,3] Example 2: Input: nums1 = [6,7], nums2 = [6,0,4], k = 5 Output: [6,7,6,0,4] Example 3: Input: nums1 = [3,9], nums2 = [8,9], k = 3 Output: [9,8,9]   Constraints: m == nums1.length n == nums2.length 1 <= m, n <= 500 0 <= nums1[i], nums2[i] <= 9 1 <= k <= m + n
Hard
[ "stack", "greedy", "monotonic-stack" ]
[ "const maxNumber = function(nums1, nums2, k) {\n const n = nums1.length\n const m = nums2.length\n let ans = new Array(k).fill(0)\n for (let i = Math.max(0, k - m); i <= k && i <= n; i++) {\n const candidate = merge(maxArray(nums1, i), maxArray(nums2, k - i), k)\n if (greater(candidate, 0, ans, 0)) ans = candidate\n }\n return ans\n}\n\nfunction merge(nums1, nums2, k) {\n const ans = new Array(k)\n for (let i = 0, j = 0, r = 0; r < k; r++) {\n ans[r] = greater(nums1, i, nums2, j) ? nums1[i++] : nums2[j++]\n }\n return ans\n}\n\nfunction greater(nums1, i, nums2, j) {\n while (i < nums1.length && j < nums2.length && nums1[i] === nums2[j]) {\n i++\n j++\n }\n return j === nums2.length || (i < nums1.length && nums1[i] > nums2[j])\n}\n\nfunction maxArray(nums, k) {\n const n = nums.length\n const ans = new Array(k)\n for (let i = 0, j = 0; i < n; i++) {\n while (n - i > k - j && j > 0 && ans[j - 1] < nums[i]) j--\n if (j < k) ans[j++] = nums[i]\n }\n return ans\n}" ]
322
coin-change
[]
/** * @param {number[]} coins * @param {number} amount * @return {number} */ var coinChange = function(coins, amount) { };
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin.   Example 1: Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 Example 2: Input: coins = [2], amount = 3 Output: -1 Example 3: Input: coins = [1], amount = 0 Output: 0   Constraints: 1 <= coins.length <= 12 1 <= coins[i] <= 231 - 1 0 <= amount <= 104
Medium
[ "array", "dynamic-programming", "breadth-first-search" ]
[ "const findItinerary = function (tickets) {\n const result = []\n const map = new Map()\n for (const [from, to] of tickets) {\n if (!map.has(from)) {\n map.set(from, [])\n }\n map.get(from).push(to)\n }\n for (const key of map.keys()) {\n map.get(key).sort()\n }\n function dfs(departure) {\n const destination = map.get(departure)\n while (destination && destination.length) {\n const newDeparture = destination.shift()\n dfs(newDeparture)\n }\n result.push(departure)\n }\n dfs('JFK')\n return result.reverse()\n}" ]
324
wiggle-sort-ii
[]
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var wiggleSort = function(nums) { };
Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... You may assume the input array always has a valid answer.   Example 1: Input: nums = [1,5,1,1,6,4] Output: [1,6,1,5,1,4] Explanation: [1,4,1,5,1,6] is also accepted. Example 2: Input: nums = [1,3,2,2,3,1] Output: [2,3,1,3,1,2]   Constraints: 1 <= nums.length <= 5 * 104 0 <= nums[i] <= 5000 It is guaranteed that there will be an answer for the given input nums.   Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space?
Medium
[ "array", "divide-and-conquer", "sorting", "quickselect" ]
[ "const wiggleSort = function(nums) {\n nums.sort((a, b) => a - b)\n const ref = [...nums]\n let j = nums.length - 1\n for (let i = 1; i < nums.length; i += 2, j--) nums[i] = ref[j]\n for (let i = 0; i < nums.length; i += 2, j--) nums[i] = ref[j]\n}" ]
326
power-of-three
[]
/** * @param {number} n * @return {boolean} */ var isPowerOfThree = function(n) { };
Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x.   Example 1: Input: n = 27 Output: true Explanation: 27 = 33 Example 2: Input: n = 0 Output: false Explanation: There is no x where 3x = 0. Example 3: Input: n = -1 Output: false Explanation: There is no x where 3x = (-1).   Constraints: -231 <= n <= 231 - 1   Follow up: Could you solve it without loops/recursion?
Easy
[ "math", "recursion" ]
[ "const isPowerOfThree = function(n) {\n const maxInt = Math.pow(3,30)\n if(n < 0) {\n return false\n }\n return maxInt % n === 0\n} ", "const isPowerOfThree = function(n) {\n if (n == 1) return true\n if (n === 0) return false\n if (n % 3 !== 0) return false\n if (n == 3) return true\n return isPowerOfThree(n / 3)\n}", "const isPowerOfThree = function(n) {\n if(n == null || n === 0) return false\n let num = 1\n while(num < n) {\n num *= 3\n } \n return num > n ? false : true\n}" ]
327
count-of-range-sum
[]
/** * @param {number[]} nums * @param {number} lower * @param {number} upper * @return {number} */ var countRangeSum = function(nums, lower, upper) { };
Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j.   Example 1: Input: nums = [-2,5,-1], lower = -2, upper = 2 Output: 3 Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. Example 2: Input: nums = [0], lower = 0, upper = 0 Output: 1   Constraints: 1 <= nums.length <= 105 -231 <= nums[i] <= 231 - 1 -105 <= lower <= upper <= 105 The answer is guaranteed to fit in a 32-bit integer.
Hard
[ "array", "binary-search", "divide-and-conquer", "binary-indexed-tree", "segment-tree", "merge-sort", "ordered-set" ]
[ "const countRangeSum = function (nums, lower, upper) {\n if (nums.length === 0) return 0\n const sums = [nums[0]]\n for (let i = 1; i < nums.length; i++) {\n sums[i] = sums[i - 1] + nums[i]\n }\n function merge_sort(A, lo, hi) {\n if (hi - lo === 1) {\n return sums[lo] >= lower && sums[lo] <= upper ? 1 : 0\n }\n const mid = lo + Math.floor((hi - lo) / 2)\n let counter = merge_sort(A, lo, mid) + merge_sort(A, mid, hi)\n let m = mid,\n n = mid\n for (let i = lo; i < mid; i++) {\n while (m !== hi && sums[m] - sums[i] < lower) {\n m++\n }\n while (n !== hi && sums[n] - sums[i] <= upper) {\n n++\n }\n counter += n - m\n }\n const M = A.slice(lo, mid)\n const N = A.slice(mid, hi)\n M.push(Number.MAX_SAFE_INTEGER)\n N.push(Number.MAX_SAFE_INTEGER)\n for (let k = lo, i = 0, j = 0; k < hi; k++) {\n A[k] = M[i] < N[j] ? M[i++] : N[j++]\n }\n return counter\n }\n return merge_sort(sums, 0, nums.length)\n}" ]
328
odd-even-linked-list
[]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {ListNode} */ var oddEvenList = function(head) { };
Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1) extra space complexity and O(n) time complexity.   Example 1: Input: head = [1,2,3,4,5] Output: [1,3,5,2,4] Example 2: Input: head = [2,1,3,5,6,4,7] Output: [2,3,6,7,1,5,4]   Constraints: The number of nodes in the linked list is in the range [0, 104]. -106 <= Node.val <= 106
Medium
[ "linked-list" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "const oddEvenList = function(head) {\n if (head === null) return null;\n let odd = head,\n even = head.next,\n evenHead = even;\n while (even !== null && even.next !== null) {\n odd.next = even.next;\n odd = odd.next;\n even.next = odd.next;\n even = even.next;\n }\n odd.next = evenHead;\n return head;\n};", "function oddEvenList(head) {\n if(head == null) return head\n const dummyOdd = new ListNode()\n const dummyEven = new ListNode()\n \n dummyOdd.next = head\n let odd = head, even = dummyEven\n let idx = 2, cur = head.next\n while(cur) {\n if (idx % 2 === 1) {\n odd.next = cur\n odd = odd.next\n } else {\n even.next = cur\n even = even.next\n }\n cur = cur.next\n idx++\n }\n odd.next = dummyEven.next\n even.next = null\n return dummyOdd.next\n}" ]
329
longest-increasing-path-in-a-matrix
[]
/** * @param {number[][]} matrix * @return {number} */ var longestIncreasingPath = function(matrix) { };
Given an m x n integers matrix, return the length of the longest increasing path in matrix. From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).   Example 1: Input: matrix = [[9,9,4],[6,6,8],[2,1,1]] Output: 4 Explanation: The longest increasing path is [1, 2, 6, 9]. Example 2: Input: matrix = [[3,4,5],[3,2,6],[2,2,1]] Output: 4 Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. Example 3: Input: matrix = [[1]] Output: 1   Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 200 0 <= matrix[i][j] <= 231 - 1
Hard
[ "array", "dynamic-programming", "depth-first-search", "breadth-first-search", "graph", "topological-sort", "memoization", "matrix" ]
[ "const longestIncreasingPath = function(matrix) {\n const m = matrix.length, n = matrix[0].length\n let res = 1\n\n const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n const memo = Array.from({ length: m }, () => Array(n).fill(0))\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n const len = dfs(i, j)\n res = Math.max(res, len)\n }\n }\n \n return res\n \n function dfs(i, j) {\n const v = matrix[i][j]\n if(memo[i][j] !== 0) return memo[i][j]\n let len = 1\n for(const [dx, dy] of dirs) {\n const nx = i + dx, ny = j + dy\n if(nx >= 0 && nx < m && ny >= 0 && ny < n && matrix[nx][ny] > v) {\n const tmp = 1 + dfs(nx, ny)\n len = Math.max(len, tmp)\n }\n }\n \n memo[i][j] = len\n return len\n }\n};", "const longestIncreasingPath = function (matrix) {\n const dirs = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ]\n const m = matrix.length,\n n = matrix[0].length\n let res = 1\n const memo = Array.from({ length: m }, () => Array(n).fill(0))\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n const tmp = dfs(matrix, i, j, m, n, memo, dirs)\n res = Math.max(tmp, res)\n }\n }\n return res\n}\n\nfunction dfs(matrix, i, j, m, n, memo, dirs) {\n if (memo[i][j] !== 0) return memo[i][j]\n let res = 1\n for (let [dx, dy] of dirs) {\n const nx = i + dx,\n ny = j + dy\n if (\n nx < 0 ||\n nx >= m ||\n ny < 0 ||\n ny >= n ||\n matrix[nx][ny] <= matrix[i][j]\n )\n continue\n const tmp = 1 + dfs(matrix, nx, ny, m, n, memo, dirs)\n res = Math.max(res, tmp)\n }\n memo[i][j] = res\n return res\n}" ]
330
patching-array
[]
/** * @param {number[]} nums * @param {number} n * @return {number} */ var minPatches = function(nums, n) { };
Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.   Example 1: Input: nums = [1,3], n = 6 Output: 1 Explanation: Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. So we only need 1 patch. Example 2: Input: nums = [1,5,10], n = 20 Output: 2 Explanation: The two patches can be [2, 4]. Example 3: Input: nums = [1,2,2], n = 5 Output: 0   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 104 nums is sorted in ascending order. 1 <= n <= 231 - 1
Hard
[ "array", "greedy" ]
[ "const minPatches = function(nums, n) {\n let answer = 0\n for (let i = 0, next = 1; next <= n; ) {\n if (i >= nums.length || nums[i] > next) {\n answer++\n next *= 2\n } else next += nums[i++]\n }\n return answer\n}" ]
331
verify-preorder-serialization-of-a-binary-tree
[]
/** * @param {string} preorder * @return {boolean} */ var isValidSerialization = function(preorder) { };
One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'. For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a null node. Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree. It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid. For example, it could never contain two consecutive commas, such as "1,,3". Note: You are not allowed to reconstruct the tree.   Example 1: Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" Output: true Example 2: Input: preorder = "1,#" Output: false Example 3: Input: preorder = "9,#,#,1" Output: false   Constraints: 1 <= preorder.length <= 104 preorder consist of integers in the range [0, 100] and '#' separated by commas ','.
Medium
[ "string", "stack", "tree", "binary-tree" ]
[ "const isValidSerialization = function(preorder) {\n const nodes = preorder.split(',')\n let diff = 1\n for(let node of nodes) {\n if(--diff < 0) return false\n if(node !== '#') diff += 2\n }\n return diff === 0\n};" ]
332
reconstruct-itinerary
[]
/** * @param {string[][]} tickets * @return {string[]} */ var findItinerary = function(tickets) { };
You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.   Example 1: Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] Output: ["JFK","MUC","LHR","SFO","SJC"] Example 2: Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order.   Constraints: 1 <= tickets.length <= 300 tickets[i].length == 2 fromi.length == 3 toi.length == 3 fromi and toi consist of uppercase English letters. fromi != toi
Hard
[ "depth-first-search", "graph", "eulerian-circuit" ]
null
[]
334
increasing-triplet-subsequence
[]
/** * @param {number[]} nums * @return {boolean} */ var increasingTriplet = function(nums) { };
Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.   Example 1: Input: nums = [1,2,3,4,5] Output: true Explanation: Any triplet where i < j < k is valid. Example 2: Input: nums = [5,4,3,2,1] Output: false Explanation: No triplet exists. Example 3: Input: nums = [2,1,5,0,4,6] Output: true Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.   Constraints: 1 <= nums.length <= 5 * 105 -231 <= nums[i] <= 231 - 1   Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?
Medium
[ "array", "greedy" ]
[ "const increasingTriplet = function(nums) {\n // start with two largest values, as soon as we find a number bigger than both, while both have been updated, return true.\n let small = Number.MAX_VALUE, big = Number.MAX_VALUE;\n for (let n of nums) {\n if (n <= small) { small = n; } // update small if n is smaller than both\n else if (n <= big) { big = n; } // update big only if greater than small but smaller than big\n else return true; // return if you find a number bigger than both\n }\n return false;\n};", "const increasingTriplet = function(nums) {\n const n = nums.length, stk = []\n for(let e of nums) {\n let l = 0, r = stk.length\n while(l < r) {\n const mid = l + Math.floor((r - l) / 2)\n if (e > stk[mid]) l = mid + 1\n else r = mid \n }\n\n stk[l] = e\n if(stk.length > 2) return true\n }\n\n return false\n};", "const increasingTriplet = function(nums) {\n let small = Number.MAX_VALUE, big = Number.MAX_VALUE\n \n for(const e of nums) {\n if(e <= small) small = e\n else if(e <= big) big = e\n else return true\n }\n \n return false\n};" ]
335
self-crossing
[]
/** * @param {number[]} distance * @return {boolean} */ var isSelfCrossing = function(distance) { };
You are given an array of integers distance. You start at the point (0, 0) on an X-Y plane, and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. Return true if your path crosses itself or false if it does not.   Example 1: Input: distance = [2,1,1,2] Output: true Explanation: The path crosses itself at the point (0, 1). Example 2: Input: distance = [1,2,3,4] Output: false Explanation: The path does not cross itself at any point. Example 3: Input: distance = [1,1,1,2,1] Output: true Explanation: The path crosses itself at the point (0, 0).   Constraints: 1 <= distance.length <= 105 1 <= distance[i] <= 105
Hard
[ "array", "math", "geometry" ]
[ "const isSelfCrossing = function(x) {\n for (let i = 3, l = x.length; i < l; i++) {\n // Case 1: current line crosses the line 3 steps ahead of it\n if (x[i] >= x[i - 2] && x[i - 1] <= x[i - 3]) return true\n // Case 2: current line crosses the line 4 steps ahead of it\n else if (i >= 4 && x[i - 1] == x[i - 3] && x[i] + x[i - 4] >= x[i - 2])\n return true\n // Case 3: current line crosses the line 6 steps ahead of it\n else if (\n i >= 5 &&\n x[i - 2] >= x[i - 4] &&\n x[i] + x[i - 4] >= x[i - 2] &&\n x[i - 1] <= x[i - 3] &&\n x[i - 1] + x[i - 5] >= x[i - 3]\n )\n return true\n }\n return false\n}" ]
336
palindrome-pairs
[ "Checking every two pairs will exceed the time limit. It will be O(n^2 * k). We need a faster way.", "If we hash every string in the array, how can we check if two pairs form a palindrome after the concatenation?", "We can check every string in words and consider it as words[j] (i.e., the suffix of the target palindrome). We can check if there is a hash of string that can be the prefix to make it a palindrome." ]
/** * @param {string[]} words * @return {number[][]} */ var palindromePairs = function(words) { };
You are given a 0-indexed array of unique strings words. A palindrome pair is a pair of integers (i, j) such that: 0 <= i, j < words.length, i != j, and words[i] + words[j] (the concatenation of the two strings) is a palindrome. Return an array of all the palindrome pairs of words. You must write an algorithm with O(sum of words[i].length) runtime complexity.   Example 1: Input: words = ["abcd","dcba","lls","s","sssll"] Output: [[0,1],[1,0],[3,2],[2,4]] Explanation: The palindromes are ["abcddcba","dcbaabcd","slls","llssssll"] Example 2: Input: words = ["bat","tab","cat"] Output: [[0,1],[1,0]] Explanation: The palindromes are ["battab","tabbat"] Example 3: Input: words = ["a",""] Output: [[0,1],[1,0]] Explanation: The palindromes are ["a","a"]   Constraints: 1 <= words.length <= 5000 0 <= words[i].length <= 300 words[i] consists of lowercase English letters.
Hard
[ "array", "hash-table", "string", "trie" ]
[ "const palindromePairs = function(words) {\n const root = new Trie();\n const pairs = [];\n words.forEach((word, index) => addWord(word, index, root));\n words.forEach((word, index) => searchWord(word, index, root, pairs));\n return pairs;\n};\n\nconst addWord = (word, wordIndex, root) => { \n const length = word.length;\n let curr = root;\n for (let i = length - 1; i >= 0; i--) {\n let char = word.charAt(i);\n if (!curr.children[char]) curr.children[char] = new Trie();\n if (isPalindrome(0, i, word)) curr.words.push(wordIndex);\n curr = curr.children[char];\n }\n curr.wordIndex = wordIndex;\n curr.words.push(wordIndex);\n}\n\nconst searchWord = (word, wordIndex, root, pairs) => {\n const length = word.length;\n let curr = root;\n for (let i = 0; i < length; i++) {\n let char = word.charAt(i);\n if (curr.wordIndex >= 0 && curr.wordIndex !== wordIndex && isPalindrome(i, length - 1, word)) {\n pairs.push([wordIndex, curr.wordIndex]);\n }\n curr = curr.children[char];\n if (!curr) return;\n }\n \n curr.words.forEach((suffix) => {\n if (suffix !== wordIndex) pairs.push([wordIndex, suffix]);\n })\n}\n\nconst isPalindrome = (left, right, word) => {\n while (left < right) {\n if (word.charAt(left++) !== word.charAt(right--)) return false;\n }\n return true;\n}\n\nclass Trie {\n constructor() {\n this.wordIndex = -1;\n this.children = {};\n this.words = [];\n }\n}", "const reverseStr = s => {\n let str = ''\n for (let i = 0; i < s.length; i++) {\n str = s[i] + str\n }\n return str\n}\nconst isPalindrome = str => {\n for (let i = 0; i < str.length / 2; i++) {\n if (str[i] !== str[str.length - 1 - i]) return false\n }\n return true\n}\n\nconst palindromePairs = function(words) {\n const map = new Map()\n words.forEach((word, idx) => map.set(word, idx))\n const result = []\n if (map.has('')) {\n const idx = map.get('')\n words.forEach((word, i) => {\n if (i !== idx && isPalindrome(word)) {\n result.push([idx, map.get(word)])\n result.push([map.get(word), idx])\n }\n })\n }\n map.delete('')\n words.forEach((word, idx) => {\n for (let i = 0; i < word.length; i++) {\n const left = word.slice(0, i)\n const right = word.slice(i)\n if (isPalindrome(left)) {\n const reversedRight = reverseStr(right)\n if (map.has(reversedRight) && map.get(reversedRight) !== idx) {\n result.push([map.get(reversedRight), idx])\n }\n }\n if (isPalindrome(right)) {\n const reversedLeft = reverseStr(left)\n if (map.has(reversedLeft) && map.get(reversedLeft) !== idx) {\n result.push([idx, map.get(reversedLeft)])\n }\n }\n }\n })\n return result\n}" ]
337
house-robber-iii
[]
/** * 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 rob = function(root) { };
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root. Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night. Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.   Example 1: Input: root = [3,2,3,null,3,null,1] Output: 7 Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. Example 2: Input: root = [3,4,5,1,3,null,1] Output: 9 Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.   Constraints: The number of nodes in the tree is in the range [1, 104]. 0 <= Node.val <= 104
Medium
[ "dynamic-programming", "tree", "depth-first-search", "binary-tree" ]
/** * 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) * } */
[ "const rob = function(root) {\n return Math.max(...dfs(root))\n}\n\nfunction dfs(node) {\n if (node == null) return [0, 0]\n const left = dfs(node.left)\n const right = dfs(node.right)\n return [\n node.val + left[1] + right[1],\n Math.max(left[0], left[1]) + Math.max(right[0], right[1])\n ]\n}" ]
338
counting-bits
[ "You should make use of what you have produced already.", "Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.", "Or does the odd/even status of the number help you in calculating the number of 1s?" ]
/** * @param {number} n * @return {number[]} */ var countBits = function(n) { };
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.   Example 1: Input: n = 2 Output: [0,1,1] Explanation: 0 --> 0 1 --> 1 2 --> 10 Example 2: Input: n = 5 Output: [0,1,1,2,1,2] Explanation: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101   Constraints: 0 <= n <= 105   Follow up: It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass? Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)?
Easy
[ "dynamic-programming", "bit-manipulation" ]
[ "const countBits = function (num) {\n const f = new Array(num + 1).fill(0)\n for (let i = 1; i <= num; i++) f[i] = f[i >> 1] + (i & 1)\n return f\n}" ]
341
flatten-nested-list-iterator
[]
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * function NestedInteger() { * * Return true if this NestedInteger holds a single integer, rather than a nested list. * @return {boolean} * this.isInteger = function() { * ... * }; * * Return the single integer that this NestedInteger holds, if it holds a single integer * Return null if this NestedInteger holds a nested list * @return {integer} * this.getInteger = function() { * ... * }; * * Return the nested list that this NestedInteger holds, if it holds a nested list * Return null if this NestedInteger holds a single integer * @return {NestedInteger[]} * this.getList = function() { * ... * }; * }; */ /** * @constructor * @param {NestedInteger[]} nestedList */ var NestedIterator = function(nestedList) { }; /** * @this NestedIterator * @returns {boolean} */ NestedIterator.prototype.hasNext = function() { }; /** * @this NestedIterator * @returns {integer} */ NestedIterator.prototype.next = function() { }; /** * Your NestedIterator will be called like this: * var i = new NestedIterator(nestedList), a = []; * while (i.hasNext()) a.push(i.next()); */
You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the NestedIterator class: NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList. int next() Returns the next integer in the nested list. boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise. Your code will be tested with the following pseudocode: initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res If res matches the expected flattened list, then your code will be judged as correct.   Example 1: Input: nestedList = [[1,1],2,[1,1]] Output: [1,1,2,1,1] Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. Example 2: Input: nestedList = [1,[4,[6]]] Output: [1,4,6] Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].   Constraints: 1 <= nestedList.length <= 500 The values of the integers in the nested list is in the range [-106, 106].
Medium
[ "stack", "tree", "depth-first-search", "design", "queue", "iterator" ]
[ "function flat(arr, res) {\n for(let i = 0; i < arr.length; i++) {\n if(arr[i].isInteger()) {\n res.push(arr[i].getInteger())\n } else {\n flat(arr[i].getList() ,res) \n }\n\n }\n}\nconst NestedIterator = function(nestedList) {\n this.arr = []\n this.idx = -1\n flat(nestedList, this.arr)\n};\n\n\n\nNestedIterator.prototype.hasNext = function() {\n return this.idx + 1 < this.arr.length\n};\n\n\nNestedIterator.prototype.next = function() {\n this.idx += 1\n return this.arr[this.idx]\n};" ]
342
power-of-four
[]
/** * @param {number} n * @return {boolean} */ var isPowerOfFour = function(n) { };
Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x.   Example 1: Input: n = 16 Output: true Example 2: Input: n = 5 Output: false Example 3: Input: n = 1 Output: true   Constraints: -231 <= n <= 231 - 1   Follow up: Could you solve it without loops/recursion?
Easy
[ "math", "bit-manipulation", "recursion" ]
[ "const isPowerOfFour = function(num) {\n if (num === 1) { return true; }\n let f = 4;\n while (f <= num) {\n if (f === num) {\n return true;\n }\n f *= 4;\n }\n return false;\n};" ]
343
integer-break
[ "There is a simple O(n) solution to this problem.", "You may check the breaking results of <i>n</i> ranging from 7 to 10 to discover the regularities." ]
/** * @param {number} n * @return {number} */ var integerBreak = function(n) { };
Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. Return the maximum product you can get.   Example 1: Input: n = 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1. Example 2: Input: n = 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.   Constraints: 2 <= n <= 58
Medium
[ "math", "dynamic-programming" ]
[ "const integerBreak = function(n) {\n const dp = Array(n + 1).fill(0)\n dp[2] = 1\n for(let i = 3; i <= n; i++) {\n for(let j = 1; j < i; j++) {\n dp[i] = Math.max(dp[i], j * Math.max(i - j, dp[i - j]))\n }\n }\n return dp[n]\n};", "const integerBreak = function(n) {\n if (n <= 2) return 1;\n\n const maxArr = [];\n for (let i = 0; i < n + 1; i++) {\n maxArr[i] = 0;\n }\n\n \n\n maxArr[1] = 0;\n maxArr[2] = 1; // 2=1+1 so maxArr[2] = 1*1\n\n for (let i = 3; i <= n; i++) {\n for (let j = 1; j < i; j++) {\n \n maxArr[i] = Math.max(maxArr[i], j * (i - j), j * maxArr[i - j]);\n }\n }\n return maxArr[n];\n};", "const integerBreak = function(n) {\n if(n === 2) return 1\n if(n === 3) return 2\n let num = ~~(n / 3)\n let rem = n % 3\n if(rem === 1) {\n rem += 3\n num--\n }\n return rem === 0 ? Math.pow(3, num) : Math.pow(3, num) * rem\n};" ]
344
reverse-string
[ "The entire logic for reversing a string is based on using the opposite directional two-pointer approach!" ]
/** * @param {character[]} s * @return {void} Do not return anything, modify s in-place instead. */ var reverseString = function(s) { };
Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory.   Example 1: Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"] Example 2: Input: s = ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"]   Constraints: 1 <= s.length <= 105 s[i] is a printable ascii character.
Easy
[ "two-pointers", "string" ]
[ "const reverseString = function(s) {\n s.reverse()\n};", "const reverseString = function(s) {\n\tfor(let i = 0; i < s.length / 2; i++){\n\t\t[ s[i] , s[s.length - 1 - i] ] = [ s[s.length - 1 - i] , s[i] ];\n\t}\n};" ]
345
reverse-vowels-of-a-string
[]
/** * @param {string} s * @return {string} */ var reverseVowels = function(s) { };
Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.   Example 1: Input: s = "hello" Output: "holle" Example 2: Input: s = "leetcode" Output: "leotcede"   Constraints: 1 <= s.length <= 3 * 105 s consist of printable ASCII characters.
Easy
[ "two-pointers", "string" ]
[ "const reverseVowels = function(s) {\n if(s == null || s === '') return ''\n const arr = s.split('')\n let p = 0\n const len = s.length\n let e = s.length - 1\n const v = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n while(p < e) {\n while(v.indexOf(arr[p]) === -1 && p < e) p++\n while(v.indexOf(arr[e]) === -1 && p < e) e--\n const tmp = arr[p]\n arr[p] = arr[e]\n arr[e] = tmp \n p++\n e--\n }\n return arr.join('')\n};", "const reverseVowels = function(s) {\n let vowels = s.match(/[aeiou]/gi)\n let k = 0\n if (vowels) {\n vowels = vowels.reverse``\n } else {\n return s\n }\n return s.replace(/[aeiou]/gi, () => vowels[k++])\n}" ]
347
top-k-frequent-elements
[]
/** * @param {number[]} nums * @param {number} k * @return {number[]} */ var topKFrequent = function(nums, k) { };
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.   Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1]   Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 k is in the range [1, the number of unique elements in the array]. It is guaranteed that the answer is unique.   Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
Medium
[ "array", "hash-table", "divide-and-conquer", "sorting", "heap-priority-queue", "bucket-sort", "counting", "quickselect" ]
[ "const topKFrequent = function(nums, k) {\n const hash = {}\n for(let i = 0; i < nums.length; i++) {\n if(hash.hasOwnProperty(nums[i])) hash[nums[i]]++\n else hash[nums[i]] = 1\n }\n const res = new Array()\n const keys = Object.keys(hash)\n \n const bucket = new Array(nums.length)\n \n for(let k of keys) {\n let freq = hash[k]\n if(bucket[freq] == null) {\n bucket[freq] = []\n }\n bucket[freq].push(k)\n }\n \n for(let i = bucket.length - 1; i >= 0 && res.length < k; i--) {\n if(bucket[i] != null) {\n res.push(...bucket[i])\n }\n }\n \n return res\n};", "const topKFrequent = function(nums, k) {\n const hash = {}\n for(let n of nums) {\n if(hash[n] == null) hash[n] = 0\n hash[n]++\n }\n const entries = Object.entries(hash)\n let min = Infinity, max = -Infinity\n const reverse = {}\n for(let [k, freq] of entries) {\n if(freq < min) min = freq\n if(freq > max) max = freq\n if(reverse[freq] == null) reverse[freq] = []\n reverse[freq].push(k)\n }\n const n = max - min + 1\n const arr = Array(n)\n let res = []\n let limit = max\n while(limit) {\n if(reverse[limit]) res.push(...reverse[limit])\n limit--\n if(res.length >= k) break\n }\n res.splice(k)\n return res\n};", " const topKFrequent = function(nums, k) {\n const n = nums.length\n const freq = Array(n + 1).fill(null)\n const hash = {}\n for(let e of nums) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n for(let k in hash) {\n if(hash.hasOwnProperty(k)) {\n const v = hash[k]\n if(freq[v] == null) freq[v] = []\n freq[v].push(k)\n }\n }\n const res = []\n for(let i = n; i >= 0; i--) {\n if(freq[i] != null) res.push(...freq[i])\n if(res.length >= k) break\n }\n if(res.length > k) res.splice(k)\n return res\n};" ]
349
intersection-of-two-arrays
[]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var intersection = function(nums1, nums2) { };
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.   Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Explanation: [4,9] is also accepted.   Constraints: 1 <= nums1.length, nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 1000
Easy
[ "array", "hash-table", "two-pointers", "binary-search", "sorting" ]
[ "const intersection = function(nums1, nums2) {\n const obj = {};\n nums1.forEach(i => (obj[i] = true));\n\n return nums2.filter(j => {\n if (obj[j]) {\n delete obj[j];\n return true;\n }\n return false;\n });\n};" ]
350
intersection-of-two-arrays-ii
[]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var intersect = function(nums1, nums2) { };
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.   Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Explanation: [9,4] is also accepted.   Constraints: 1 <= nums1.length, nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 1000   Follow up: What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to nums2's size? Which algorithm is better? What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
Easy
[ "array", "hash-table", "two-pointers", "binary-search", "sorting" ]
[ "const intersect = function(nums1, nums2) {\n const res = []\n const map = {}\n for(let i = 0; i < nums1.length; i++) {\n if(map.hasOwnProperty(nums1[i])) {\n map[nums1[i]] += 1\n } else {\n map[nums1[i]] = 1\n }\n }\n \n for(let j = 0; j < nums2.length; j++) {\n if(map.hasOwnProperty(nums2[j]) && map[nums2[j]] > 0) {\n res.push(nums2[j])\n map[nums2[j]] -= 1\n }\n }\n \n return res\n};" ]
352
data-stream-as-disjoint-intervals
[]
var SummaryRanges = function() { }; /** * @param {number} value * @return {void} */ SummaryRanges.prototype.addNum = function(value) { }; /** * @return {number[][]} */ SummaryRanges.prototype.getIntervals = function() { }; /** * Your SummaryRanges object will be instantiated and called as such: * var obj = new SummaryRanges() * obj.addNum(value) * var param_2 = obj.getIntervals() */
Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals. Implement the SummaryRanges class: SummaryRanges() Initializes the object with an empty stream. void addNum(int value) Adds the integer value to the stream. int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi]. The answer should be sorted by starti.   Example 1: Input ["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"] [[], [1], [], [3], [], [7], [], [2], [], [6], []] Output [null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]] Explanation SummaryRanges summaryRanges = new SummaryRanges(); summaryRanges.addNum(1); // arr = [1] summaryRanges.getIntervals(); // return [[1, 1]] summaryRanges.addNum(3); // arr = [1, 3] summaryRanges.getIntervals(); // return [[1, 1], [3, 3]] summaryRanges.addNum(7); // arr = [1, 3, 7] summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]] summaryRanges.addNum(2); // arr = [1, 2, 3, 7] summaryRanges.getIntervals(); // return [[1, 3], [7, 7]] summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7] summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]   Constraints: 0 <= value <= 104 At most 3 * 104 calls will be made to addNum and getIntervals. At most 102 calls will be made to getIntervals.   Follow up: What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
Hard
[ "binary-search", "design", "ordered-set" ]
[ "var SummaryRanges = function() {\n this.intervals = []\n}\n\n\nSummaryRanges.prototype.addNum = function(val) {\n const current = [val, val]\n const intervals = this.intervals\n const less = []\n const more = []\n for (let vals of intervals) {\n if (vals[0] > current[1] + 1) {\n more.push(vals)\n } else if (vals[1] + 1 < current[0]) {\n less.push(vals)\n } else {\n current[0] = Math.min(current[0], vals[0])\n current[1] = Math.max(current[1], vals[1])\n }\n }\n this.intervals = [...less, current, ...more]\n}\n\n\nSummaryRanges.prototype.getIntervals = function() {\n return this.intervals\n}" ]
354
russian-doll-envelopes
[]
/** * @param {number[][]} envelopes * @return {number} */ var maxEnvelopes = function(envelopes) { };
You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other). Note: You cannot rotate an envelope.   Example 1: Input: envelopes = [[5,4],[6,4],[6,7],[2,3]] Output: 3 Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). Example 2: Input: envelopes = [[1,1],[1,1],[1,1]] Output: 1   Constraints: 1 <= envelopes.length <= 105 envelopes[i].length == 2 1 <= wi, hi <= 105
Hard
[ "array", "binary-search", "dynamic-programming", "sorting" ]
[ "const maxEnvelopes = function(envelopes) {\n const env = envelopes\n env.sort((a, b) => a[0] - b[0] || b[1] - a[1])\n const stk = []\n for(const e of env) {\n if(stk.length === 0 || e[1] > stk[stk.length - 1][1]) {\n stk.push(e)\n continue\n }\n let l = 0, r = stk.length - 1\n while(l < r) {\n const mid = l + Math.floor((r - l) / 2)\n if(stk[mid][1] < e[1]) l = mid + 1\n else r = mid\n }\n \n stk[l] = e\n }\n \n return stk.length\n};", "const maxEnvelopes = function(envelopes) {\n envelopes.sort((a, b) => {\n if (a[0] == b[0]) {\n return b[1] - a[1]\n } else {\n return a[0] - b[0]\n }\n })\n const n = envelopes.length\n const dp = []\n for (let i = 0; i < n; i++) {\n let l = 0,\n r = dp.length,\n t = envelopes[i][1]\n while (l < r) {\n let m = l + ~~((r - l) / 2)\n if (dp[m] < t) l = m + 1\n else r = m\n }\n if (r >= dp.length) dp.push(t)\n else dp[r] = t\n }\n return dp.length\n}", "const maxEnvelopes = function(envelopes) {\n envelopes.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])\n const stack = []\n for(let e of envelopes) {\n if(stack.length === 0 || e[1] > stack[stack.length - 1][1]) {\n stack.push(e)\n continue\n }\n let l = 0, r = stack.length - 1\n while(l < r) {\n const mid = ~~((l+r)/2)\n if(stack[mid][1] < e[1]) {\n l = mid + 1\n } else r = mid\n }\n stack[l] = e\n }\n return stack.length\n};" ]
355
design-twitter
[]
var Twitter = function() { }; /** * @param {number} userId * @param {number} tweetId * @return {void} */ Twitter.prototype.postTweet = function(userId, tweetId) { }; /** * @param {number} userId * @return {number[]} */ Twitter.prototype.getNewsFeed = function(userId) { }; /** * @param {number} followerId * @param {number} followeeId * @return {void} */ Twitter.prototype.follow = function(followerId, followeeId) { }; /** * @param {number} followerId * @param {number} followeeId * @return {void} */ Twitter.prototype.unfollow = function(followerId, followeeId) { }; /** * Your Twitter object will be instantiated and called as such: * var obj = new Twitter() * obj.postTweet(userId,tweetId) * var param_2 = obj.getNewsFeed(userId) * obj.follow(followerId,followeeId) * obj.unfollow(followerId,followeeId) */
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user's news feed. Implement the Twitter class: Twitter() Initializes your twitter object. void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user userId. Each call to this function will be made with a unique tweetId. List<Integer> getNewsFeed(int userId) Retrieves the 10 most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent. void follow(int followerId, int followeeId) The user with ID followerId started following the user with ID followeeId. void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId.   Example 1: Input ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]] Output [null, null, [5], null, null, [6, 5], null, [5]] Explanation Twitter twitter = new Twitter(); twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5] twitter.follow(1, 2); // User 1 follows user 2. twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. twitter.unfollow(1, 2); // User 1 unfollows user 2. twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.   Constraints: 1 <= userId, followerId, followeeId <= 500 0 <= tweetId <= 104 All the tweets have unique IDs. At most 3 * 104 calls will be made to postTweet, getNewsFeed, follow, and unfollow.
Medium
[ "hash-table", "linked-list", "design", "heap-priority-queue" ]
[ "const Twitter = function() {\n this.userTweets = new Map()\n this.userFollowing = new Map()\n this.lastIndex = 1\n}\n\n\nTwitter.prototype.postTweet = function(userId, tweetId) {\n let tweets = this.userTweets.get(userId)\n if (!tweets) {\n tweets = []\n this.userTweets.set(userId, tweets)\n }\n tweets.unshift({ id: tweetId, index: this.lastIndex })\n this.lastIndex = this.lastIndex + 1\n}\n\n\nTwitter.prototype.getNewsFeed = function(userId) {\n const followings = this.userFollowing.get(userId)\n let tweets = (this.userTweets.get(userId) || []).slice(0, 10)\n followings &&\n followings.forEach(uid => {\n if (uid === userId) return\n\n const userTweets = this.userTweets.get(uid)\n if (userTweets) {\n tweets = tweets.concat(userTweets)\n }\n })\n return tweets\n .sort((a, b) => b.index - a.index)\n .map(tweet => tweet.id)\n .slice(0, 10)\n}\n\n\nTwitter.prototype.follow = function(followerId, followeeId) {\n let followings = this.userFollowing.get(followerId)\n if (!followings) {\n followings = new Set()\n this.userFollowing.set(followerId, followings)\n }\n followings.add(followeeId)\n}\n\n\nTwitter.prototype.unfollow = function(followerId, followeeId) {\n const followings = this.userFollowing.get(followerId)\n followings && followings.delete(followeeId)\n}" ]
357
count-numbers-with-unique-digits
[ "A direct way is to use the backtracking approach.", "Backtracking should contains three states which are (the current number, number of steps to get that number and a bitmask which represent which number is marked as visited so far in the current number). Start with state (0,0,0) and count all valid number till we reach number of steps equals to 10<sup>n</sup>.", "This problem can also be solved using a dynamic programming approach and some knowledge of combinatorics.", "Let f(k) = count of numbers with unique digits with length equals k.", "f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0]." ]
/** * @param {number} n * @return {number} */ var countNumbersWithUniqueDigits = function(n) { };
Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.   Example 1: Input: n = 2 Output: 91 Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99 Example 2: Input: n = 0 Output: 1   Constraints: 0 <= n <= 8
Medium
[ "math", "dynamic-programming", "backtracking" ]
[ "const countNumbersWithUniqueDigits = function(n) {\n if (n === 0) return 1;\n let res = 10;\n let tmp = 9;\n let remainDigitNum = 9;\n while (n - 1 > 0 && remainDigitNum > 0) {\n tmp = tmp * remainDigitNum;\n res += tmp;\n n -= 1;\n remainDigitNum -= 1;\n }\n\n return res;\n};", "const countNumbersWithUniqueDigits = function(n) {\n const limit = 10 ** n\n let res = 1\n let m = 1\n if(n === 0) return 1\n while(10**m <= limit) {\n res += 9 * helper(9, m - 1)\n m++\n }\n \n return res\n \n function helper(m, n) {\n return n === 0 ? 1 : helper(m, n - 1) * (m - n + 1)\n }\n};", "const countNumbersWithUniqueDigits = function(n) {\n if(n === 0) return 1\n let res = 10\n let tmp = 9, digits = 9\n while(n > 1 && digits > 0) {\n tmp *= digits \n res += tmp\n n--\n digits--\n }\n \n return res\n};" ]
363
max-sum-of-rectangle-no-larger-than-k
[]
/** * @param {number[][]} matrix * @param {number} k * @return {number} */ var maxSumSubmatrix = function(matrix, k) { };
Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k. It is guaranteed that there will be a rectangle with a sum no larger than k.   Example 1: Input: matrix = [[1,0,1],[0,-2,3]], k = 2 Output: 2 Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2). Example 2: Input: matrix = [[2,2,-1]], k = 3 Output: 3   Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 100 -100 <= matrix[i][j] <= 100 -105 <= k <= 105   Follow up: What if the number of rows is much larger than the number of columns?
Hard
[ "array", "binary-search", "matrix", "prefix-sum", "ordered-set" ]
[ "const maxSumSubmatrix = function(matrix, k) {\n const row = matrix.length,\n col = matrix[0].length\n let result = -Infinity\n for (let i = 0; i < col; i++) {\n let rowSum = Array(row).fill(0)\n for (let j = i; j < col; j++) {\n let sum = 0,\n max = -Infinity\n for (let r = 0; r < row; r++) {\n rowSum[r] += matrix[r][j]\n if (sum < 0) sum = 0\n sum += rowSum[r]\n max = Math.max(max, sum)\n }\n if (max <= k) result = Math.max(result, max)\n else {\n max = -Infinity\n for (let m = 0; m < row; m++) {\n sum = 0\n for (let n = m; n < row; n++) {\n sum += rowSum[n]\n if (sum <= k) max = Math.max(max, sum)\n }\n }\n result = Math.max(result, max)\n }\n if (result === k) return k\n }\n }\n return result\n}" ]
365
water-and-jug-problem
[]
/** * @param {number} jug1Capacity * @param {number} jug2Capacity * @param {number} targetCapacity * @return {boolean} */ var canMeasureWater = function(jug1Capacity, jug2Capacity, targetCapacity) { };
You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs. If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end. Operations allowed: Fill any of the jugs with water. Empty any of the jugs. Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty.   Example 1: Input: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4 Output: true Explanation: The famous Die Hard example Example 2: Input: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5 Output: false Example 3: Input: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3 Output: true   Constraints: 1 <= jug1Capacity, jug2Capacity, targetCapacity <= 106
Medium
[ "math", "depth-first-search", "breadth-first-search" ]
[ "const canMeasureWater = function(x, y, z) {\n return z === 0 || (x + y >= z && z % gcd(x, y) === 0)\n}\nfunction gcd(x, y) {\n if (y === 0) {\n return x\n }\n return gcd(y, x % y)\n}" ]
367
valid-perfect-square
[]
/** * @param {number} num * @return {boolean} */ var isPerfectSquare = function(num) { };
Given a positive integer num, return true if num is a perfect square or false otherwise. A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself. You must not use any built-in library function, such as sqrt.   Example 1: Input: num = 16 Output: true Explanation: We return true because 4 * 4 = 16 and 4 is an integer. Example 2: Input: num = 14 Output: false Explanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer.   Constraints: 1 <= num <= 231 - 1
Easy
[ "math", "binary-search" ]
[ "const isPerfectSquare = function(num) {\n let s = 0\n let e = num\n while(s <= e) {\n const mid = s + ((e - s) >> 1)\n const res = mid ** 2\n if(res === num) return true\n if(res < num) s = mid + 1\n else e = mid - 1\n }\n return false\n};" ]
368
largest-divisible-subset
[]
/** * @param {number[]} nums * @return {number[]} */ var largestDivisibleSubset = function(nums) { };
Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies: answer[i] % answer[j] == 0, or answer[j] % answer[i] == 0 If there are multiple solutions, return any of them.   Example 1: Input: nums = [1,2,3] Output: [1,2] Explanation: [1,3] is also accepted. Example 2: Input: nums = [1,2,4,8] Output: [1,2,4,8]   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 2 * 109 All the integers in nums are unique.
Medium
[ "array", "math", "dynamic-programming", "sorting" ]
[ "const largestDivisibleSubset = function(nums) {\n const n = nums.length;\n if(n === 0 || n === 1) return nums\n let maxSize = 0;\n const dp = Array(n).fill(1)\n nums.sort((a, b) => a - b)\n for(let i = 1; i < n; i++) {\n for(let j = i - 1; j >= 0; j--) {\n if(nums[i] % nums[j] === 0) {\n const tmp = dp[j] + 1\n if(tmp > dp[i]) dp[i] = tmp \n }\n }\n if(dp[i] > maxSize) maxSize = dp[i]\n }\n const res = []\n let pivot = 0\n for(let i = n - 1; i >= 0; i--) {\n if(dp[i] === maxSize && (pivot % nums[i] === 0)) {\n pivot = nums[i]\n maxSize--\n res.push(nums[i])\n }\n }\n \n return res\n};", "const largestDivisibleSubset = function(nums) {\n let len = nums.length;\n let maxSize = 0;\n let maxSizeLastIdx;\n // T[n] should be the length of the largest divisible subset whose smallest number is a[n]\n const T = new Array(len).fill(0);\n const son = new Array(len).fill(0);\n nums.sort((a, b) => a - b);\n for (let i = 0; i < len; i++) {\n for (let j = i; j >= 0; j--) {\n if (nums[i] % nums[j] === 0 && T[j] + 1 > T[i]) {\n T[i] = T[j] + 1;\n son[i] = j;\n }\n }\n if (T[i] > maxSize) {\n maxSize = T[i];\n maxSizeLastIdx = i;\n }\n }\n const re = [];\n for (let i = 0; i < maxSize; i++) {\n re.unshift(nums[maxSizeLastIdx]);\n maxSizeLastIdx = son[maxSizeLastIdx];\n }\n return re;\n};" ]
371
sum-of-two-integers
[]
/** * @param {number} a * @param {number} b * @return {number} */ var getSum = function(a, b) { };
Given two integers a and b, return the sum of the two integers without using the operators + and -.   Example 1: Input: a = 1, b = 2 Output: 3 Example 2: Input: a = 2, b = 3 Output: 5   Constraints: -1000 <= a, b <= 1000
Medium
[ "math", "bit-manipulation" ]
[ "const getSum = function(a, b) {\n return b === 0 ? a : getSum(a ^ b, (a & b) << 1);\n};" ]
372
super-pow
[]
/** * @param {number} a * @param {number[]} b * @return {number} */ var superPow = function(a, b) { };
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.   Example 1: Input: a = 2, b = [3] Output: 8 Example 2: Input: a = 2, b = [1,0] Output: 1024 Example 3: Input: a = 1, b = [4,3,3,8,5,2] Output: 1   Constraints: 1 <= a <= 231 - 1 1 <= b.length <= 2000 0 <= b[i] <= 9 b does not contain leading zeros.
Medium
[ "math", "divide-and-conquer" ]
[ "const superPow = function(a, b) {\n const base = 1337\n function powmod(a, k) {\n a %= base\n let res = 1\n for(let i = 0; i < k; i++) res = res * a % base\n return res\n }\n if(b.length === 0) return 1\n const last = b.pop()\n return powmod(superPow(a, b), 10) * powmod(a, last) % base\n}; " ]
373
find-k-pairs-with-smallest-sums
[]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @param {number} k * @return {number[][]} */ var kSmallestPairs = function(nums1, nums2, k) { };
You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k. Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.   Example 1: Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 Output: [[1,2],[1,4],[1,6]] Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] Example 2: Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 Output: [[1,1],[1,1]] Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] Example 3: Input: nums1 = [1,2], nums2 = [3], k = 3 Output: [[1,3],[2,3]] Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]   Constraints: 1 <= nums1.length, nums2.length <= 105 -109 <= nums1[i], nums2[i] <= 109 nums1 and nums2 both are sorted in non-decreasing order. 1 <= k <= 104
Medium
[ "array", "heap-priority-queue" ]
[ "const kSmallestPairs = function (nums1, nums2, k) {\n const pq = new PriorityQueue((a, b) => a[0] + a[1] < b[0] + b[1])\n for(let i = 0; i < nums1.length && i < k; i++) {\n pq.push([nums1[i], nums2[0], 0])\n }\n const res = []\n while(k > 0 && !pq.isEmpty()) {\n const [e1, e2, e2i] = pq.pop()\n res.push([e1, e2])\n if(e2i + 1 < nums2.length) pq.push([e1, nums2[e2i + 1], e2i + 1])\n k--\n }\n \n return res\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}", "const kSmallestPairs = function(nums1, nums2, k) {\n let len1 = nums1.length,\n len2 = nums2.length\n let arr = Array(len1).fill(0),\n resList = []\n while (k-- > 0) {\n let min = Infinity,\n index = -1,\n lastj = Infinity\n for (let i = 0; i < len1; i++) {\n const j = arr[i]\n if (j < lastj && j < len2) {\n const sum = nums1[i] + nums2[j]\n if (sum < min) {\n min = sum\n index = i\n }\n lastj = j\n }\n }\n if (index == -1) {\n break\n }\n resList.push([nums1[index], nums2[arr[index]]])\n arr[index]++\n }\n return resList\n}" ]
374
guess-number-higher-or-lower
[]
/** * Forward declaration of guess API. * @param {number} num your guess * @return -1 if num is higher than the picked number * 1 if num is lower than the picked number * otherwise return 0 * var guess = function(num) {} */ /** * @param {number} n * @return {number} */ var guessNumber = function(n) { };
We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num), which returns three possible results: -1: Your guess is higher than the number I picked (i.e. num > pick). 1: Your guess is lower than the number I picked (i.e. num < pick). 0: your guess is equal to the number I picked (i.e. num == pick). Return the number that I picked.   Example 1: Input: n = 10, pick = 6 Output: 6 Example 2: Input: n = 1, pick = 1 Output: 1 Example 3: Input: n = 2, pick = 1 Output: 1   Constraints: 1 <= n <= 231 - 1 1 <= pick <= n
Easy
[ "binary-search", "interactive" ]
null
[]
375
guess-number-higher-or-lower-ii
[ "The best strategy to play the game is to minimize the maximum loss you could possibly face. Another strategy is to minimize the expected loss. Here, we are interested in the <b>first</b> scenario.", "Take a small example (n = 3). What do you end up paying in the worst case?", "Check out <a href=\"https://en.wikipedia.org/wiki/Minimax\">this article</a> if you're still stuck.", "The purely recursive implementation of minimax would be worthless for even a small n. You MUST use dynamic programming.", "As a follow-up, how would you modify your code to solve the problem of minimizing the expected loss, instead of the worst-case loss?" ]
/** * @param {number} n * @return {number} */ var getMoneyAmount = function(n) { };
We are playing the Guessing Game. The game will work as follows: I pick a number between 1 and n. You guess a number. If you guess the right number, you win the game. If you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing. Every time you guess a wrong number x, you will pay x dollars. If you run out of money, you lose the game. Given a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick.   Example 1: Input: n = 10 Output: 16 Explanation: The winning strategy is as follows: - The range is [1,10]. Guess 7.   - If this is my number, your total is $0. Otherwise, you pay $7.   - If my number is higher, the range is [8,10]. Guess 9.   - If this is my number, your total is $7. Otherwise, you pay $9.   - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.   - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.   - If my number is lower, the range is [1,6]. Guess 3.   - If this is my number, your total is $7. Otherwise, you pay $3.   - If my number is higher, the range is [4,6]. Guess 5.   - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.   - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.   - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.   - If my number is lower, the range is [1,2]. Guess 1.   - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.   - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11. The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win. Example 2: Input: n = 1 Output: 0 Explanation: There is only one possible number, so you can guess 1 and not have to pay anything. Example 3: Input: n = 2 Output: 1 Explanation: There are two possible numbers, 1 and 2. - Guess 1.   - If this is my number, your total is $0. Otherwise, you pay $1.   - If my number is higher, it must be 2. Guess 2. Your total is $1. The worst case is that you pay $1.   Constraints: 1 <= n <= 200
Medium
[ "math", "dynamic-programming", "game-theory" ]
[ "const getMoneyAmount = function(n) {\n const dp = Array.from({length: n + 1}, () => new Array(n + 1).fill(0))\n return helper(dp, 1, n)\n};\n\nfunction helper(dp, s, e) {\n if(s >= e) return 0\n if(dp[s][e] !== 0) return dp[s][e]\n let res = Number.MAX_VALUE\n for(let i = s; i <= e; i++) {\n const tmp = i + Math.max(helper(dp, s, i - 1), helper(dp, i + 1, e))\n res = Math.min(res, tmp)\n }\n dp[s][e] = res\n return res\n}" ]
376
wiggle-subsequence
[]
/** * @param {number[]} nums * @return {number} */ var wiggleMaxLength = function(nums) { };
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative. In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero. A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array nums, return the length of the longest wiggle subsequence of nums.   Example 1: Input: nums = [1,7,4,9,2,5] Output: 6 Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). Example 2: Input: nums = [1,17,5,10,13,15,10,5,16,8] Output: 7 Explanation: There are several subsequences that achieve this length. One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8). Example 3: Input: nums = [1,2,3,4,5,6,7,8,9] Output: 2   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 1000   Follow up: Could you solve this in O(n) time?
Medium
[ "array", "dynamic-programming", "greedy" ]
[ "const wiggleMaxLength = function(nums) {\n if (nums.length < 2) return nums.length\n let prevdiff = nums[1] - nums[0]\n let count = prevdiff !== 0 ? 2 : 1\n for (let i = 2; i < nums.length; i++) {\n let diff = nums[i] - nums[i - 1]\n if ((diff > 0 && prevdiff <= 0) || (diff < 0 && prevdiff >= 0)) {\n count++\n prevdiff = diff\n }\n }\n return count\n}", "const wiggleMaxLength = function(nums) {\n const len = nums.length\n if (len === 0) return 0\n let up = 1\n let down = 1\n for (let i = 1; i < len; i++) {\n if (nums[i] > nums[i - 1]) {\n up = down + 1\n } else if (nums[i] < nums[i - 1]) {\n down = up + 1\n }\n }\n return Math.max(up, down)\n}" ]
377
combination-sum-iv
[]
/** * @param {number[]} nums * @param {number} target * @return {number} */ var combinationSum4 = function(nums, target) { };
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target. The test cases are generated so that the answer can fit in a 32-bit integer.   Example 1: Input: nums = [1,2,3], target = 4 Output: 7 Explanation: The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. Example 2: Input: nums = [9], target = 3 Output: 0   Constraints: 1 <= nums.length <= 200 1 <= nums[i] <= 1000 All the elements of nums are unique. 1 <= target <= 1000   Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
Medium
[ "array", "dynamic-programming" ]
[ "const combinationSum4 = function(nums, target) {\n const comb = [1];\n for (let i = 1; i <= target; i++) {\n comb[i] || (comb[i] = 0);\n for (let j = 0; j < nums.length; j++) {\n if (i >= nums[j]) {\n comb[i] += comb[i - nums[j]];\n }\n }\n }\n return comb[target];\n};" ]
378
kth-smallest-element-in-a-sorted-matrix
[]
/** * @param {number[][]} matrix * @param {number} k * @return {number} */ var kthSmallest = function(matrix, k) { };
Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. You must find a solution with a memory complexity better than O(n2).   Example 1: Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 Output: 13 Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13 Example 2: Input: matrix = [[-5]], k = 1 Output: -5   Constraints: n == matrix.length == matrix[i].length 1 <= n <= 300 -109 <= matrix[i][j] <= 109 All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order. 1 <= k <= n2   Follow up: Could you solve the problem with a constant memory (i.e., O(1) memory complexity)? Could you solve the problem in O(n) time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.
Medium
[ "array", "binary-search", "sorting", "heap-priority-queue", "matrix" ]
[ "const kthSmallest = function(matrix, k) {\n let lo = matrix[0][0],\n hi = matrix[matrix.length - 1][matrix[0].length - 1] + 1; //[lo, hi)\n while (lo < hi) {\n let mid = Math.floor(lo + (hi - lo) / 2);\n let count = 0,\n j = matrix[0].length - 1;\n for (let i = 0; i < matrix.length; i++) {\n while (j >= 0 && matrix[i][j] > mid) j--;\n count += j + 1;\n }\n if (count < k) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n};\n\nconsole.log(kthSmallest([[-5]], 1));\nconsole.log(kthSmallest([[1, 2], [1, 3]], 4));\nconsole.log(kthSmallest([[1, 5, 9], [10, 11, 13], [12, 13, 15]], 8));\nconsole.log(kthSmallest([[1, 2], [1, 3]], 2));" ]
380
insert-delete-getrandom-o1
[]
var RandomizedSet = function() { }; /** * @param {number} val * @return {boolean} */ RandomizedSet.prototype.insert = function(val) { }; /** * @param {number} val * @return {boolean} */ RandomizedSet.prototype.remove = function(val) { }; /** * @return {number} */ RandomizedSet.prototype.getRandom = function() { }; /** * Your RandomizedSet object will be instantiated and called as such: * var obj = new RandomizedSet() * var param_1 = obj.insert(val) * var param_2 = obj.remove(val) * var param_3 = obj.getRandom() */
Implement the RandomizedSet class: RandomizedSet() Initializes the RandomizedSet object. bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise. int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned. You must implement the functions of the class such that each function works in average O(1) time complexity.   Example 1: Input ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] [[], [1], [2], [2], [], [1], [2], []] Output [null, true, false, true, 2, true, false, 2] Explanation RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.   Constraints: -231 <= val <= 231 - 1 At most 2 * 105 calls will be made to insert, remove, and getRandom. There will be at least one element in the data structure when getRandom is called.
Medium
[ "array", "hash-table", "math", "design", "randomized" ]
[ "const RandomizedSet = function () {\n this.arr = []\n this.map = new Map()\n}\n\n\nRandomizedSet.prototype.insert = function (val) {\n const {arr, map} = this\n if(map.has(val)) return false\n const size = arr.length\n arr.push(val)\n map.set(val, size)\n return true\n}\n\n\nRandomizedSet.prototype.remove = function (val) {\n const {arr, map} = this\n if(!map.has(val)) return false\n const idx = map.get(val), last = arr[arr.length - 1]\n arr[idx] = last\n map.set(last, idx)\n arr.pop()\n map.delete(val)\n return true\n}\n\n\nRandomizedSet.prototype.getRandom = function () {\n return this.arr[~~(this.arr.length * Math.random())]\n}" ]
381
insert-delete-getrandom-o1-duplicates-allowed
[]
var RandomizedCollection = function() { }; /** * @param {number} val * @return {boolean} */ RandomizedCollection.prototype.insert = function(val) { }; /** * @param {number} val * @return {boolean} */ RandomizedCollection.prototype.remove = function(val) { }; /** * @return {number} */ RandomizedCollection.prototype.getRandom = function() { }; /** * Your RandomizedCollection object will be instantiated and called as such: * var obj = new RandomizedCollection() * var param_1 = obj.insert(val) * var param_2 = obj.remove(val) * var param_3 = obj.getRandom() */
RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element. Implement the RandomizedCollection class: RandomizedCollection() Initializes the empty RandomizedCollection object. bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise. bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them. int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of the same values the multiset contains. You must implement the functions of the class such that each function works on average O(1) time complexity. Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection.   Example 1: Input ["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] [[], [1], [1], [2], [], [1], []] Output [null, true, false, true, 2, true, 1] Explanation RandomizedCollection randomizedCollection = new RandomizedCollection(); randomizedCollection.insert(1); // return true since the collection does not contain 1. // Inserts 1 into the collection. randomizedCollection.insert(1); // return false since the collection contains 1. // Inserts another 1 into the collection. Collection now contains [1,1]. randomizedCollection.insert(2); // return true since the collection does not contain 2. // Inserts 2 into the collection. Collection now contains [1,1,2]. randomizedCollection.getRandom(); // getRandom should: // - return 1 with probability 2/3, or // - return 2 with probability 1/3. randomizedCollection.remove(1); // return true since the collection contains 1. // Removes 1 from the collection. Collection now contains [1,2]. randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.   Constraints: -231 <= val <= 231 - 1 At most 2 * 105 calls in total will be made to insert, remove, and getRandom. There will be at least one element in the data structure when getRandom is called.
Hard
[ "array", "hash-table", "math", "design", "randomized" ]
[ "const RandomizedCollection = function() {\n this.map = new Map()\n this.list = []\n}\n\n\nRandomizedCollection.prototype.insert = function(val) {\n const index = this.list.length\n const node = { val, index }\n this.list[index] = node\n\n const nodeList = this.map.get(val)\n const isNew = nodeList === undefined || nodeList.length === 0\n if (nodeList === undefined) {\n this.map.set(val, [node])\n } else {\n nodeList.push(node)\n }\n return isNew\n}\n\n\nRandomizedCollection.prototype.remove = function(val) {\n const nodeList = this.map.get(val)\n if (!nodeList || nodeList.length === 0) return false\n const node = nodeList.pop()\n const replacement = this.list.pop()\n if (replacement.index !== node.index) {\n replacement.index = node.index\n this.list[replacement.index] = replacement\n }\n return true\n}\n\n\nRandomizedCollection.prototype.getRandom = function() {\n const index = Math.floor(Math.random() * this.list.length)\n return this.list[index].val\n}" ]
382
linked-list-random-node
[]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head */ var Solution = function(head) { }; /** * @return {number} */ Solution.prototype.getRandom = function() { }; /** * Your Solution object will be instantiated and called as such: * var obj = new Solution(head) * var param_1 = obj.getRandom() */
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Implement the Solution class: Solution(ListNode head) Initializes the object with the head of the singly-linked list head. int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.   Example 1: Input ["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"] [[[1, 2, 3]], [], [], [], [], []] Output [null, 1, 3, 2, 2, 3] Explanation Solution solution = new Solution([1, 2, 3]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.   Constraints: The number of nodes in the linked list will be in the range [1, 104]. -104 <= Node.val <= 104 At most 104 calls will be made to getRandom.   Follow up: What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?
Medium
[ "linked-list", "math", "reservoir-sampling", "randomized" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "const Solution = function(head) {\n this.list = head;\n this.arr = [];\n loop(head, this.arr);\n};\n\n\nSolution.prototype.getRandom = function() {\n const len = this.arr.length;\n return this.arr[Math.floor(Math.random() * len)].val;\n};\n\n\nfunction loop(node, arr) {\n if (node == null) return;\n arr.push(node);\n loop(node.next, arr);\n}" ]
383
ransom-note
[]
/** * @param {string} ransomNote * @param {string} magazine * @return {boolean} */ var canConstruct = function(ransomNote, magazine) { };
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote.   Example 1: Input: ransomNote = "a", magazine = "b" Output: false Example 2: Input: ransomNote = "aa", magazine = "ab" Output: false Example 3: Input: ransomNote = "aa", magazine = "aab" Output: true   Constraints: 1 <= ransomNote.length, magazine.length <= 105 ransomNote and magazine consist of lowercase English letters.
Easy
[ "hash-table", "string", "counting" ]
[ "const canConstruct = function(ransomNote, magazine) {\n const m = new Map()\n for(let c of magazine) {\n m.set(c, (m.get(c) || 0) + 1 )\n }\n for(let c of ransomNote) {\n if(!m.has(c) || m.get(c) <= 0) return false\n m.set(c, m.get(c) - 1)\n }\n return true\n};" ]
384
shuffle-an-array
[ "The solution expects that we always use the original array to shuffle() else some of the test cases fail. (Credits; @snehasingh31)" ]
/** * @param {number[]} nums */ var Solution = function(nums) { }; /** * @return {number[]} */ Solution.prototype.reset = function() { }; /** * @return {number[]} */ Solution.prototype.shuffle = function() { }; /** * Your Solution object will be instantiated and called as such: * var obj = new Solution(nums) * var param_1 = obj.reset() * var param_2 = obj.shuffle() */
Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. Implement the Solution class: Solution(int[] nums) Initializes the object with the integer array nums. int[] reset() Resets the array to its original configuration and returns it. int[] shuffle() Returns a random shuffling of the array.   Example 1: Input ["Solution", "shuffle", "reset", "shuffle"] [[[1, 2, 3]], [], [], []] Output [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] Explanation Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // Shuffle the array [1,2,3] and return its result. // Any permutation of [1,2,3] must be equally likely to be returned. // Example: return [3, 1, 2] solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]   Constraints: 1 <= nums.length <= 50 -106 <= nums[i] <= 106 All the elements of nums are unique. At most 104 calls in total will be made to reset and shuffle.
Medium
[ "array", "math", "randomized" ]
[ "const Solution = function(nums) {\n this.original = nums;\n};\n\nSolution.prototype.reset = function() {\n return this.original;\n};\n\n\nSolution.prototype.shuffle = function() {\n const res = [];\n const len = this.original.length;\n let idx = 0;\n let i = 0;\n while (idx <= len - 1) {\n i = Math.floor(Math.random() * len);\n if (res[i] == null) {\n res[i] = this.original[idx];\n idx += 1;\n }\n }\n return res;\n};" ]
385
mini-parser
[]
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * function NestedInteger() { * * Return true if this NestedInteger holds a single integer, rather than a nested list. * @return {boolean} * this.isInteger = function() { * ... * }; * * Return the single integer that this NestedInteger holds, if it holds a single integer * Return null if this NestedInteger holds a nested list * @return {integer} * this.getInteger = function() { * ... * }; * * Set this NestedInteger to hold a single integer equal to value. * @return {void} * this.setInteger = function(value) { * ... * }; * * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. * @return {void} * this.add = function(elem) { * ... * }; * * Return the nested list that this NestedInteger holds, if it holds a nested list * Return null if this NestedInteger holds a single integer * @return {NestedInteger[]} * this.getList = function() { * ... * }; * }; */ /** * @param {string} s * @return {NestedInteger} */ var deserialize = function(s) { };
Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger. Each element is either an integer or a list whose elements may also be integers or other lists.   Example 1: Input: s = "324" Output: 324 Explanation: You should return a NestedInteger object which contains a single integer 324. Example 2: Input: s = "[123,[456,[789]]]" Output: [123,[456,[789]]] Explanation: Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789   Constraints: 1 <= s.length <= 5 * 104 s consists of digits, square brackets "[]", negative sign '-', and commas ','. s is the serialization of valid NestedInteger. All the values in the input are in the range [-106, 106].
Medium
[ "string", "stack", "depth-first-search" ]
[ "const deserialize = function(s) {\n const recursion = s => {\n const re = new NestedInteger()\n if (!s || s.length === 0) {\n return re\n }\n if (s.charAt(0) !== '[') {\n re.setInteger(parseInt(s, 10))\n } else if (s.length > 2) {\n let start = 1\n let cnt = 0\n for (let i = 1; i < s.length; i++) {\n const char = s.charAt(i)\n if (cnt === 0 && (char === ',' || i === s.length - 1)) {\n re.add(recursion(s.substring(start, i)))\n start = i + 1\n } else if (char === '[') {\n cnt++\n } else if (char === ']') {\n cnt--\n }\n }\n }\n return re\n }\n return recursion(s)\n}" ]
386
lexicographical-numbers
[]
/** * @param {number} n * @return {number[]} */ var lexicalOrder = function(n) { };
Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order. You must write an algorithm that runs in O(n) time and uses O(1) extra space.    Example 1: Input: n = 13 Output: [1,10,11,12,13,2,3,4,5,6,7,8,9] Example 2: Input: n = 2 Output: [1,2]   Constraints: 1 <= n <= 5 * 104
Medium
[ "depth-first-search", "trie" ]
[ "const lexicalOrder = function(n) {\n const res = []\n for(let i = 1; i < 10; i++) {\n dfs(i)\n }\n \n return res\n \n function dfs(num) {\n if(num > n) return\n res.push(num)\n for(let i = 0; i < 10; i++) {\n const tmp = num * 10 + i\n if(tmp > n) return\n dfs(tmp)\n }\n }\n};", "const lexicalOrder = function(n) {\n const result = []\n for (let i = 1; i < 10; i++) {\n dfs(i)\n }\n function dfs(n) {\n if (n <= num) result.push(n)\n if (10 * n <= num) {\n for (let j = 0; j < 10; j++) {\n dfs(10 * n + j)\n }\n }\n }\n return result\n}", "const lexicalOrder = function(n) {\n function getNumberByOrder(start, end) {\n for (let i = start; i <= end; i++) {\n if (i > n) {\n break\n }\n res.push(i)\n getNumberByOrder(i * 10, i * 10 + 9)\n }\n }\n const res = []\n getNumberByOrder(1, 9)\n return res\n}" ]
387
first-unique-character-in-a-string
[]
/** * @param {string} s * @return {number} */ var firstUniqChar = function(s) { };
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.   Example 1: Input: s = "leetcode" Output: 0 Example 2: Input: s = "loveleetcode" Output: 2 Example 3: Input: s = "aabb" Output: -1   Constraints: 1 <= s.length <= 105 s consists of only lowercase English letters.
Easy
[ "hash-table", "string", "queue", "counting" ]
[ "const firstUniqChar = function(s) {\n const arr = [];\n const res = [];\n const hash = {};\n let tmp;\n let idx;\n for (let i = 0; i < s.length; i++) {\n tmp = s.charAt(i);\n if (hash.hasOwnProperty(tmp)) {\n idx = arr.indexOf(tmp);\n if (idx >= 0) {\n arr.splice(idx, 1);\n res.splice(idx, 1);\n }\n\n hash[tmp] += 1;\n } else {\n arr.push(tmp);\n res.push(i);\n hash[tmp] = 1;\n }\n }\n return res[0] == null ? -1 : res[0];\n};", "const firstUniqChar = function(s) {\n if(s === '') return -1\n const map = new Map()\n for(let i = 0, len = s.length; i < len; i++) {\n if(!map.has(s[i])) map.set(s[i], [i, 0])\n map.get(s[i])[1] += 1\n }\n for(let [key, val] of map) {\n if(val[1] === 1) return val[0]\n }\n return -1\n \n};" ]