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
101
symmetric-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 {boolean} */ var isSymmetric = function(root) { };
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).   Example 1: Input: root = [1,2,2,3,4,4,3] Output: true Example 2: Input: root = [1,2,2,null,3,null,3] Output: false   Constraints: The number of nodes in the tree is in the range [1, 1000]. -100 <= Node.val <= 100   Follow up: Could you solve it both recursively and iteratively?
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 isSymmetric = function(root) {\n if(root == null) return true\n return compare(root.left, root.right)\n};\n\nfunction compare(l, r) {\n if(l == null && r == null) return true\n if( (l == null && r != null) || (l != null && r == null) ) return false\n \n if(l.val === r.val) {\n if(compare(l.left, r.right) !== false && compare(l.right, r.left) !== false) {\n return true\n } else {\n return false\n }\n \n } else {\n return false\n }\n}" ]
102
binary-tree-level-order-traversal
[]
/** * 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 levelOrder = function(root) { };
Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).   Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: []   Constraints: The number of nodes in the tree is in the range [0, 2000]. -1000 <= Node.val <= 1000
Medium
[ "tree", "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 levelOrder = function(root) {\n const res = [];\n if (root == null) return res;\n let next = [root];\n while (next.length > 0) {\n next = tr(res, next);\n }\n return res;\n};\n\nfunction tr(res, nodeArr) {\n const arr = [];\n const nextLevelNodes = [];\n for (let i = 0; i < nodeArr.length; i++) {\n arr.push(nodeArr[i].val);\n if (nodeArr[i].left) {\n nextLevelNodes.push(nodeArr[i].left);\n }\n if (nodeArr[i].right) {\n nextLevelNodes.push(nodeArr[i].right);\n }\n }\n if (arr.length) res.push(arr);\n return nextLevelNodes;\n}" ]
103
binary-tree-zigzag-level-order-traversal
[]
/** * 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 zigzagLevelOrder = function(root) { };
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).   Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[3],[20,9],[15,7]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: []   Constraints: The number of nodes in the tree is in the range [0, 2000]. -100 <= Node.val <= 100
Medium
[ "tree", "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 zigzagLevelOrder = function(root) {\n if(root == null) return []\n const row = [root]\n const res = []\n bfs(row, res)\n for(let i = 0; i < res.length; i++) {\n res[i] = i % 2 === 0 ? res[i] : res[i].reverse()\n }\n return res\n};\n\nfunction bfs(row, res) {\n if(row.length === 0) return\n let tmp = []\n let next = []\n for(let i = 0; i< row.length; i++) {\n tmp.push(row[i].val)\n if(row[i].left) {\n next.push(row[i].left)\n }\n if(row[i].right) {\n next.push(row[i].right)\n }\n }\n if(tmp.length) {\n res.push(tmp)\n }\n bfs(next, res)\n}", "const zigzagLevelOrder = function (root) {\n if (!root) return [];\n const queue = [root];\n const zigzag = [];\n let numLevels = 1;\n while (queue.length > 0) {\n const width = queue.length;\n const levelTraversal = [];\n for (let i = 0; i < width; i++) {\n const currentNode = queue.shift();\n if (currentNode.right) queue.push(currentNode.right);\n if (currentNode.left) queue.push(currentNode.left);\n numLevels % 2 === 0\n ? levelTraversal.push(currentNode.val)\n : levelTraversal.unshift(currentNode.val);\n }\n zigzag.push(levelTraversal);\n numLevels++;\n }\n\n return zigzag;\n};", "const zigzagLevelOrder = function (root) {\n const res = []\n dfs(root, res, 0)\n return res\n \n function dfs(node, res, level) {\n if(node == null) return\n if(res.length <= level) res.push([])\n const tmp = res[level]\n if(level % 2 === 0) tmp.push(node.val)\n else tmp.unshift(node.val)\n \n dfs(node.left, res, level + 1)\n dfs(node.right, res, level + 1)\n }\n};" ]
104
maximum-depth-of-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 {number} */ var maxDepth = function(root) { };
Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.   Example 1: Input: root = [3,9,20,null,null,15,7] Output: 3 Example 2: Input: root = [1,null,2] Output: 2   Constraints: The number of nodes in the tree is in the range [0, 104]. -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 maxDepth = function(root) {\n if (!root) return 0;\n const left = maxDepth(root.left);\n const right = maxDepth(root.right);\n let depth = left > right ? left : right;\n return (depth += 1);\n};" ]
105
construct-binary-tree-from-preorder-and-inorder-traversal
[]
/** * 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 {number[]} preorder * @param {number[]} inorder * @return {TreeNode} */ var buildTree = function(preorder, inorder) { };
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.   Example 1: Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] Output: [3,9,20,null,null,15,7] Example 2: Input: preorder = [-1], inorder = [-1] Output: [-1]   Constraints: 1 <= preorder.length <= 3000 inorder.length == preorder.length -3000 <= preorder[i], inorder[i] <= 3000 preorder and inorder consist of unique values. Each value of inorder also appears in preorder. preorder is guaranteed to be the preorder traversal of the tree. inorder is guaranteed to be the inorder traversal of the tree.
Medium
[ "array", "hash-table", "divide-and-conquer", "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 buildTree = function(preorder, inorder) {\n if(preorder.length === 0 && inorder.length === 0) return null\n const val = preorder[0]\n const node = new TreeNode(val)\n const inIdx = inorder.indexOf(val)\n const leftIn = inorder.slice(0, inIdx)\n const rightIn = inorder.slice(inIdx + 1)\n \n const leftPre = preorder.slice(1, leftIn.length + 1)\n const rightPre = preorder.slice(leftIn.length + 1)\n \n // console.log(leftIn, rightIn, leftPre, rightPre)\n node.left = buildTree(leftPre, leftIn)\n node.right = buildTree(rightPre, rightIn)\n return node\n};", "let pre\nlet ins\nlet inmap = {}\nconst buildTree = function(preorder, inorder) {\n pre = preorder\n ins = inorder\n for(let i = 0; i < inorder.length; i++) {\n inmap[inorder[i]] = i\n }\n let root = helper(0,0,ins.length - 1)\n return root\n};\n\nfunction helper(preStart, inStart, inEnd) {\n if (preStart > pre.length -1 || inStart > inEnd) {\n return null\n }\n let val = pre[preStart]\n let root = new TreeNode(val)\n let inIndex = inmap[val]\n root.left = helper(preStart + 1, inStart, inIndex - 1)\n root.right = helper(preStart+inIndex-inStart+1, inIndex+1, inEnd)\n return root\n}" ]
106
construct-binary-tree-from-inorder-and-postorder-traversal
[]
/** * 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 {number[]} inorder * @param {number[]} postorder * @return {TreeNode} */ var buildTree = function(inorder, postorder) { };
Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.   Example 1: Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] Output: [3,9,20,null,null,15,7] Example 2: Input: inorder = [-1], postorder = [-1] Output: [-1]   Constraints: 1 <= inorder.length <= 3000 postorder.length == inorder.length -3000 <= inorder[i], postorder[i] <= 3000 inorder and postorder consist of unique values. Each value of postorder also appears in inorder. inorder is guaranteed to be the inorder traversal of the tree. postorder is guaranteed to be the postorder traversal of the tree.
Medium
[ "array", "hash-table", "divide-and-conquer", "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 buildTree = function(inorder, postorder) {\n const inmap = {};\n const posts = postorder;\n for (let i = 0; i < inorder.length; i++) {\n inmap[inorder[i]] = i;\n }\n return helper(postorder.length - 1, 0, inorder.length - 1);\n\n function helper(postEnd, inStart, inEnd) {\n if (postEnd < 0 || inEnd < inStart) return null;\n const val = posts[postEnd];\n const idx = inmap[\"\" + val];\n const root = new TreeNode(val);\n root.left = helper(postEnd - (inEnd - idx) - 1, inStart, idx - 1);\n root.right = helper(postEnd - 1, idx + 1, inEnd);\n\n return root;\n }\n};", "const buildTree = function (inorder, postorder) {\n let pInorder = inorder.length - 1\n let pPostorder = postorder.length - 1\n return helper(inorder, postorder, null)\n function helper(inorder, postorder, end) {\n if (pPostorder < 0) return null\n // create root node\n const n = new TreeNode(postorder[pPostorder--])\n // if right node exist, create right subtree\n if (inorder[pInorder] != n.val) {\n n.right = helper(inorder, postorder, n)\n }\n pInorder--\n // if left node exist, create left subtree\n if (end === null || inorder[pInorder] !== end.val) {\n n.left = helper(inorder, postorder, end)\n }\n return n\n }\n}" ]
107
binary-tree-level-order-traversal-ii
[]
/** * 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 levelOrderBottom = function(root) { };
Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).   Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[15,7],[9,20],[3]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: []   Constraints: The number of nodes in the tree is in the range [0, 2000]. -1000 <= Node.val <= 1000
Medium
[ "tree", "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 levelOrderBottom = function(root) {\n const levels = []\n postOrderTraversal(root)\n return levels.reverse()\n\n function postOrderTraversal(node, level = 0) {\n if (node) {\n if (!levels[level]) levels.push([])\n postOrderTraversal(node.left, level + 1)\n postOrderTraversal(node.right, level + 1)\n levels[level].push(node.val)\n }\n }\n}", "const levelOrderBottom = function(root) {\n if (!root) return []\n const currentLevelNodes = [root]\n const result = []\n while (currentLevelNodes.length > 0) {\n const count = currentLevelNodes.length\n const currentLevelValues = []\n for (let i = 0; i < count; i++) {\n const node = currentLevelNodes.shift()\n currentLevelValues.push(node.val)\n if (node.left) currentLevelNodes.push(node.left)\n if (node.right) currentLevelNodes.push(node.right)\n }\n result.unshift(currentLevelValues)\n }\n return result\n}" ]
108
convert-sorted-array-to-binary-search-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 {number[]} nums * @return {TreeNode} */ var sortedArrayToBST = function(nums) { };
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.   Example 1: Input: nums = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: [0,-10,5,null,-3,null,9] is also accepted: Example 2: Input: nums = [1,3] Output: [3,1] Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.   Constraints: 1 <= nums.length <= 104 -104 <= nums[i] <= 104 nums is sorted in a strictly increasing order.
Easy
[ "array", "divide-and-conquer", "tree", "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 sortedArrayToBST = function(nums) {\n if (nums.length == 0) {\n return null;\n }\n const head = helper(nums, 0, nums.length - 1);\n return head;\n};\n\nfunction helper(num, low, high) {\n if (low > high) {\n // Done\n return null;\n }\n let mid = Math.floor((low + high) / 2);\n let node = new TreeNode(num[mid]);\n node.left = helper(num, low, mid - 1);\n node.right = helper(num, mid + 1, high);\n return node;\n}" ]
109
convert-sorted-list-to-binary-search-tree
[]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * 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 {ListNode} head * @return {TreeNode} */ var sortedListToBST = function(head) { };
Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.   Example 1: Input: head = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. Example 2: Input: head = [] Output: []   Constraints: The number of nodes in head is in the range [0, 2 * 104]. -105 <= Node.val <= 105
Medium
[ "linked-list", "divide-and-conquer", "tree", "binary-search-tree", "binary-tree" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "const sortedListToBST = function(head) {\n if(head == null) return null\n const arr = []\n let cur = head\n while(cur !== null) {\n arr.push(cur)\n cur = cur.next\n }\n return build(arr, null, '')\n};\n\nfunction build(arr, parent, type) {\n if(arr.length === 0) return\n let mid = Math.floor(arr.length / 2)\n let left = arr.slice(0, mid)\n let right = arr.slice(mid + 1)\n const node = new TreeNode(arr[mid].val)\n if(parent) parent[type] = node\n build(left, node, 'left')\n build(right, node, 'right')\n return node\n}", "const sortedListToBST = function(head, tail = null) {\n if (head === tail) {\n return null;\n } else if (head.next === tail) {\n return new TreeNode(head.val);\n } else {\n let slow = head; \n let fast = head;\n while (fast !== tail && fast.next !== tail) {\n slow = slow.next;\n fast = fast.next.next;\n }\n let node = new TreeNode(slow.val);\n node.left = sortedListToBST(head, slow);\n node.right = sortedListToBST(slow.next, tail);\n return node;\n }\n};" ]
110
balanced-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 {boolean} */ var isBalanced = function(root) { };
Given a binary tree, determine if it is height-balanced.   Example 1: Input: root = [3,9,20,null,null,15,7] Output: true Example 2: Input: root = [1,2,2,3,3,null,null,4,4] Output: false Example 3: Input: root = [] Output: true   Constraints: The number of nodes in the tree is in the range [0, 5000]. -104 <= Node.val <= 104
Easy
[ "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 isBalanced = function(root) {\n return check(root) >= 0 ? true : false\n};\n\nconst check = (root) => {\n if(!root) return 1\n \n const left = check(root.left)\n if( left === -1 ) return -1\n \n const right = check(root.right)\n if( right === -1 ) return -1\n \n if(Math.abs(left - right) > 1)return -1\n \n return (1 + Math.max(left, right))\n}" ]
111
minimum-depth-of-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 {number} */ var minDepth = function(root) { };
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children.   Example 1: Input: root = [3,9,20,null,null,15,7] Output: 2 Example 2: Input: root = [2,null,3,null,4,null,5,null,6] Output: 5   Constraints: The number of nodes in the tree is in the range [0, 105]. -1000 <= Node.val <= 1000
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 minDepth = function(root) {\n if(root == null) return 0\n if(root.left === null && root.right === null) return 1\n const res = {\n min:Number.MAX_VALUE\n }\n dfs(root, res, 1)\n return res.min\n};\n\nfunction dfs(node, res, cur) {\n if(node == null) return\n if(node !== null && node.left === null && node.right === null) {\n if(cur < res.min) {\n res.min = cur \n }\n return\n }\n dfs(node.left, res, cur + 1)\n dfs(node.right, res, cur + 1)\n \n} " ]
112
path-sum
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} targetSum * @return {boolean} */ var hasPathSum = function(root, targetSum) { };
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children.   Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: The root-to-leaf path with the target sum is shown. Example 2: Input: root = [1,2,3], targetSum = 5 Output: false Explanation: There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5. Example 3: Input: root = [], targetSum = 0 Output: false Explanation: Since the tree is empty, there are no root-to-leaf paths.   Constraints: The number of nodes in the tree is in the range [0, 5000]. -1000 <= Node.val <= 1000 -1000 <= targetSum <= 1000
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 hasPathSum = function(root, sum) {\n if (root == null) {\n return false\n }\n const obj = {\n sum: 0\n }\n const res = []\n dfs(root, obj, sum, res)\n return res.indexOf(true) !== -1\n};\n\nfunction dfs(node, obj, target, res) {\n\n if (node.left == null && node.right == null) {\n obj.sum += node.val\n if (obj.sum === target) {\n res.push(true)\n }\n }\n if (node.left) {\n dfs(node.left, {sum: obj.sum + node.val}, target, res)\n }\n if (node.right) {\n dfs(node.right, {sum: obj.sum + node.val}, target, res)\n }\n}" ]
113
path-sum-ii
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} targetSum * @return {number[][]} */ var pathSum = function(root, targetSum) { };
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references. A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.   Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: [[5,4,11,2],[5,8,4,5]] Explanation: There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 Example 2: Input: root = [1,2,3], targetSum = 5 Output: [] Example 3: Input: root = [1,2], targetSum = 0 Output: []   Constraints: The number of nodes in the tree is in the range [0, 5000]. -1000 <= Node.val <= 1000 -1000 <= targetSum <= 1000
Medium
[ "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 pathSum = function(root, sum) {\n const result = [];\n backtrack(root, sum, [], result);\n return result;\n};\n\nconst backtrack = function(root, sum, temp, result) {\n if (root == null) {\n return;\n }\n temp.push(root.val);\n let newSum = sum - root.val;\n if (root.left == null && root.right == null) {\n if (newSum === 0) {\n result.push([...temp]);\n }\n temp.pop();\n return;\n }\n backtrack(root.left, newSum, temp, result);\n backtrack(root.right, newSum, temp, result);\n temp.pop();\n}" ]
114
flatten-binary-tree-to-linked-list
[ "If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal." ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {void} Do not return anything, modify root in-place instead. */ var flatten = function(root) { };
Given the root of a binary tree, flatten the tree into a "linked list": The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The "linked list" should be in the same order as a pre-order traversal of the binary tree.   Example 1: Input: root = [1,2,5,3,4,null,6] Output: [1,null,2,null,3,null,4,null,5,null,6] Example 2: Input: root = [] Output: [] Example 3: Input: root = [0] Output: [0]   Constraints: The number of nodes in the tree is in the range [0, 2000]. -100 <= Node.val <= 100   Follow up: Can you flatten the tree in-place (with O(1) extra space)?
Medium
[ "linked-list", "stack", "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 flatten = function(root) {\n let prev = null\n function op(root) {\n if (root == null) return;\n op(root.right);\n op(root.left);\n root.right = prev;\n root.left = null;\n prev = root;\n }\n op(root)\n};" ]
115
distinct-subsequences
[]
/** * @param {string} s * @param {string} t * @return {number} */ var numDistinct = function(s, t) { };
Given two strings s and t, return the number of distinct subsequences of s which equals t modulo 109 + 7.   Example 1: Input: s = "rabbbit", t = "rabbit" Output: 3 Explanation: As shown below, there are 3 ways you can generate "rabbit" from s. rabbbit rabbbit rabbbit Example 2: Input: s = "babgbag", t = "bag" Output: 5 Explanation: As shown below, there are 5 ways you can generate "bag" from s. babgbag babgbag babgbag babgbag babgbag   Constraints: 1 <= s.length, t.length <= 1000 s and t consist of English letters.
Hard
[ "string", "dynamic-programming" ]
[ "const numDistinct = function(s, t) {\n const tlen = t.length\n const slen = s.length\n const mem = Array.from({ length: tlen + 1 }, () =>\n new Array(slen + 1).fill(0)\n )\n for (let j = 0; j <= slen; j++) {\n mem[0][j] = 1\n }\n for (let i = 0; i < tlen; i++) {\n for (let j = 0; j < slen; j++) {\n if (t.charAt(i) === s.charAt(j)) {\n mem[i + 1][j + 1] = mem[i][j] + mem[i + 1][j]\n } else {\n mem[i + 1][j + 1] = mem[i + 1][j]\n }\n }\n }\n return mem[tlen][slen]\n}", "const numDistinct = function(s, t) {\n const m = t.length,\n n = s.length\n const cur = new Array(m + 1).fill(0)\n cur[0] = 1\n for (let j = 1; j <= n; j++) {\n let pre = 1\n for (let i = 1; i <= m; i++) {\n let temp = cur[i]\n cur[i] = cur[i] + (t[i - 1] == s[j - 1] ? pre : 0)\n pre = temp\n }\n }\n return cur[m]\n}", "const numDistinct = function(s, t) {\n const m = t.length,\n n = s.length\n const dp = new Array(m + 1).fill(0)\n dp[0] = 1\n for (let j = 1; j <= n; j++) {\n for (let i = m; i > 0; i--) {\n dp[i] = dp[i] + (t[i - 1] == s[j - 1] ? dp[i - 1] : 0)\n }\n }\n return dp[m]\n}" ]
116
populating-next-right-pointers-in-each-node
[]
/** * // Definition for a Node. * function Node(val, left, right, next) { * this.val = val === undefined ? null : val; * this.left = left === undefined ? null : left; * this.right = right === undefined ? null : right; * this.next = next === undefined ? null : next; * }; */ /** * @param {Node} root * @return {Node} */ var connect = function(root) { };
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.   Example 1: Input: root = [1,2,3,4,5,6,7] Output: [1,#,2,3,#,4,5,6,7,#] Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. Example 2: Input: root = [] Output: []   Constraints: The number of nodes in the tree is in the range [0, 212 - 1]. -1000 <= Node.val <= 1000   Follow-up: You may only use constant extra space. The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
Medium
[ "linked-list", "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * // Definition for a Node. * function Node(val, left, right, next) { * this.val = val === undefined ? null : val; * this.left = left === undefined ? null : left; * this.right = right === undefined ? null : right; * this.next = next === undefined ? null : next; * }; */
[ "const connect = function(root) {\n if (root == null) return null\n const cur = [root]\n while (cur.length) {\n let len = cur.length\n for (let i = 0; i < len; i++) {\n let el = cur.shift()\n if (i === len - 1) el.next = null\n else el.next = cur[0]\n\n if (el.left) cur.push(el.left)\n if (el.right) cur.push(el.right)\n }\n }\n return root\n}", "const connect = function(root) {\n if (!root) return null\n if (root.left && root.right) {\n root.left.next = root.right\n root.right.next = root.next ? root.next.left : null\n }\n connect(root.left)\n connect(root.right)\n return root\n}" ]
117
populating-next-right-pointers-in-each-node-ii
[]
/** * // Definition for a Node. * function Node(val, left, right, next) { * this.val = val === undefined ? null : val; * this.left = left === undefined ? null : left; * this.right = right === undefined ? null : right; * this.next = next === undefined ? null : next; * }; */ /** * @param {Node} root * @return {Node} */ var connect = function(root) { };
Given a binary tree struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.   Example 1: Input: root = [1,2,3,4,5,null,7] Output: [1,#,2,3,#,4,5,7,#] Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. Example 2: Input: root = [] Output: []   Constraints: The number of nodes in the tree is in the range [0, 6000]. -100 <= Node.val <= 100   Follow-up: You may only use constant extra space. The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
Medium
[ "linked-list", "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * // Definition for a Node. * function Node(val, left, right, next) { * this.val = val === undefined ? null : val; * this.left = left === undefined ? null : left; * this.right = right === undefined ? null : right; * this.next = next === undefined ? null : next; * }; */
[ "const connect = function(root) {\n if (root == null) return null\n const cur = [root]\n while (cur.length) {\n const len = cur.length\n for (let i = 0; i < len; i++) {\n const el = cur.shift()\n if (i === len - 1) el.next = null\n else el.next = cur[0]\n if (el.left) cur.push(el.left)\n if (el.right) cur.push(el.right)\n }\n }\n return root\n}" ]
118
pascals-triangle
[]
/** * @param {number} numRows * @return {number[][]} */ var generate = function(numRows) { };
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:   Example 1: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] Example 2: Input: numRows = 1 Output: [[1]]   Constraints: 1 <= numRows <= 30
Easy
[ "array", "dynamic-programming" ]
[ "const generate = function(numRows) {\n // row 0 => [1] length 0\n // row 1 => [1, 1] length 1\n // row 2 => [1, 2, 1] length 2\n // row 3 => [1, 3, 3, 1] length 3\n\n // current[i] = prev[i - 1] + prev[i]\n\n const res = [];\n for (let row = 0; row < numRows; row += 1) {\n if (row === 0) {\n res.push([1]);\n continue;\n }\n\n if (row === 1) {\n res.push([1, 1]);\n continue;\n }\n\n const newRow = [];\n const maxIdx = row;\n for (let i = 0; i <= maxIdx; i += 1) {\n if (i === 0 || i === maxIdx) {\n newRow.push(1);\n } else {\n newRow.push(res[row - 1][i - 1] + res[row - 1][i]);\n }\n }\n res.push(newRow);\n }\n\n return res;\n};" ]
119
pascals-triangle-ii
[]
/** * @param {number} rowIndex * @return {number[]} */ var getRow = function(rowIndex) { };
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:   Example 1: Input: rowIndex = 3 Output: [1,3,3,1] Example 2: Input: rowIndex = 0 Output: [1] Example 3: Input: rowIndex = 1 Output: [1,1]   Constraints: 0 <= rowIndex <= 33   Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?
Easy
[ "array", "dynamic-programming" ]
[ "const getRow = function(rowIndex) {\n if (!rowIndex) return [1];\n if (rowIndex === 1) return [1, 1];\n const res = [1, 1];\n for (let i = 2; i <= rowIndex; i++) {\n res[i] = 1;\n for (let j = i - 1; j >= 1; j--) {\n res[j] = res[j] + res[j - 1];\n }\n }\n return res;\n};" ]
120
triangle
[]
/** * @param {number[][]} triangle * @return {number} */ var minimumTotal = function(triangle) { };
Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.   Example 1: Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] Output: 11 Explanation: The triangle looks like: 2 3 4 6 5 7 4 1 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). Example 2: Input: triangle = [[-10]] Output: -10   Constraints: 1 <= triangle.length <= 200 triangle[0].length == 1 triangle[i].length == triangle[i - 1].length + 1 -104 <= triangle[i][j] <= 104   Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle?
Medium
[ "array", "dynamic-programming" ]
[ "const minimumTotal = function(triangle) {\n const n = triangle.length;\n for (let i = n - 2; i >= 0; i--) {\n for (let j = 0; j < n; j++) {\n let self = triangle[i][j]; //获取第(i+1)行(j+1)个数字\n let res = Math.min(\n triangle[i + 1][j] + self,\n triangle[i + 1][j + 1] + self\n ); //得到这一行与下一行相邻数的和的最小值\n triangle[i][j] = res; //更新第(i+1)行第(j+1)个数字\n }\n }\n\n return triangle[0][0];\n};", "const minimumTotal = function(triangle) {\n const m = triangle.length, n = triangle.at(-1).length\n const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(Infinity))\n dp[1][1] = triangle[0][0]\n for(let i = 2; i <= m; i++) {\n for(let j = 1; j <= triangle[i - 1].length; j++) {\n if(j === 1) dp[i][j] = dp[i - 1][j] + triangle[i - 1][j - 1]\n else dp[i][j] = Math.min(dp[i - 1][j], dp[i - 1][j - 1]) + triangle[i - 1][j - 1] \n }\n }\n let res = Infinity\n for (let j = 0; j <= n; j++) {\n res = Math.min(res, dp[m][j])\n }\n return res\n};" ]
121
best-time-to-buy-and-sell-stock
[]
/** * @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. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.   Example 1: Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. Example 2: Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transactions are done and the max profit = 0.   Constraints: 1 <= prices.length <= 105 0 <= prices[i] <= 104
Easy
[ "array", "dynamic-programming" ]
[ "const maxProfit = function(prices) {\n let minPrice = Number.MAX_SAFE_INTEGER;\n let maxP = 0;\n for (let i = 0; i < prices.length; i++) {\n if (prices[i] < minPrice) {\n minPrice = prices[i];\n } else if (prices[i] - minPrice > maxP) {\n maxP = prices[i] - minPrice;\n }\n }\n return maxP;\n};", "const maxProfit = function(prices) {\n let res = 0, maxCur = 0\n for(let i = 1; i < prices.length; i++) {\n maxCur = Math.max(0, maxCur + (prices[i] - prices[i - 1]))\n res = Math.max(res, maxCur)\n }\n return res\n};" ]
122
best-time-to-buy-and-sell-stock-ii
[]
/** * @param {number[]} prices * @return {number} */ var maxProfit = function(prices) { };
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.   Example 1: Input: prices = [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. Example 2: Input: prices = [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. Example 3: Input: prices = [7,6,4,3,1] Output: 0 Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.   Constraints: 1 <= prices.length <= 3 * 104 0 <= prices[i] <= 104
Medium
[ "array", "dynamic-programming", "greedy" ]
[ "const maxProfit = function (prices) {\n let p = 0\n for (let i = 1; i < prices.length; ++i) {\n let delta = prices[i] - prices[i - 1]\n if (delta > 0) {\n p += delta\n }\n }\n return p\n}" ]
123
best-time-to-buy-and-sell-stock-iii
[]
/** * @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 at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).   Example 1: Input: prices = [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: prices = [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.   Constraints: 1 <= prices.length <= 105 0 <= prices[i] <= 105
Hard
[ "array", "dynamic-programming" ]
[ "const maxProfit = function(prices) {\n let maxProfit1 = 0\n let maxProfit2 = 0\n let lowestBuyPrice1 = Number.MAX_VALUE\n let lowestBuyPrice2 = Number.MAX_VALUE\n\n for (let p of prices) {\n maxProfit2 = Math.max(maxProfit2, p - lowestBuyPrice2)\n lowestBuyPrice2 = Math.min(lowestBuyPrice2, p - maxProfit1)\n maxProfit1 = Math.max(maxProfit1, p - lowestBuyPrice1)\n lowestBuyPrice1 = Math.min(lowestBuyPrice1, p)\n }\n return maxProfit2\n}" ]
124
binary-tree-maximum-path-sum
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var maxPathSum = function(root) { };
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path.   Example 1: Input: root = [1,2,3] Output: 6 Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. Example 2: Input: root = [-10,9,20,null,null,15,7] Output: 42 Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.   Constraints: The number of nodes in the tree is in the range [1, 3 * 104]. -1000 <= Node.val <= 1000
Hard
[ "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 maxPathSum = function(root) {\n let obj = {\n max: Number.MIN_SAFE_INTEGER\n }\n traverse(root, obj)\n \n return obj.max\n};\n\nfunction traverse(node, obj) {\n if(node === null) return 0\n let left = Math.max(0, traverse(node.left, obj))\n let right = Math.max(0, traverse(node.right, obj))\n obj.max = Math.max(obj.max, node.val+left+right)\n return node.val + Math.max(left, right)\n}", "const maxPathSum = function(root) {\n let res = -Infinity\n dfs(root)\n return res\n\n function dfs(node) {\n if(node == null) return 0\n let left = dfs(node.left), right = dfs(node.right)\n res = Math.max(\n res,\n node.val,\n node.val + left,\n node.val + right,\n node.val + left + right,\n )\n return Math.max(node.val, node.val + left, node.val + right)\n }\n};" ]
125
valid-palindrome
[]
/** * @param {string} s * @return {boolean} */ var isPalindrome = function(s) { };
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.   Example 1: Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome. Example 2: Input: s = "race a car" Output: false Explanation: "raceacar" is not a palindrome. Example 3: Input: s = " " Output: true Explanation: s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.   Constraints: 1 <= s.length <= 2 * 105 s consists only of printable ASCII characters.
Easy
[ "two-pointers", "string" ]
[ "const isPalindrome = function(s) {\n let start = 0\n let end = s.length - 1\n\n while(start < end) {\n while(start < s.length && !valid(s[start])) {\n start++ \n }\n while(end >=0 && !valid(s[end])) {\n end-- \n }\n if(start < s.length && end >=0) {\n if(s[start].toLowerCase() !== s[end].toLowerCase()) return false \n }\n start++\n end--\n }\n return true\n};\n\nfunction valid(c) {\n const code = c.toLowerCase().charCodeAt(0)\n const zeroCode = ('0').charCodeAt(0)\n const nineCode = ('9').charCodeAt(0)\n const aCode = ('a').charCodeAt(0)\n const zCode = ('z').charCodeAt(0)\n if( (code >= zeroCode && code <= nineCode) || ( code >= aCode && code <= zCode ) ) return true\n \n return false\n} " ]
126
word-ladder-ii
[]
/** * @param {string} beginWord * @param {string} endWord * @param {string[]} wordList * @return {string[][]} */ var findLadders = function(beginWord, endWord, wordList) { };
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].   Example 1: Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]] Explanation: There are 2 shortest transformation sequences: "hit" -> "hot" -> "dot" -> "dog" -> "cog" "hit" -> "hot" -> "lot" -> "log" -> "cog" Example 2: Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output: [] Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.   Constraints: 1 <= beginWord.length <= 5 endWord.length == beginWord.length 1 <= wordList.length <= 500 wordList[i].length == beginWord.length beginWord, endWord, and wordList[i] consist of lowercase English letters. beginWord != endWord All the words in wordList are unique. The sum of all shortest transformation sequences does not exceed 105.
Hard
[ "hash-table", "string", "backtracking", "breadth-first-search" ]
[ "const findLadders = function (beginWord, endWord, wordList) {\n const res = []\n if (!wordList.includes(endWord)) return res\n const set1 = new Set([beginWord]),\n set2 = new Set([endWord]),\n wordSet = new Set(wordList),\n temp = [beginWord]\n const map = new Map()\n const traverse = (set1, set2, dir) => {\n if (set1.size === 0) return false\n if (set1.size > set2.size) return traverse(set2, set1, !dir)\n for (const val of set1.values()) {\n if (wordSet.has(val)) wordSet.delete(val)\n }\n for (const val of set2.values()) {\n if (wordSet.has(val)) wordSet.delete(val)\n }\n const set = new Set()\n let done = false\n for (const str of set1.values()) {\n for (let i = 0; i < str.length; i++) {\n for (let ch = 'a'.charCodeAt(); ch <= 'z'.charCodeAt(); ch++) {\n const word =\n str.slice(0, i) + String.fromCharCode(ch) + str.slice(i + 1)\n const key = dir ? str : word\n const val = dir ? word : str\n const list = map.get(key) || []\n if (set2.has(word)) {\n done = true\n list.push(val)\n map.set(key, list)\n }\n if (!done && wordSet.has(word)) {\n set.add(word)\n list.push(val)\n map.set(key, list)\n }\n }\n }\n }\n return done || traverse(set2, set, !dir)\n }\n const dfs = (word) => {\n if (word === endWord) {\n res.push(temp.slice())\n return\n }\n const nei = map.get(word) || []\n for (const w of nei) {\n temp.push(w)\n dfs(w)\n temp.pop()\n }\n }\n traverse(set1, set2, true)\n dfs(beginWord)\n return res\n}" ]
127
word-ladder
[]
/** * @param {string} beginWord * @param {string} endWord * @param {string[]} wordList * @return {number} */ var ladderLength = function(beginWord, endWord, wordList) { };
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.   Example 1: Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: 5 Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long. Example 2: Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output: 0 Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.   Constraints: 1 <= beginWord.length <= 10 endWord.length == beginWord.length 1 <= wordList.length <= 5000 wordList[i].length == beginWord.length beginWord, endWord, and wordList[i] consist of lowercase English letters. beginWord != endWord All the words in wordList are unique.
Hard
[ "hash-table", "string", "breadth-first-search" ]
[ "const ladderLength = function(beginWord, endWord, wordList) {\n const list = new Set(wordList)\n if (!list.has(endWord)) return 0\n let one = new Set([beginWord])\n let two = new Set([endWord])\n let step = 1\n while (one.size && two.size) {\n let temp = new Set()\n if (two.size < one.size) [one, two] = [two, one]\n for (const word of one) {\n for (let i = 0; i < word.length; i++) {\n for (let j = 0; j < 26; j++) {\n const candidate =\n word.slice(0, i) + String.fromCharCode(97 + j) + word.slice(i + 1)\n if (two.has(candidate)) return step + 1\n if (!list.has(candidate)) continue\n temp.add(candidate)\n list.delete(candidate)\n }\n }\n }\n ;[one, temp] = [temp, one]\n step++\n }\n return 0\n}" ]
128
longest-consecutive-sequence
[]
/** * @param {number[]} nums * @return {number} */ var longestConsecutive = function(nums) { };
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.   Example 1: Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. Example 2: Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9   Constraints: 0 <= nums.length <= 105 -109 <= nums[i] <= 109
Medium
[ "array", "hash-table", "union-find" ]
[ "const longestConsecutive = function(nums) {\n if(nums.length === 0) return 0\n nums.sort((a, b) => a - b)\n let max = 1\n let cur = 1\n for(let i = 1; i < nums.length; i++) {\n if(nums[i] - nums[i-1] === 1) {\n cur += 1\n max = Math.max(max, cur)\n } else if(nums[i] - nums[i-1] === 0) {\n \n } else {\n cur = 1\n }\n }\n \n return max\n};" ]
129
sum-root-to-leaf-numbers
[]
/** * 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 sumNumbers = function(root) { };
You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123. Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children.   Example 1: Input: root = [1,2,3] Output: 25 Explanation: The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path 1->3 represents the number 13. Therefore, sum = 12 + 13 = 25. Example 2: Input: root = [4,9,0,5,1] Output: 1026 Explanation: The root-to-leaf path 4->9->5 represents the number 495. The root-to-leaf path 4->9->1 represents the number 491. The root-to-leaf path 4->0 represents the number 40. Therefore, sum = 495 + 491 + 40 = 1026.   Constraints: The number of nodes in the tree is in the range [1, 1000]. 0 <= Node.val <= 9 The depth of the tree will not exceed 10.
Medium
[ "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 sumNumbers = function(root) {\n const sum = []\n rec(root, '', sum)\n return sum.reduce((ac, el) => ac + el, 0)\n};\n\nfunction rec(node, str, arr) {\n if (node == null) {\n arr.push(+str)\n return\n }\n if (node.left !== null) {\n rec(node.left, str + node.val, arr)\n }\n if (node.right !== null) {\n rec(node.right, str + node.val, arr)\n }\n if (node.left === null && node.right === null) {\n arr.push(+(str + node.val) )\n }\n}" ]
130
surrounded-regions
[]
/** * @param {character[][]} board * @return {void} Do not return anything, modify board in-place instead. */ var solve = function(board) { };
Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region.   Example 1: Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]] Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]] Explanation: Notice that an 'O' should not be flipped if: - It is on the border, or - It is adjacent to an 'O' that should not be flipped. The bottom 'O' is on the border, so it is not flipped. The other three 'O' form a surrounded region, so they are flipped. Example 2: Input: board = [["X"]] Output: [["X"]]   Constraints: m == board.length n == board[i].length 1 <= m, n <= 200 board[i][j] is 'X' or 'O'.
Medium
[ "array", "depth-first-search", "breadth-first-search", "union-find", "matrix" ]
[ "const solve = function(board) {\n if (!board || board.length < 3 || board[0].length < 3) return;\n let r = board.length;\n let c = board[0].length;\n for (let i = 0; i < c; i++) {\n if (board[0][i] === \"O\") search(board, 0, i);\n if (board[r - 1][i] === \"O\") search(board, r - 1, i);\n }\n for (let i = 0; i < r; i++) {\n if (board[i][0] === \"O\") search(board, i, 0);\n if (board[i][c - 1] === \"O\") search(board, i, c - 1);\n }\n for (let i = 0; i < r; i++) {\n for (let j = 0; j < c; j++) {\n if (board[i][j] === \"O\") board[i][j] = \"X\";\n if (board[i][j] === \"*\") board[i][j] = \"O\";\n }\n }\n};\n\nfunction search(board, i, j) {\n if (i < 0 || j < 0 || i >= board.length || j >= board[0].length) return;\n if (board[i][j] !== \"O\") return;\n board[i][j] = \"*\";\n search(board, i + 1, j);\n search(board, i - 1, j);\n search(board, i, j + 1);\n search(board, i, j - 1);\n}", "const solve = (board) => {\n if (!board || board.length === 0 || board[0].length === 0) return;\n const n = board.length;\n const m = board[0].length;\n const dirs = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ];\n const bfs = (board, n, m, i, j) => {\n const queue = [];\n queue.push([i, j]);\n board[i][j] = \"1\";\n while (queue.length > 0) {\n const pos = queue.shift();\n for (let k = 0; k < 4; k++) {\n i = pos[0] + dirs[k][0];\n j = pos[1] + dirs[k][1];\n if (i >= 0 && i < n && j >= 0 && j < m && board[i][j] === \"O\") {\n board[i][j] = \"1\";\n queue.push([i, j]);\n }\n }\n }\n };\n // scan the borders and mark the 'O's to '1'\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (\n (i === 0 || i === n - 1 || j === 0 || j === m - 1) &&\n board[i][j] === \"O\"\n ) {\n bfs(board, n, m, i, j);\n }\n }\n }\n // scan the inner area and mark the 'O's to 'X'\n for (let i = 1; i < n; i++) {\n for (let j = 1; j < m; j++) {\n if (board[i][j] === \"O\") {\n board[i][j] = \"X\";\n }\n }\n }\n // reset all the '1's to 'O's\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (board[i][j] === \"1\") {\n board[i][j] = \"O\";\n }\n }\n }\n};" ]
131
palindrome-partitioning
[]
/** * @param {string} s * @return {string[][]} */ var partition = function(s) { };
Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.   Example 1: Input: s = "aab" Output: [["a","a","b"],["aa","b"]] Example 2: Input: s = "a" Output: [["a"]]   Constraints: 1 <= s.length <= 16 s contains only lowercase English letters.
Medium
[ "string", "dynamic-programming", "backtracking" ]
[ "const partition = function(s) {\n let res = []\n backtrack(res, [], 0, s)\n return res\n}\n\nfunction backtrack(res, cur, start, s) {\n if (start === s.length) res.push([...cur])\n else {\n for (let i = start; i < s.length; i++) {\n if (isPalindrome(s, start, i)) {\n cur.push(s.substring(start, i + 1))\n backtrack(res, cur, i + 1, s)\n cur.pop()\n }\n }\n }\n}\n\nfunction isPalindrome(str, start, i) {\n let l = start,\n r = i\n while (l < r) {\n if (str[l] !== str[r]) return false\n l++\n r--\n }\n return true\n}", "const partition = function(s) {\n const res = []\n helper(s, 0, [], res)\n return res\n};\n\nfunction helper(str, idx, cur, res) {\n if(idx >= str.length) {\n res.push(cur.slice())\n return\n }\n for(let i = idx, len = str.length; i < len; i++) {\n const tmp = str.slice(idx, i + 1)\n if(chk(tmp)) {\n cur.push(tmp)\n helper(str, i + 1, cur, res)\n cur.pop()\n }\n }\n}\nfunction chk(str) {\n const n = str.length\n let l = 0, r = n - 1\n while(l < r) {\n if(str[l] !== str[r]) return false\n l++\n r--\n }\n return true\n}" ]
132
palindrome-partitioning-ii
[]
/** * @param {string} s * @return {number} */ var minCut = function(s) { };
Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s.   Example 1: Input: s = "aab" Output: 1 Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. Example 2: Input: s = "a" Output: 0 Example 3: Input: s = "ab" Output: 1   Constraints: 1 <= s.length <= 2000 s consists of lowercase English letters only.
Hard
[ "string", "dynamic-programming" ]
[ "const minCut = function(s) {\n const n = s.length\n if (n <= 1) return 0\n const dp = new Array(n).fill(0)\n for (let i = 1; i < n; i++) dp[i] = i\n for (let i = 1; i < n; i++) {\n // odd\n for (\n let start = i, end = i;\n end < n && start >= 0 && s[end] === s[start];\n start--, end++\n ) {\n dp[end] = Math.min(dp[end], start === 0 ? 0 : dp[start - 1] + 1)\n }\n // even\n for (\n let start = i - 1, end = i;\n end < n && start >= 0 && s[end] === s[start];\n start--, end++\n ) {\n dp[end] = Math.min(dp[end], start === 0 ? 0 : dp[start - 1] + 1)\n }\n }\n return dp[n - 1]\n}", "const minCut = function(s) {\n const n = s.length\n const cut = new Array(n + 1).fill(0)\n for (let i = 0; i <= n; i++) cut[i] = i - 1\n for (let i = 0; i < n; i++) {\n // odd\n for (let j = 0; i + j < n && i - j >= 0 && s[i + j] === s[i - j]; j++) {\n cut[i + j + 1] = Math.min(cut[i + j + 1], cut[i - j] + 1)\n }\n // even\n for (\n let j = 1;\n i + j < n && i - j + 1 >= 0 && s[i + j] === s[i - j + 1];\n j++\n ) {\n cut[i + j + 1] = Math.min(cut[i + j + 1], cut[i - j + 1] + 1)\n }\n }\n return cut[n]\n}" ]
133
clone-graph
[]
/** * // Definition for a Node. * function Node(val, neighbors) { * this.val = val === undefined ? 0 : val; * this.neighbors = neighbors === undefined ? [] : neighbors; * }; */ /** * @param {Node} node * @return {Node} */ var cloneGraph = function(node) { };
Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. class Node { public int val; public List<Node> neighbors; }   Test case format: For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list. An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.   Example 1: Input: adjList = [[2,4],[1,3],[2,4],[1,3]] Output: [[2,4],[1,3],[2,4],[1,3]] Explanation: There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). Example 2: Input: adjList = [[]] Output: [[]] Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. Example 3: Input: adjList = [] Output: [] Explanation: This an empty graph, it does not have any nodes.   Constraints: The number of nodes in the graph is in the range [0, 100]. 1 <= Node.val <= 100 Node.val is unique for each node. There are no repeated edges and no self-loops in the graph. The Graph is connected and all nodes can be visited starting from the given node.
Medium
[ "hash-table", "depth-first-search", "breadth-first-search", "graph" ]
/** * // Definition for a Node. * function Node(val, neighbors) { * this.val = val === undefined ? 0 : val; * this.neighbors = neighbors === undefined ? [] : neighbors; * }; */
[ "const cloneGraph = function(node) {\n if (!node) return node\n const map = {}\n return traverse(node)\n function traverse(node) {\n if(!node) return node;\n if (!map[node.val]) {\n const newNode = new Node(node.val)\n map[node.val] = newNode\n newNode.neighbors = node.neighbors.map(traverse)\n }\n return map[node.val]\n }\n}" ]
134
gas-station
[]
/** * @param {number[]} gas * @param {number[]} cost * @return {number} */ var canCompleteCircuit = function(gas, cost) { };
There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique   Example 1: Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] Output: 3 Explanation: Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. Example 2: Input: gas = [2,3,4], cost = [3,4,3] Output: -1 Explanation: You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start.   Constraints: n == gas.length == cost.length 1 <= n <= 105 0 <= gas[i], cost[i] <= 104
Medium
[ "array", "greedy" ]
[ "const canCompleteCircuit = function(gas, cost) {\n let total = 0\n let curLeft = 0\n let curtIdx = 0\n for (let i = 0; i < gas.length; i++) {\n total += gas[i] - cost[i]\n curLeft += gas[i] - cost[i]\n if (curLeft < 0) {\n curtIdx = i + 1\n curLeft = 0\n }\n }\n return total < 0 ? -1 : curtIdx\n}", "const canCompleteCircuit = function(gas, cost) {\n const len = gas.length\n let tank = 0\n let count = 0\n for (let i = 0; i < len * 2; i++) {\n let idx = i % len\n if (count === len) return idx\n count += 1\n tank += gas[idx] - cost[idx]\n if (tank < 0) {\n tank = 0\n count = 0\n }\n }\n return -1\n}" ]
135
candy
[]
/** * @param {number[]} ratings * @return {number} */ var candy = function(ratings) { };
There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. Return the minimum number of candies you need to have to distribute the candies to the children.   Example 1: Input: ratings = [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Example 2: Input: ratings = [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.   Constraints: n == ratings.length 1 <= n <= 2 * 104 0 <= ratings[i] <= 2 * 104
Hard
[ "array", "greedy" ]
[ "const candy = function(ratings) {\n const candies = new Array(ratings.length).fill(1);\n for (let i = 1; i < candies.length; i++) {\n if (ratings[i] > ratings[i - 1]) {\n candies[i] = candies[i - 1] + 1;\n }\n }\n let sum = candies[candies.length - 1];\n for (let i = candies.length - 2; i >= 0; i--) {\n if (ratings[i] > ratings[i + 1]) {\n candies[i] = Math.max(candies[i], candies[i + 1] + 1);\n }\n sum += candies[i];\n }\n return sum;\n};" ]
136
single-number
[]
/** * @param {number[]} nums * @return {number} */ var singleNumber = function(nums) { };
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space.   Example 1: Input: nums = [2,2,1] Output: 1 Example 2: Input: nums = [4,1,2,1,2] Output: 4 Example 3: Input: nums = [1] Output: 1   Constraints: 1 <= nums.length <= 3 * 104 -3 * 104 <= nums[i] <= 3 * 104 Each element in the array appears twice except for one element which appears only once.
Easy
[ "array", "bit-manipulation" ]
[ "const singleNumber = function(nums) {\n let xor = nums[0]\n for(let i = 1; i< nums.length; i++) xor ^= nums[i]\n return xor\n};", "const singleNumber = function(nums) {\n return nums.reduce((ac, e) => ac ^ e, 0)\n};" ]
137
single-number-ii
[]
/** * @param {number[]} nums * @return {number} */ var singleNumber = function(nums) { };
Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it. You must implement a solution with a linear runtime complexity and use only constant extra space.   Example 1: Input: nums = [2,2,3,2] Output: 3 Example 2: Input: nums = [0,1,0,1,0,1,99] Output: 99   Constraints: 1 <= nums.length <= 3 * 104 -231 <= nums[i] <= 231 - 1 Each element in nums appears exactly three times except for one element which appears once.
Medium
[ "array", "bit-manipulation" ]
[ "const singleNumber = function(nums) {\n const hash = {}\n \n nums.forEach(el => {\n hash[el] = (hash[el] && hash[el] + 1) || 1\n })\n \n for(let el in hash) {\n if(hash[el] === 1) return +el\n }\n};", "const singleNumber = (nums)=> {\n let one=0, two=0;\n for (let i=0; i<nums.length; i++) {\n one = (one ^ nums[i]) & ~two;\n two = (two ^ nums[i]) & ~one;\n }\n return one;\n}", "const singleNumber = (nums)=> {\n // Initialize result\n let result = 0;\n let x, sum;\n const n = nums.length\n // Iterate through every bit\n for (let i = 0; i < 32; i++) {\n // Find sum of set bits at ith position in all\n // array elements\n sum = 0;\n x = (1 << i);\n for (let j = 0; j < n; j++ ) {\n if (nums[j] & x) sum++;\n }\n // The bits with sum not multiple of 3, are the\n // bits of element with single occurrence.\n if (sum % 3) result |= x;\n }\n return result;\n}" ]
138
copy-list-with-random-pointer
[ "Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, ensure you are not making multiple copies of the same node.", "You may want to use extra space to keep old_node ---> new_node mapping to prevent creating multiple copies of the same node.", "We can avoid using extra space for old_node ---> new_node mapping by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For example:\r\nOld List: A --> B --> C --> D\r\nInterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D'", "The interweaving is done using next</b> pointers and we can make use of interweaved structure to get the correct reference nodes for random</b> pointers." ]
/** * // Definition for a Node. * function Node(val, next, random) { * this.val = val; * this.next = next; * this.random = random; * }; */ /** * @param {Node} head * @return {Node} */ var copyRandomList = function(head) { };
A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y. Return the head of the copied linked list. The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where: val: an integer representing Node.val random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node. Your code will only be given the head of the original linked list.   Example 1: Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] Example 2: Input: head = [[1,1],[2,1]] Output: [[1,1],[2,1]] Example 3: Input: head = [[3,null],[3,0],[3,null]] Output: [[3,null],[3,0],[3,null]]   Constraints: 0 <= n <= 1000 -104 <= Node.val <= 104 Node.random is null or is pointing to some node in the linked list.
Medium
[ "hash-table", "linked-list" ]
/** * // Definition for a Node. * function Node(val, next, random) { * this.val = val; * this.next = next; * this.random = random; * }; */
[ "const copyRandomList = function(head) {\n if (head == null) {\n return null;\n }\n \n // Creating a new weaved list of original and copied nodes.\n let ptr = head;\n while (ptr != null) {\n \n // Cloned node\n const newNode = new RandomListNode(ptr.label);\n \n // Inserting the cloned node just next to the original node.\n // If A->B->C is the original linked list,\n // Linked list after weaving cloned nodes would be A->A'->B->B'->C->C'\n newNode.next = ptr.next;\n ptr.next = newNode;\n ptr = newNode.next;\n }\n \n ptr = head;\n \n // Now link the random pointers of the new nodes created.\n // Iterate the newly created list and use the original nodes' random pointers,\n // to assign references to random pointers for cloned nodes.\n while (ptr != null) {\n ptr.next.random = (ptr.random != null) ? ptr.random.next : null;\n ptr = ptr.next.next;\n }\n \n // Unweave the linked list to get back the original linked list and the cloned list.\n // i.e. A->A'->B->B'->C->C' would be broken to A->B->C and A'->B'->C'\n let ptr_old_list = head; // A->B->C\n let ptr_new_list = head.next; // A'->B'->C'\n let head_old = head.next;\n while (ptr_old_list != null) {\n ptr_old_list.next = ptr_old_list.next.next;\n ptr_new_list.next = (ptr_new_list.next != null) ? ptr_new_list.next.next : null;\n ptr_old_list = ptr_old_list.next;\n ptr_new_list = ptr_new_list.next;\n }\n return head_old;\n};" ]
139
word-break
[]
/** * @param {string} s * @param {string[]} wordDict * @return {boolean} */ var wordBreak = function(s, wordDict) { };
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation.   Example 1: Input: s = "leetcode", wordDict = ["leet","code"] Output: true Explanation: Return true because "leetcode" can be segmented as "leet code". Example 2: Input: s = "applepenapple", wordDict = ["apple","pen"] Output: true Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word. Example 3: Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output: false   Constraints: 1 <= s.length <= 300 1 <= wordDict.length <= 1000 1 <= wordDict[i].length <= 20 s and wordDict[i] consist of only lowercase English letters. All the strings of wordDict are unique.
Medium
[ "array", "hash-table", "string", "dynamic-programming", "trie", "memoization" ]
[ "const wordBreak = function(s, wordDict) {\n const map = new Map()\n return helper(s, 0, new Set(wordDict), map)\n};\n\nfunction helper(str, idx, set, map) {\n if(idx === str.length) return true\n if(map.has(idx)) return map.get(idx)\n let res = false\n for(let i = idx; i < str.length; i++) {\n const tmp = str.slice(idx, i + 1)\n if(set.has(tmp)) {\n const bool = helper(str, i + 1, set, map)\n if(bool) {\n res = true\n break\n }\n }\n }\n map.set(idx, res)\n return res\n}", "const wordBreak = function(s, wordDict) {\n const len = s.length;\n const dp = new Array(len).fill(false);\n\n for (let i = 0; i < len; i++) {\n for (let word of wordDict) {\n if (word.length <= i + 1 \n && s.substring(i - word.length + 1, i + 1) === word) {\n let index = i - word.length;\n if (index < 0) {\n dp[i] = true;\n } else {\n dp[i] = dp[index];\n }\n if(dp[i]) break;\n }\n }\n }\n\n return dp[len - 1];\n};", "const wordBreak = function(s, wordDict) {\n const len = s.length;\n const f = new Array(len + 1).fill(false);\n\n f[0] = true;\n\n for(let i = 1; i <= len; i++){\n for(let str of wordDict){\n if(str.length <= i \n && f[i - str.length] \n && s.slice(i - str.length, i) === str){\n f[i] = true;\n break;\n }\n }\n }\n\n return f[len];\n};", "const wordBreak = function(s, wordDict) {\n const set = new Set(wordDict)\n const dp = Array(s.length + 1).fill(false)\n dp[0] = true\n for(let i = 1; i <= s.length; i++) {\n for(let j = 0; j < i; j++) {\n if(dp[j] && set.has(s.slice(j, i))) {\n dp[i] = true\n break\n }\n }\n }\n \n return dp[s.length]\n};" ]
140
word-break-ii
[]
/** * @param {string} s * @param {string[]} wordDict * @return {string[]} */ var wordBreak = function(s, wordDict) { };
Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order. Note that the same word in the dictionary may be reused multiple times in the segmentation.   Example 1: Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"] Output: ["cats and dog","cat sand dog"] Example 2: Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"] Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"] Explanation: Note that you are allowed to reuse a dictionary word. Example 3: Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output: []   Constraints: 1 <= s.length <= 20 1 <= wordDict.length <= 1000 1 <= wordDict[i].length <= 10 s and wordDict[i] consist of only lowercase English letters. All the strings of wordDict are unique. Input is generated in a way that the length of the answer doesn't exceed 105.
Hard
[ "array", "hash-table", "string", "dynamic-programming", "backtracking", "trie", "memoization" ]
[ "const wordBreak = function(s, wordDict) {\n const set = new Set(wordDict)\n const map = new Map()\n return helper(s, 0, set, map)\n};\n\nfunction helper(str, idx, set, map) {\n if(idx === str.length) return []\n if(map.has(idx)) return map.get(idx)\n const res = []\n for(let i = idx; i < str.length; i++) {\n const tmp = str.slice(idx, i + 1)\n if(set.has(tmp)) {\n const arr = helper(str, i + 1, set, map)\n if(i === str.length - 1) res.push(tmp)\n for(let item of arr) {\n res.push(`${tmp} ${item}`)\n }\n }\n }\n map.set(idx, res)\n return res\n}", "const wordBreak = function(s, wordDict) {\n return backTrack(s, wordDict, {})\n};\n\nfunction backTrack(s, wordDict, mem) {\n if(mem.hasOwnProperty(s)) return mem[s]\n const result = []\n for(let word of wordDict) {\n if(s.startsWith(word)) {\n let next = s.slice(word.length)\n if(next.length === 0) result.push(word)\n else {\n for(let sub of backTrack(next, wordDict, mem)) {\n result.push(word+ ' '+sub)\n }\n }\n }\n }\n mem[s] = result\n return result\n}", "const wordBreak = function (s, wordDict) {\n const dictSet = new Set(wordDict)\n const memo = {}\n function dfs(start) {\n if (start > s.length - 1) {\n return [[]]\n }\n if (memo[start] !== undefined) {\n return memo[start]\n }\n const out = []\n for (let i = start; i < s.length; i++) {\n const substr = s.substring(start, i + 1)\n if (dictSet.has(substr)) {\n let next = dfs(i + 1)\n for (let n of next) {\n out.push([substr, ...n])\n }\n }\n }\n return (memo[start] = out)\n }\n const res = dfs(0)\n return res.filter((a) => a.join('') === s).map((a) => a.join(' '))\n}", "const wordBreak = (s, wordDict) => {\n const set = new Set(wordDict)\n return helper(s, 0, set)\n}\n\nfunction helper(s, idx, dict) {\n if(idx === s.length) return []\n const res = []\n for(let i = idx; i < s.length; i++) {\n const tmp = s.slice(idx, i + 1)\n if(dict.has(tmp)) {\n const arr = helper(s, i + 1, dict)\n if(i + 1 >= s.length) {\n res.push(tmp)\n } else if(arr.length) {\n for(let e of arr) {\n res.push(tmp + ' ' + e)\n }\n }\n }\n }\n return res\n}" ]
141
linked-list-cycle
[]
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {boolean} */ var hasCycle = function(head) { };
Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false.   Example 1: Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). Example 2: Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 0th node. Example 3: Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list.   Constraints: The number of the nodes in the list is in the range [0, 104]. -105 <= Node.val <= 105 pos is -1 or a valid index in the linked-list.   Follow up: Can you solve it using O(1) (i.e. constant) memory?
Easy
[ "hash-table", "linked-list", "two-pointers" ]
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */
[ "const hasCycle = function(head) {\n const seen = []\n while(head != null) {\n if(seen.indexOf(head) !== -1) {\n return true\n } else {\n seen.push(head)\n }\n head = head.next\n }\n return false\n};" ]
142
linked-list-cycle-ii
[]
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ var detectCycle = function(head) { };
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. Do not modify the linked list.   Example 1: Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node. Example 2: Input: head = [1,2], pos = 0 Output: tail connects to node index 0 Explanation: There is a cycle in the linked list, where tail connects to the first node. Example 3: Input: head = [1], pos = -1 Output: no cycle Explanation: There is no cycle in the linked list.   Constraints: The number of the nodes in the list is in the range [0, 104]. -105 <= Node.val <= 105 pos is -1 or a valid index in the linked-list.   Follow up: Can you solve it using O(1) (i.e. constant) memory?
Medium
[ "hash-table", "linked-list", "two-pointers" ]
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */
[ "const detectCycle = function(head) {\n if(head === null || head.next === null) return null\n let fast = head\n let slow = head\n let start = head\n while(fast !== null && fast.next !== null) {\n fast = fast.next.next\n slow = slow.next\n if(fast === slow) {\n while(slow !== start) {\n slow = slow.next\n start = start.next\n }\n return start\n }\n }\n return null\n};", "const detectCycle = (head) => {\n if (!head) return head;\n let currentNode = head;\n let previousNode = true;\n while (currentNode) {\n if (currentNode.previous) return currentNode\n if (!currentNode.previous) {\n currentNode.previous = previousNode;\n previousNode = currentNode;\n currentNode = currentNode.next;\n }\n }\n return null;\n};" ]
143
reorder-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 {void} Do not return anything, modify head in-place instead. */ var reorderList = function(head) { };
You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → … → Ln - 1 → Ln Reorder the list to be on the following form: L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … You may not modify the values in the list's nodes. Only nodes themselves may be changed.   Example 1: Input: head = [1,2,3,4] Output: [1,4,2,3] Example 2: Input: head = [1,2,3,4,5] Output: [1,5,2,4,3]   Constraints: The number of nodes in the list is in the range [1, 5 * 104]. 1 <= Node.val <= 1000
Medium
[ "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 reorderList = function(head) {\n if(head == null) return head\n let slow = head, fast = head\n while(fast && fast.next) {\n slow = slow.next\n fast = fast.next.next\n }\n let head2 = reverse(slow.next)\n slow.next = null\n \n while(head && head2) {\n const next = head.next, next2 = head2.next\n head2.next = head.next\n head.next = head2\n head = next\n head2 = next2\n }\n \n function reverse(node) {\n let pre = null, cur = node\n while(cur) {\n const tmp = cur.next\n cur.next = pre\n pre = cur\n cur = tmp\n }\n return pre\n }\n};", "const reorderList = function(head) {\n if (!head || !head.next) return head;\n\n const reverse = head => {\n if (!head || !head.next) return head;\n const newHead = reverse(head.next);\n head.next.next = head;\n head.next = null;\n return newHead;\n };\n\n const merge = (l1, l2) => {\n if (!l1) return l2;\n if (!l2) return l1;\n while (l1 && l2) {\n const next1 = l1.next;\n const next2 = l2.next;\n l1.next = l2;\n if (next1 == null) break;\n l2.next = next1;\n l1 = next1;\n l2 = next2;\n }\n };\n\n let fast = head;\n let slow = head;\n\n while (fast && fast.next) {\n fast = fast.next.next;\n slow = slow.next;\n }\n\n fast = slow.next;\n slow.next = null;\n\n fast = reverse(fast);\n merge(head, fast);\n};", "const reorderList = function(head) {\n if (head == null || head.next == null) {\n return head;\n }\n const arr = [];\n let tmp = head;\n while (tmp.next) {\n arr.push(tmp);\n tmp = tmp.next;\n }\n arr.push(tmp);\n for (let i = 1; i < arr.length; i = i + 2) {\n if (arr.length - 1 > i) {\n let el = arr.pop();\n arr.splice(i, 0, el);\n }\n }\n for (let i = 1; i < arr.length; i++) {\n arr[i - 1].next = arr[i];\n if (i === arr.length - 1) arr[i].next = null;\n }\n};" ]
144
binary-tree-preorder-traversal
[]
/** * 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 preorderTraversal = function(root) { };
Given the root of a binary tree, return the preorder traversal of its nodes' values.   Example 1: Input: root = [1,null,2,3] Output: [1,2,3] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1]   Constraints: The number of nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100   Follow up: Recursive solution is trivial, could you do it iteratively?
Easy
[ "stack", "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 preorderTraversal = function(root) {\n const res = [];\n traversal(root, res);\n return res;\n};\n\nfunction traversal(node, arr) {\n if (node === null) return;\n arr.push(node.val);\n if (node.left) {\n traversal(node.left, arr);\n }\n if (node.right) {\n traversal(node.right, arr);\n }\n}" ]
145
binary-tree-postorder-traversal
[]
/** * 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 postorderTraversal = function(root) { };
Given the root of a binary tree, return the postorder traversal of its nodes' values.   Example 1: Input: root = [1,null,2,3] Output: [3,2,1] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1]   Constraints: The number of the nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100   Follow up: Recursive solution is trivial, could you do it iteratively?
Easy
[ "stack", "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 postorderTraversal = function(root) {\n const res = []\n traverse(root, res)\n return res\n};\n\nfunction traverse(node, arr) {\n if(node == null) return\n traverse(node.left, arr)\n traverse(node.right, arr)\n arr.push(node.val)\n}" ]
146
lru-cache
[]
/** * @param {number} capacity */ var LRUCache = function(capacity) { }; /** * @param {number} key * @return {number} */ LRUCache.prototype.get = function(key) { }; /** * @param {number} key * @param {number} value * @return {void} */ LRUCache.prototype.put = function(key, value) { }; /** * Your LRUCache object will be instantiated and called as such: * var obj = new LRUCache(capacity) * var param_1 = obj.get(key) * obj.put(key,value) */
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key. The functions get and put must each run in O(1) average time complexity.   Example 1: Input ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]] Output [null, null, null, 1, null, -1, null, -1, 3, 4] Explanation LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4   Constraints: 1 <= capacity <= 3000 0 <= key <= 104 0 <= value <= 105 At most 2 * 105 calls will be made to get and put.
Medium
[ "hash-table", "linked-list", "design", "doubly-linked-list" ]
[ "class Node {\n constructor(key, val) {\n this.val = val;\n this.key = key;\n this.next = this.pre = null;\n }\n}\n\nconst LRUCache = function(capacity) {\n this.capacity = capacity;\n this.count = 0;\n this.start = new Node(-1, -1);\n this.end = new Node(-1, -1);\n this.start.next = this.end;\n this.end.pre = this.start;\n this.map = {};\n};\n\n// insert node into the next of the start\nconst insertAfter = function(start, node) {\n let next = start.next;\n start.next = node;\n node.pre = start;\n node.next = next;\n next.pre = node;\n};\n\nconst detach = function(node) {\n let pre = node.pre,\n next = node.next;\n pre.next = next;\n next.pre = pre;\n node.next = node.pre = null;\n};\n\n\nLRUCache.prototype.get = function(key) {\n let node = this.map[key];\n if (node != undefined) {\n detach(node);\n insertAfter(this.start, node);\n return node.val;\n } else {\n return -1;\n }\n};\n\n\nLRUCache.prototype.put = function(key, value) {\n let node = this.map[key];\n if (!node) {\n if (this.count == this.capacity) {\n // deleting last nodes\n let t = this.end.pre;\n detach(t);\n delete this.map[t.key];\n } else {\n this.count++;\n }\n node = new Node(key, value);\n this.map[key] = node;\n insertAfter(this.start, node);\n } else {\n node.val = value;\n detach(node);\n insertAfter(this.start, node);\n }\n};", "const LRUCache = function(capacity) {\n this.m = new Map()\n this.limit = capacity\n};\n\n\nLRUCache.prototype.get = function(key) {\n if(!this.m.has(key)) return -1\n const v = this.m.get(key)\n this.m.delete(key)\n this.m.set(key, v)\n return v\n};\n\n\nLRUCache.prototype.put = function(key, value) {\n if(this.m.has(key)) {\n this.m.delete(key)\n } else {\n if(this.m.size >= this.limit) {\n const first = this.m.keys().next().value\n this.m.delete(first)\n }\n }\n this.m.set(key, value)\n};" ]
147
insertion-sort-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 insertionSortList = function(head) { };
Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head. The steps of the insertion sort algorithm: Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. It repeats until no input elements remain. The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.   Example 1: Input: head = [4,2,1,3] Output: [1,2,3,4] Example 2: Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5]   Constraints: The number of nodes in the list is in the range [1, 5000]. -5000 <= Node.val <= 5000
Medium
[ "linked-list", "sorting" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "const insertionSortList = function(head) {\n const dummy = new ListNode()\n dummy.next = head\n let insert = dummy\n let cur = head\n while (cur && cur.next) {\n if (cur.val < cur.next.val) {\n cur = cur.next\n continue\n }\n insert = dummy\n while (insert.next.val < cur.next.val) {\n insert = insert.next\n }\n const temp = cur.next\n cur.next = temp.next\n temp.next = insert.next\n insert.next = temp\n }\n return dummy.next\n}" ]
148
sort-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 sortList = function(head) { };
Given the head of a linked list, return the list after sorting it in ascending order.   Example 1: Input: head = [4,2,1,3] Output: [1,2,3,4] Example 2: Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5] Example 3: Input: head = [] Output: []   Constraints: The number of nodes in the list is in the range [0, 5 * 104]. -105 <= Node.val <= 105   Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?
Medium
[ "linked-list", "two-pointers", "divide-and-conquer", "sorting", "merge-sort" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "function sortList(head) {\n quickSort(head, null);\n return head;\n}\n\nfunction quickSort(head, tail) {\n if (head == tail) {\n return;\n }\n const slow = partition(head, tail);\n quickSort(head, slow);\n quickSort(slow.next, tail);\n}\n\nfunction swap(node1, node2) {\n let tmp = node1.val;\n node1.val = node2.val;\n node2.val = tmp;\n}\n\nfunction partition(head, tail) {\n let slow = head,\n fast = head.next;\n let p = head.val;\n while (fast != tail) {\n if (fast.val <= p) {\n slow = slow.next;\n swap(slow, fast);\n }\n fast = fast.next;\n }\n swap(head, slow);\n return slow;\n}", "function sortList(head) {\n if(head == null || head.next == null) return head\n let slow = head, fast = head, pre = null\n while(fast && fast.next) {\n pre = slow\n slow = slow.next\n fast = fast.next.next\n }\n pre.next = null\n const left = sortList(head)\n const right = sortList(slow)\n return merge(left, right)\n}\n\nfunction merge(left, right) {\n const dummy = new ListNode()\n let cur = dummy\n while(left && right) {\n if (left.val <= right.val) {\n cur.next = left\n left = left.next\n } else {\n cur.next = right\n right = right.next\n }\n cur = cur.next\n }\n if(left) {\n cur.next = left\n }\n\n if(right) {\n cur.next = right\n }\n\n return dummy.next\n}", " function sortList(head) {\n quickSort(head, null);\n return head;\n }\n \n function quickSort( head, tail){\n if (head == tail) {\n return;\n }\n let slow = head, fast = head.next;\n let p = head.val;\n while (fast != tail){\n if (fast.val <= p){\n slow = slow.next;\n swap(slow, fast);\n }\n fast = fast.next;\n }\n swap(head, slow);\n quickSort(head, slow);\n quickSort(slow.next, tail);\n }\n \n function swap( node1, node2){\n let tmp = node1.val;\n node1.val = node2.val;\n node2.val = tmp;\n }", "const sortList = function(head) {\n let dummy = new ListNode(0);\n dummy.next = head;\n const list = [];\n let done = (null === head);\n // Keep partitioning our list into bigger sublists length. Starting with a size of 1 and doubling each time\n for (let step = 1; !done; step *= 2) {\n done = true;\n let prev = dummy;\n let remaining = prev.next;\n do {\n // Split off two sublists of size step\n for (let i = 0; i < 2; ++i) {\n list[i] = remaining;\n let tail = null;\n for (let j = 0; j < step && null != remaining; ++j, remaining = remaining.next) {\n tail = remaining;\n }\n // Terminate our sublist\n if (null != tail) {\n tail.next = null;\n }\n }\n\n // We're done if these are the first two sublists in this pass and they\n // encompass the entire primary list\n done &= (null == remaining);\n\n // If we have two sublists, merge them into one\n if (null != list[1]) {\n while (null != list[0] || null != list[1]) {\n let idx = (null == list[1] || null != list[0] && list[0].val <= list[1].val) ? 0 : 1;\n prev.next = list[idx];\n list[idx] = list[idx].next;\n prev = prev.next;\n }\n\n // Terminate our new sublist\n prev.next = null;\n } else {\n // Only a single sublist, no need to merge, just attach to the end\n prev.next = list[0];\n }\n } while (null !== remaining);\n }\n return dummy.next;\n}" ]
149
max-points-on-a-line
[]
/** * @param {number[][]} points * @return {number} */ var maxPoints = function(points) { };
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.   Example 1: Input: points = [[1,1],[2,2],[3,3]] Output: 3 Example 2: Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] Output: 4   Constraints: 1 <= points.length <= 300 points[i].length == 2 -104 <= xi, yi <= 104 All the points are unique.
Hard
[ "array", "hash-table", "math", "geometry" ]
[ "const maxPoints = function (points) {\n if (points.length < 2 || points == null) return points.length\n let max = 2\n for (let i = 0; i < points.length; i++) {\n let [p1x, p1y] = points[i]\n let samePoint = 1,\n map = { base: 0 } // to avoid when map = {}, the max value is -Infinity\n for (let j = i + 1; j < points.length; j++) {\n if (points[i][0] == points[j][0] && points[i][1] == points[j][1]) {\n samePoint++\n } else {\n let [p2x, p2y] = points[j]\n let slope = (1000000.0 * (p2y - p1y)) / (p2x - p1x)\n if (!Number.isFinite(slope)) slope = 'v'\n else if (Number.isNaN(slope)) slope = 'h'\n map[slope] = map[slope] + 1 || 1\n }\n }\n max = Math.max(Math.max(...Object.values(map)) + samePoint, max)\n }\n return max\n}" ]
150
evaluate-reverse-polish-notation
[]
/** * @param {string[]} tokens * @return {number} */ var evalRPN = function(tokens) { };
You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation. Evaluate the expression. Return an integer that represents the value of the expression. Note that: The valid operators are '+', '-', '*', and '/'. Each operand may be an integer or another expression. The division between two integers always truncates toward zero. There will not be any division by zero. The input represents a valid arithmetic expression in a reverse polish notation. The answer and all the intermediate calculations can be represented in a 32-bit integer.   Example 1: Input: tokens = ["2","1","+","3","*"] Output: 9 Explanation: ((2 + 1) * 3) = 9 Example 2: Input: tokens = ["4","13","5","/","+"] Output: 6 Explanation: (4 + (13 / 5)) = 6 Example 3: Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22   Constraints: 1 <= tokens.length <= 104 tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
Medium
[ "array", "math", "stack" ]
[ "const evalRPN = function(tokens) {\n const stack = []\n for (let token of tokens) {\n if (token === '+') {\n stack.push(stack.pop() + stack.pop())\n } else if (token === '-') {\n stack.push(-stack.pop() + stack.pop())\n } else if (token === '*') {\n stack.push(stack.pop() * stack.pop())\n } else if (token === '/') {\n stack.push(Math.trunc((1 / stack.pop()) * stack.pop()))\n } else {\n stack.push(parseInt(token))\n }\n }\n return stack[0]\n}" ]
151
reverse-words-in-a-string
[]
/** * @param {string} s * @return {string} */ var reverseWords = function(s) { };
Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.   Example 1: Input: s = "the sky is blue" Output: "blue is sky the" Example 2: Input: s = " hello world " Output: "world hello" Explanation: Your reversed string should not contain leading or trailing spaces. Example 3: Input: s = "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.   Constraints: 1 <= s.length <= 104 s contains English letters (upper-case and lower-case), digits, and spaces ' '. There is at least one word in s.   Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?
Medium
[ "two-pointers", "string" ]
[ "const reverseWords = function(str) {\n return str\n .trim()\n .split(/\\s+/)\n .reverse()\n .join(\" \");\n};", "const reverseWords = function (s) {\n let sb = ''\n const n = s.length\n let i = n - 1\n while (i >= 0) {\n if (s.charAt(i) == ' ') {\n i--\n continue\n }\n let j = i - 1\n while (j >= 0 && s.charAt(j) != ' ') j--\n sb += ' '\n sb += s.slice(j + 1, i + 1)\n i = j - 1\n }\n if (sb.length > 0) sb = sb.slice(1)\n return sb\n}" ]
152
maximum-product-subarray
[]
/** * @param {number[]} nums * @return {number} */ var maxProduct = function(nums) { };
Given an integer array nums, find a subarray that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer.   Example 1: Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: nums = [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.   Constraints: 1 <= nums.length <= 2 * 104 -10 <= nums[i] <= 10 The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
Medium
[ "array", "dynamic-programming" ]
[ "const maxProduct = function(nums) {\n let min = nums[0], max = nums[0], res = nums[0]\n for(let i = 1, n = nums.length; i < n; i++) {\n const e = nums[i]\n if(e < 0) [min, max] = [max, min]\n min = Math.min(e, min * e)\n max = Math.max(e, max * e)\n res = Math.max(res, max)\n }\n return res\n};", "const maxProduct = function(nums) {\n let A = nums\n let r = A[0];\n\n // imax/imin stores the max/min product of\n // subarray that ends with the current number A[i]\n for (let i = 1, imax = r, imin = r, n = A.length; i < n; i++) {\n if (A[i] < 0) {\n let tmp = imax\n imax = imin\n imin = tmp\n };\n // max/min product for the current number is either the current number itself\n // or the max/min by the previous number times the current one\n imax = Math.max(A[i], imax * A[i]);\n imin = Math.min(A[i], imin * A[i]);\n\n // the newly computed max value is a candidate for our global result\n r = Math.max(r, imax);\n }\n return r;\n};", "const maxProduct = function(nums) {\n if(nums.length == 1)return nums[0];\n let dpMax = nums[0];\n let dpMin = nums[0];\n let max = nums[0];\n for (let i = 1; i < nums.length; i++) {\n let k = dpMax*nums[i];\n let m = dpMin*nums[i];\n dpMax = Math.max(nums[i], Math.max(k, m));\n dpMin = Math.min(nums[i], Math.min(k, m));\n max = Math.max(dpMax, max);\n }\n return max;\n};", "const maxProduct = function(nums) {\n const n = nums.length\n let max, min\n let res = max = min = nums[0]\n for(let i = 1; i < n; i++) {\n if(nums[i] < 0) [max, min] = [min, max]\n max = Math.max(nums[i], nums[i] * max)\n min = Math.min(nums[i], nums[i] * min)\n res = Math.max(res, max)\n }\n return res\n};", "const maxProduct = function (nums) {\n if(nums == null || nums.length === 0) return 0\n const n = nums.length\n let res = nums[0]\n for(let i = 1, min = res, max = res; i < n; i++) {\n if(nums[i] < 0) {\n let tmax = max, tmin = min\n min = Math.min(nums[i], tmax * nums[i])\n max = Math.max(nums[i], tmin * nums[i])\n } else {\n min = Math.min(nums[i], min * nums[i])\n max = Math.max(nums[i], max * nums[i])\n }\n res = Math.max(res, max)\n }\n \n return res\n}" ]
153
find-minimum-in-rotated-sorted-array
[ "Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2].", "You can divide the search space into two and see which direction to go.\r\nCan you think of an algorithm which has O(logN) search complexity?", "<ol>\r\n<li>All the elements to the left of inflection point > first element of the array.</li>\r\n<li>All the elements to the right of inflection point < first element of the array.</li>\r\n<ol>" ]
/** * @param {number[]} nums * @return {number} */ var findMin = function(nums) { };
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: [4,5,6,7,0,1,2] if it was rotated 4 times. [0,1,2,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. Given the sorted rotated array nums of unique elements, return the minimum element of this array. You must write an algorithm that runs in O(log n) time.   Example 1: Input: nums = [3,4,5,1,2] Output: 1 Explanation: The original array was [1,2,3,4,5] rotated 3 times. Example 2: Input: nums = [4,5,6,7,0,1,2] Output: 0 Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. Example 3: Input: nums = [11,13,15,17] Output: 11 Explanation: The original array was [11,13,15,17] and it was rotated 4 times.   Constraints: n == nums.length 1 <= n <= 5000 -5000 <= nums[i] <= 5000 All the integers of nums are unique. nums is sorted and rotated between 1 and n times.
Medium
[ "array", "binary-search" ]
[ "const findMin = function (nums) {\n let low = 0,\n high = nums.length - 1\n // loop invariant: 1. low < high\n // 2. mid != high and thus A[mid] != A[high] (no duplicate exists)\n // 3. minimum is between [low, high]\n // The proof that the loop will exit: after each iteration either the 'high' decreases\n // or the 'low' increases, so the interval [low, high] will always shrink.\n while (low < high) {\n const mid = low + ((high - low) >> 1)\n if (nums[mid] <= nums[high]) high = mid\n else if (nums[mid] > nums[high]) low = mid + 1\n }\n\n return nums[low]\n}" ]
154
find-minimum-in-rotated-sorted-array-ii
[]
/** * @param {number[]} nums * @return {number} */ var findMin = function(nums) { };
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: [4,5,6,7,0,1,4] if it was rotated 4 times. [0,1,4,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array. You must decrease the overall operation steps as much as possible.   Example 1: Input: nums = [1,3,5] Output: 1 Example 2: Input: nums = [2,2,2,0,1] Output: 0   Constraints: n == nums.length 1 <= n <= 5000 -5000 <= nums[i] <= 5000 nums is sorted and rotated between 1 and n times.   Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?  
Hard
[ "array", "binary-search" ]
[ "const findMin = function(nums) {\n for(let i = 1, len = nums.length; i < len; i++) {\n if(nums[i] < nums[i - 1]) {\n return nums[i]\n }\n }\n return nums[0]\n};", "const findMin = function(nums) {\n let lo = 0,\n hi = nums.length - 1\n while (lo < hi) {\n let mid = Math.floor(lo + (hi - lo) / 2)\n if (nums[mid] > nums[hi]) lo = mid + 1\n else if (nums[mid] < nums[hi]) hi = mid\n else hi--\n }\n return nums[lo]\n}" ]
155
min-stack
[ "Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan)" ]
var MinStack = function() { }; /** * @param {number} val * @return {void} */ MinStack.prototype.push = function(val) { }; /** * @return {void} */ MinStack.prototype.pop = function() { }; /** * @return {number} */ MinStack.prototype.top = function() { }; /** * @return {number} */ MinStack.prototype.getMin = function() { }; /** * Your MinStack object will be instantiated and called as such: * var obj = new MinStack() * obj.push(val) * obj.pop() * var param_3 = obj.top() * var param_4 = obj.getMin() */
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: MinStack() initializes the stack object. void push(int val) pushes the element val onto the stack. void pop() removes the element on the top of the stack. int top() gets the top element of the stack. int getMin() retrieves the minimum element in the stack. You must implement a solution with O(1) time complexity for each function.   Example 1: Input ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]] Output [null,null,null,null,-3,null,0,-2] Explanation MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2   Constraints: -231 <= val <= 231 - 1 Methods pop, top and getMin operations will always be called on non-empty stacks. At most 3 * 104 calls will be made to push, pop, top, and getMin.
Medium
[ "stack", "design" ]
[ "const MinStack = function () {\n this.stack = []\n this.min = null\n}\n\n\nMinStack.prototype.push = function (x) {\n if (this.min === null) {\n this.min = x\n } else {\n this.min = Math.min(x, this.min)\n }\n return this.stack.push(x)\n}\n\n\nMinStack.prototype.pop = function () {\n let removed = this.stack.pop()\n if (this.min === removed) {\n this.min = this.stack.length > 0 ? Math.min(...this.stack) : null\n }\n return this.stack\n}\n\n\nMinStack.prototype.top = function () {\n return this.stack[this.stack.length - 1]\n}\n\n\nMinStack.prototype.getMin = function () {\n return this.min\n}" ]
160
intersection-of-two-linked-lists
[]
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} headA * @param {ListNode} headB * @return {ListNode} */ var getIntersectionNode = function(headA, headB) { };
Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. For example, the following two linked lists begin to intersect at node c1: The test cases are generated such that there are no cycles anywhere in the entire linked structure. Note that the linked lists must retain their original structure after the function returns. Custom Judge: The inputs to the judge are given as follows (your program is not given these inputs): intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node. listA - The first linked list. listB - The second linked list. skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node. skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node. The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted.   Example 1: Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 Output: Intersected at '8' Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. Example 2: Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 Output: Intersected at '2' Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. Example 3: Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 Output: No intersection Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null.   Constraints: The number of nodes of listA is in the m. The number of nodes of listB is in the n. 1 <= m, n <= 3 * 104 1 <= Node.val <= 105 0 <= skipA < m 0 <= skipB < n intersectVal is 0 if listA and listB do not intersect. intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.   Follow up: Could you write a solution that runs in O(m + n) time and use only O(1) memory?
Easy
[ "hash-table", "linked-list", "two-pointers" ]
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */
[ "const getIntersectionNode = function(headA, headB) {\n let a = headA, b = headB\n while(a !== b) {\n a = a == null ? headB : a.next\n b = b == null ? headA : b.next\n }\n return a\n};", "const getIntersectionNode = function(headA, headB) {\n let aend = null\n let bend = null\n let ahead = headA\n let bhead = headB\n while(headA !== null && headB !== null) {\n if (aend !== null && bend !== null && aend !== bend) {\n return null\n }\n\n if (headA === headB) {\n return headA\n }\n\n if (headA.next === null) {\n if(aend === null) {\n aend = headA\n }\n headA = bhead\n } else {\n headA = headA.next\n\n }\n if (headB.next === null) {\n if(bend === null) {\n bend = headB\n }\n headB = ahead\n } else {\n headB = headB.next\n }\n\n }\n\n};" ]
162
find-peak-element
[]
/** * @param {number[]} nums * @return {number} */ var findPeakElement = function(nums) { };
A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time.   Example 1: Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2. Example 2: Input: nums = [1,2,1,3,5,6,4] Output: 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.   Constraints: 1 <= nums.length <= 1000 -231 <= nums[i] <= 231 - 1 nums[i] != nums[i + 1] for all valid i.
Medium
[ "array", "binary-search" ]
[ "const findPeakElement = function(nums) {\n let low = 0;\n let high = nums.length-1;\n\n while(low < high) {\n let mid1 = low + ((high - low) >> 1);\n let mid2 = mid1 + 1;\n if(nums[mid1] < nums[mid2]) low = mid2;\n else high = mid1;\n }\n return low;\n};", "const findPeakElement = function(nums) {\n if(nums == null) return -1\n const len = nums.length\n if(len === 1) return 0\n for(let i = 1; i < len; i++) {\n if(i === 1 && nums[i] < nums[i - 1]) return 0\n else if(i === len - 1 && nums[i] > nums[i - 1]) return len - 1\n else if(nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) return i\n }\n return -1\n};" ]
164
maximum-gap
[]
/** * @param {number[]} nums * @return {number} */ var maximumGap = function(nums) { };
Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0. You must write an algorithm that runs in linear time and uses linear extra space.   Example 1: Input: nums = [3,6,9,1] Output: 3 Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3. Example 2: Input: nums = [10] Output: 0 Explanation: The array contains less than 2 elements, therefore return 0.   Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109
Hard
[ "array", "sorting", "bucket-sort", "radix-sort" ]
[ "const maximumGap = function (nums) {\n if (nums.length < 2) return\n let max = 0\n nums = nums.sort(function (a, b) {\n return a - b\n })\n for (let i = 1; i < nums.length; i++) {\n if (nums[i] - nums[i - 1] > max) max = nums[i] - nums[i - 1]\n }\n return max\n}" ]
165
compare-version-numbers
[]
/** * @param {string} version1 * @param {string} version2 * @return {number} */ var compareVersion = function(version1, version2) { };
Given two version numbers, version1 and version2, compare them. Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers. To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1. Return the following: If version1 < version2, return -1. If version1 > version2, return 1. Otherwise, return 0.   Example 1: Input: version1 = "1.01", version2 = "1.001" Output: 0 Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1". Example 2: Input: version1 = "1.0", version2 = "1.0.0" Output: 0 Explanation: version1 does not specify revision 2, which means it is treated as "0". Example 3: Input: version1 = "0.1", version2 = "1.1" Output: -1 Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2.   Constraints: 1 <= version1.length, version2.length <= 500 version1 and version2 only contain digits and '.'. version1 and version2 are valid version numbers. All the given revisions in version1 and version2 can be stored in a 32-bit integer.
Medium
[ "two-pointers", "string" ]
[ "const compareVersion = function(version1, version2) {\n const fa = version1.split(\".\");\n const sa = version2.split(\".\");\n const len = Math.max(fa.length, sa.length);\n if (fa.length < len) {\n while (fa.length < len) {\n fa.push(\"0\");\n }\n }\n if (sa.length < len) {\n while (sa.length < len) {\n sa.push(\"0\");\n }\n }\n while (sa.length > 0 && fa.length > 0) {\n let fe = +fa.shift();\n let se = +sa.shift();\n if (fe > se) {\n return 1;\n }\n if (fe < se) {\n return -1;\n }\n }\n return 0;\n};" ]
166
fraction-to-recurring-decimal
[ "No scary math, just apply elementary math knowledge. Still remember how to perform a <i>long division</i>?", "Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?", "Notice that once the remainder starts repeating, so does the divided result.", "Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly." ]
/** * @param {number} numerator * @param {number} denominator * @return {string} */ var fractionToDecimal = function(numerator, denominator) { };
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, return any of them. It is guaranteed that the length of the answer string is less than 104 for all the given inputs.   Example 1: Input: numerator = 1, denominator = 2 Output: "0.5" Example 2: Input: numerator = 2, denominator = 1 Output: "2" Example 3: Input: numerator = 4, denominator = 333 Output: "0.(012)"   Constraints: -231 <= numerator, denominator <= 231 - 1 denominator != 0
Medium
[ "hash-table", "math", "string" ]
[ "const fractionToDecimal = function (numerator, denominator) {\n if (numerator === 0) return '0'\n let s = ''\n if (Math.sign(numerator) !== Math.sign(denominator)) s += '-'\n let n = Math.abs(numerator)\n const d = Math.abs(denominator)\n s += Math.floor(n / d)\n n %= d\n if (n === 0) return s\n s += '.'\n const map = {}\n while (n !== 0) {\n map[n] = s.length\n n *= 10\n s += Math.floor(n / d)\n n %= d\n const i = map[n] // repeat starting index\n if (i != null) return `${s.slice(0, i)}(${s.slice(i)})`\n }\n return s\n}" ]
167
two-sum-ii-input-array-is-sorted
[]
/** * @param {number[]} numbers * @param {number} target * @return {number[]} */ var twoSum = function(numbers, target) { };
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 < numbers.length. Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. The tests are generated such that there is exactly one solution. You may not use the same element twice. Your solution must use only constant extra space.   Example 1: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. Example 2: Input: numbers = [2,3,4], target = 6 Output: [1,3] Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. Example 3: Input: numbers = [-1,0], target = -1 Output: [1,2] Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].   Constraints: 2 <= numbers.length <= 3 * 104 -1000 <= numbers[i] <= 1000 numbers is sorted in non-decreasing order. -1000 <= target <= 1000 The tests are generated such that there is exactly one solution.
Medium
[ "array", "two-pointers", "binary-search" ]
[ "const twoSum = function(numbers, target) {\n const res = [];\n let remaining;\n let next = 0;\n for (let i = 0; i < numbers.length; i++) {\n remaining = target - numbers[i];\n next = i + 1;\n while (next < numbers.length && numbers[next] <= remaining) {\n if (numbers[next] === remaining) {\n res.push(i + 1, next + 1);\n break;\n }\n next += 1;\n }\n }\n\n return res;\n};" ]
168
excel-sheet-column-title
[]
/** * @param {number} columnNumber * @return {string} */ var convertToTitle = function(columnNumber) { };
Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...   Example 1: Input: columnNumber = 1 Output: "A" Example 2: Input: columnNumber = 28 Output: "AB" Example 3: Input: columnNumber = 701 Output: "ZY"   Constraints: 1 <= columnNumber <= 231 - 1
Easy
[ "math", "string" ]
[ "const convertToTitle = function(n) {\n if (n === 0) {\n return ''\n }\n const res = [];\n const hash = {};\n ('ABCDEFGHIJKLMNOPQRSTUVWXYZ').split('').forEach((el,idx) => {\n hash[idx] = el\n })\n \n while(n > 0) {\n n--;\n res.unshift(hash[n % 26]);\n n = Math.floor(n / 26);\n }\n\n return res.join('')\n};" ]
169
majority-element
[]
/** * @param {number[]} nums * @return {number} */ var majorityElement = function(nums) { };
Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.   Example 1: Input: nums = [3,2,3] Output: 3 Example 2: Input: nums = [2,2,1,1,1,2,2] Output: 2   Constraints: n == nums.length 1 <= n <= 5 * 104 -109 <= nums[i] <= 109   Follow-up: Could you solve the problem in linear time and in O(1) space?
Easy
[ "array", "hash-table", "divide-and-conquer", "sorting", "counting" ]
[ "const majorityElement = function(nums) {\n const hash = {};\n nums.forEach(el => {\n if (hash.hasOwnProperty(el)) {\n hash[el] += 1;\n } else {\n hash[el] = 1;\n }\n });\n return Object.entries(hash)\n .filter(el => el[1] > Math.floor(nums.length / 2))\n .map(el => +el[0])\n .sort((a, b) => b - a)[0];\n};", "const majorityElement = function(nums) {\n let cnt = 1, candidate = nums[0]\n for(let i = 1, n = nums.length; i < n; i++) {\n if(candidate === nums[i]) cnt++\n else cnt--\n if(cnt === 0) {\n cnt = 1\n candidate = nums[i]\n }\n }\n return candidate\n};", "const majorityElement = function(nums) {\n let cnt = 1, candidate = nums[0]\n for(let i = 1, n = nums.length; i < n; i++) {\n if(cnt === 0) {\n cnt = 1\n candidate = nums[i]\n }else if(candidate === nums[i]) cnt++\n else cnt--\n }\n return candidate\n};" ]
171
excel-sheet-column-number
[]
/** * @param {string} columnTitle * @return {number} */ var titleToNumber = function(columnTitle) { };
Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...   Example 1: Input: columnTitle = "A" Output: 1 Example 2: Input: columnTitle = "AB" Output: 28 Example 3: Input: columnTitle = "ZY" Output: 701   Constraints: 1 <= columnTitle.length <= 7 columnTitle consists only of uppercase English letters. columnTitle is in the range ["A", "FXSHRXW"].
Easy
[ "math", "string" ]
[ "const titleToNumber = function(s) {\n const arr = s.split(\"\");\n const len = arr.length;\n const uac = \"A\".charCodeAt(0);\n return arr.reduce((ac, el, idx, arr) => {\n return ac + Math.pow(26, len - idx - 1) * (`${el}`.charCodeAt(0) - uac + 1);\n }, 0);\n};\n\nconsole.log(titleToNumber(\"A\"));\nconsole.log(titleToNumber(\"AA\"));", "const titleToNumber = function(s) {\n let result = 0;\n const A = 'A'.charCodeAt(0)\n for (let i = 0; i < s.length; result = result * 26 + (s.charCodeAt(i) - A + 1), i++);\n return result;\n};" ]
172
factorial-trailing-zeroes
[]
/** * @param {number} n * @return {number} */ var trailingZeroes = function(n) { };
Given an integer n, return the number of trailing zeroes in n!. Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.   Example 1: Input: n = 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: n = 5 Output: 1 Explanation: 5! = 120, one trailing zero. Example 3: Input: n = 0 Output: 0   Constraints: 0 <= n <= 104   Follow up: Could you write a solution that works in logarithmic time complexity?
Medium
[ "math" ]
[ "const trailingZeroes = function(n) {\n let result = 0;\n for(let i = 5; Math.floor(n/i) > 0; i *= 5){\n result += (Math.floor(n/i));\n }\n return result;\n};" ]
173
binary-search-tree-iterator
[]
/** * 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 */ var BSTIterator = function(root) { }; /** * @return {number} */ BSTIterator.prototype.next = function() { }; /** * @return {boolean} */ BSTIterator.prototype.hasNext = function() { }; /** * Your BSTIterator object will be instantiated and called as such: * var obj = new BSTIterator(root) * var param_1 = obj.next() * var param_2 = obj.hasNext() */
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST. boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false. int next() Moves the pointer to the right, then returns the number at the pointer. Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST. You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.   Example 1: Input ["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"] [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] Output [null, 3, 7, true, 9, true, 15, true, 20, false] Explanation BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False   Constraints: The number of nodes in the tree is in the range [1, 105]. 0 <= Node.val <= 106 At most 105 calls will be made to hasNext, and next.   Follow up: Could you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?
Medium
[ "stack", "tree", "design", "binary-search-tree", "binary-tree", "iterator" ]
/** * 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 BSTIterator = function(root) {\n this.root = root;\n this.stack = [];\n};\n\n\nBSTIterator.prototype.next = function() {\n while (this.root) {\n this.stack.push(this.root);\n this.root = this.root.left;\n }\n this.root = this.stack.pop();\n const result = this.root.val;\n this.root = this.root.right;\n return result;\n};\n\n\nBSTIterator.prototype.hasNext = function() {\n return this.root || this.stack.length;\n};", "const BSTIterator = function(root) {\n this.generator = dfsGenerator(root)\n this.root = root\n this.nextSmall = this.generator.next().value\n}\nfunction* dfsGenerator(root) {\n if (root === null) return\n const stack = []\n let current = root\n while (true) {\n if (current) {\n stack.push(current)\n current = current.left\n } else if (stack.length) {\n const top = stack.pop()\n yield top.val\n current = top.right\n } else {\n break\n }\n }\n}\n\n\nBSTIterator.prototype.next = function() {\n const smallReturn = this.nextSmall\n this.nextSmall = this.generator.next().value\n return smallReturn\n}\n\n\nBSTIterator.prototype.hasNext = function() {\n return this.nextSmall !== undefined ? true : false\n}" ]
174
dungeon-game
[]
/** * @param {number[][]} dungeon * @return {number} */ var calculateMinimumHP = function(dungeon) { };
The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. Return the knight's minimum initial health so that he can rescue the princess. Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.   Example 1: Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] Output: 7 Explanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN. Example 2: Input: dungeon = [[0]] Output: 1   Constraints: m == dungeon.length n == dungeon[i].length 1 <= m, n <= 200 -1000 <= dungeon[i][j] <= 1000
Hard
[ "array", "dynamic-programming", "matrix" ]
[ "const calculateMinimumHP = function (dungeon) {\n const M = dungeon.length\n const N = dungeon[0].length\n // hp[i][j] represents the min hp needed at position (i, j)\n // Add dummy row and column at bottom and right side\n const hp = Array.from({ length: M + 1 }, () =>\n Array(N + 1).fill(Number.MAX_VALUE)\n )\n hp[M][N - 1] = 1\n hp[M - 1][N] = 1\n for (let i = M - 1; i >= 0; i--) {\n for (let j = N - 1; j >= 0; j--) {\n const need = Math.min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j]\n hp[i][j] = need <= 0 ? 1 : need\n }\n }\n return hp[0][0]\n}", "const calculateMinimumHP = function (dungeon) {\n const n = dungeon.length,\n m = dungeon[0].length\n const dp = Array(n + 1).fill(Number.MAX_VALUE)\n dp[n - 1] = 1\n for (let j = m - 1; j >= 0; j--) {\n for (let i = n - 1; i >= 0; i--) {\n dp[i] = Math.min(dp[i], dp[i + 1]) - dungeon[i][j]\n dp[i] = Math.max(1, dp[i])\n }\n }\n return dp[0]\n}" ]
179
largest-number
[]
/** * @param {number[]} nums * @return {string} */ var largestNumber = function(nums) { };
Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer.   Example 1: Input: nums = [10,2] Output: "210" Example 2: Input: nums = [3,30,34,5,9] Output: "9534330"   Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 109
Medium
[ "array", "string", "greedy", "sorting" ]
[ "const largestNumber = function(nums) {\n const arr = nums\n .map(v => v.toString())\n .sort((a, b) => (a + b < b + a ? 1 : -1))\n .join(\"\");\n\n return arr[0] === \"0\" ? \"0\" : arr;\n};" ]
187
repeated-dna-sequences
[]
/** * @param {string} s * @return {string[]} */ var findRepeatedDnaSequences = function(s) { };
The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'. For example, "ACGAATTCCG" is a DNA sequence. When studying DNA, it is useful to identify repeated sequences within the DNA. Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.   Example 1: Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" Output: ["AAAAACCCCC","CCCCCAAAAA"] Example 2: Input: s = "AAAAAAAAAAAAA" Output: ["AAAAAAAAAA"]   Constraints: 1 <= s.length <= 105 s[i] is either 'A', 'C', 'G', or 'T'.
Medium
[ "hash-table", "string", "bit-manipulation", "sliding-window", "rolling-hash", "hash-function" ]
[ "const findRepeatedDnaSequences = function(s) {\n if (!s || s.length < 10) {\n return [];\n }\n const map = new Map([[\"A\", 0], [\"C\", 1], [\"G\", 2], [\"T\", 3]]);\n const dna = new Set();\n const repeated = new Set();\n const mask = 0xfffff;\n let cur = 0;\n for (let i = 0, n = s.length; i < n; i++) {\n cur <<= 2;\n cur = cur | map.get(s[i]);\n cur = cur & mask;\n if (i >= 9) {\n if (dna.has(cur)) {\n const seq = s.slice(i - 9, i + 1);\n if (!repeated.has(seq)) {\n repeated.add(seq);\n }\n } else {\n dna.add(cur);\n }\n }\n }\n return Array.from(repeated);\n};", "const findRepeatedDnaSequences = function(s) {\n let store = new Set(), result = new Set()\n for(let i = 0; i < s.length - 9; i++) {\n const str = s.substring(i, i + 10)\n if(store.has(str)) {\n result.add(str)\n } else {\n store.add(str)\n }\n }\n return Array.from(result)\n};" ]
188
best-time-to-buy-and-sell-stock-iv
[]
/** * @param {number} k * @param {number[]} prices * @return {number} */ var maxProfit = function(k, prices) { };
You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k. Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).   Example 1: Input: k = 2, prices = [2,4,1] Output: 2 Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. Example 2: Input: k = 2, prices = [3,2,6,5,0,3] Output: 7 Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Constraints: 1 <= k <= 100 1 <= prices.length <= 1000 0 <= prices[i] <= 1000
Hard
[ "array", "dynamic-programming" ]
[ "const maxProfit = function(k, prices) {\n if (!prices.length) return 0\n let len = prices.length,\n res = 0\n if (k >= ~~(len / 2)) {\n for (let i = 1; i < len; i++) {\n res += Math.max(prices[i] - prices[i - 1], 0)\n }\n return res\n }\n const buy = new Array(k + 1).fill(Number.MIN_SAFE_INTEGER)\n const sell = new Array(k + 1).fill(0)\n\n for (let p of prices) {\n for (let i = 1; i <= k; i++) {\n buy[i] = Math.max(sell[i - 1] - p, buy[i])\n sell[i] = Math.max(buy[i] + p, sell[i])\n }\n }\n return sell[k]\n}", "const maxProfit = function(k, prices) {\n if(prices.length === 0) return 0\n \n if(k > (prices.length/2)) {\n let profit = 0\n for(let i = 1; i < prices.length; i++) {\n if(prices[i] > prices[i-1]) profit += prices[i] - prices[i-1]\n }\n return profit\n } else {\n let dp = new Array(prices.length).fill(0)\n let length = prices.length\n for(let j = 0; j < k; j++) {\n let min = prices[0], max = 0\n for(let i = 0; i < length; i++) {\n min = Math.min(min, prices[i] - dp[i])\n max = Math.max(max, prices[i] - min)\n dp[i] = max\n }\n }\n return dp.pop()\n }\n}\n\n // another\n\n\nconst maxProfit = function(k, prices) {\n if (k >= prices.length / 2) {\n let max = 0;\n for(let i = 1; i < prices.length; i++) {\n if (prices[i] > prices[i - 1]) {\n max += prices[i] - prices[i - 1];\n }\n }\n return max;\n }\n if (prices.length === 0) return 0;\n let dp = new Array(k + 1);\n dp[0] = new Array(prices.length).fill(0);\n for (let t = 1; t <= k; t++) {\n dp[t] = [0];\n let max = dp[t - 1][0] - prices[0];\n for (let day = 1; day < prices.length; day++) {\n dp[t][day] = Math.max(dp[t][day - 1], max + prices[day]);\n max = Math.max(max, dp[t - 1][day] - prices[day]);\n }\n }\n return dp[k][prices.length - 1];\n}" ]
189
rotate-array
[ "The easiest solution would use additional memory and that is perfectly fine.", "The actual trick comes when trying to solve this problem without using any additional memory. This means you need to use the original array somehow to move the elements around. Now, we can place each element in its original location and shift all the elements around it to adjust as that would be too costly and most likely will time out on larger input arrays.", "One line of thought is based on reversing the array (or parts of it) to obtain the desired result. Think about how reversal might potentially help us out by using an example.", "The other line of thought is a tad bit complicated but essentially it builds on the idea of placing each element in its original position while keeping track of the element originally in that position. Basically, at every step, we place an element in its rightful position and keep track of the element already there or the one being overwritten in an additional variable. We can't do this in one linear pass and the idea here is based on <b>cyclic-dependencies</b> between elements." ]
/** * @param {number[]} nums * @param {number} k * @return {void} Do not return anything, modify nums in-place instead. */ var rotate = function(nums, k) { };
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.   Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]   Constraints: 1 <= nums.length <= 105 -231 <= nums[i] <= 231 - 1 0 <= k <= 105   Follow up: Try to come up with as many solutions as you can. There are at least three different ways to solve this problem. Could you do it in-place with O(1) extra space?
Medium
[ "array", "math", "two-pointers" ]
[ "const rotate = function(nums, k) {\n nums.unshift(...nums.splice(nums.length - k))\n};", "const rotate = function(nums, k) {\n let i = k\n while (i > 0) {\n nums.unshift(nums.pop())\n i--\n }\n};", "const rotate = function(nums, k) {\n k %= nums.length\n reverse(nums, 0, nums.length - 1)\n reverse(nums, 0, k - 1)\n reverse(nums, k, nums.length - 1)\n}\n\nfunction reverse(nums, start, end) {\n while (start < end) {\n var temp = nums[start]\n nums[start] = nums[end]\n nums[end] = temp\n start++\n end--\n }\n}" ]
190
reverse-bits
[]
/** * @param {number} n - a positive integer * @return {number} - a positive integer */ var reverseBits = function(n) { };
Reverse bits of a given 32 bits unsigned integer. Note: Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.   Example 1: Input: n = 00000010100101000001111010011100 Output: 964176192 (00111001011110000010100101000000) Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000. Example 2: Input: n = 11111111111111111111111111111101 Output: 3221225471 (10111111111111111111111111111111) Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.   Constraints: The input must be a binary string of length 32   Follow up: If this function is called many times, how would you optimize it?
Easy
[ "divide-and-conquer", "bit-manipulation" ]
[ "const reverseBits = function(n) {\n let r = 0;\n for (let i = 0; i < 32; i++) {\n if (n & 1) {\n r = r | 1;\n } \n if (i !== 31) {\n r = r << 1;\n n = n >> 1;\n }\n }\n return r >>> 0;\n};", "const reverseBits = function(n) {\n let s = '';\n let count = 0;\n let index = 31;\n while (n > 0) {\n if (n % 2 !== 0) count += Math.pow(2, index);\n index--;\n n = Math.floor(n / 2);\n }\n return count;\n};", "const reverseBits = function(n) {\n const b = n.toString(2)\n const leadingZeroes = b.padStart(32,'0')\n const rev = leadingZeroes.split('')\n rev.reverse()\n return parseInt(rev.join(''), 2)\n};" ]
191
number-of-1-bits
[]
/** * @param {number} n - a positive integer * @return {number} */ var hammingWeight = function(n) { };
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). Note: Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.   Example 1: Input: n = 00000000000000000000000000001011 Output: 3 Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits. Example 2: Input: n = 00000000000000000000000010000000 Output: 1 Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit. Example 3: Input: n = 11111111111111111111111111111101 Output: 31 Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.   Constraints: The input must be a binary string of length 32.   Follow up: If this function is called many times, how would you optimize it?
Easy
[ "divide-and-conquer", "bit-manipulation" ]
[ "const hammingWeight = function(n) {\n let res = 0\n while(n > 0) {\n if(n & 1) res++\n n = n >>> 1\n }\n return res\n};", "const hammingWeight = function(n) {\n const str = (n >>> 0).toString(2)\n let res = 0\n for(let c of str) {\n if(c === '1') res++\n }\n return res\n};" ]
198
house-robber
[]
/** * @param {number[]} nums * @return {number} */ var rob = function(nums) { };
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.   Example 1: Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. Example 2: Input: nums = [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.   Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 400
Medium
[ "array", "dynamic-programming" ]
[ "function rob(nums) {\n if (nums.length == 0) return 0;\n let prev1 = 0;\n let prev2 = 0;\n for (let num of nums) {\n let tmp = prev1;\n prev1 = Math.max(prev2 + num, prev1);\n prev2 = tmp;\n }\n return prev1;\n}", "const rob = function(nums) {\n const n = nums.length\n const dp = Array(n+1).fill(0)\n dp[1] = nums[0] \n \n for(let i = 1; i < n; i++) {\n dp[i + 1] = Math.max(dp[i], dp[i - 1] + nums[i])\n }\n \n return dp[n]\n};" ]
199
binary-tree-right-side-view
[]
/** * 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 rightSideView = function(root) { };
Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.   Example 1: Input: root = [1,2,3,null,5,null,4] Output: [1,3,4] Example 2: Input: root = [1,null,3] Output: [1,3] Example 3: Input: root = [] Output: []   Constraints: The number of nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100
Medium
[ "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 rightSideView = function(root) {\n if(root == null) return []\n const queue = [root]\n const res = []\n while(queue.length) {\n const len = queue.length\n for(let i = 0; i < len; i++) {\n const el = queue.shift()\n if(i === len - 1) res.push(el.val)\n if(el.left) queue.push(el.left)\n if(el.right) queue.push(el.right)\n }\n }\n return res\n};", "const rightSideView = function(root) {\n const res = []\n const helper = function(node, level) {\n if (!node) {\n return\n }\n if (!res[level]) {\n res.push(node.val)\n }\n helper(node.right, level + 1)\n helper(node.left, level + 1)\n }\n helper(root, 0)\n return res\n}" ]
200
number-of-islands
[]
/** * @param {character[][]} grid * @return {number} */ var numIslands = function(grid) { };
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.   Example 1: Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1 Example 2: Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] Output: 3   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 300 grid[i][j] is '0' or '1'.
Medium
[ "array", "depth-first-search", "breadth-first-search", "union-find", "matrix" ]
[ "const numIslands = function(grid) {\n if (grid.length === 0) return 0;\n const totalRow = grid.length;\n const totalCol = grid[0].length;\n let res = 0;\n \n for (let i = 0; i < totalRow; i += 1) {\n for (let j = 0; j < totalCol; j += 1) {\n if (grid[i][j] === '1') {\n res += 1;\n dfs(grid, i, j, totalRow, totalCol);\n }\n }\n }\n \n return res;\n};\n\nconst dfs = (grid, row, col, totalRow, totalCol) => {\n if (row < 0 || col < 0 || row === totalRow || col === totalCol || grid[row][col] === '0') {\n return;\n }\n \n grid[row][col] = '0';\n dfs(grid, row - 1, col, totalRow, totalCol);\n dfs(grid, row + 1, col, totalRow, totalCol);\n dfs(grid, row, col - 1, totalRow, totalCol);\n dfs(grid, row, col + 1, totalRow, totalCol);\n}" ]
201
bitwise-and-of-numbers-range
[]
/** * @param {number} left * @param {number} right * @return {number} */ var rangeBitwiseAnd = function(left, right) { };
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.   Example 1: Input: left = 5, right = 7 Output: 4 Example 2: Input: left = 0, right = 0 Output: 0 Example 3: Input: left = 1, right = 2147483647 Output: 0   Constraints: 0 <= left <= right <= 231 - 1
Medium
[ "bit-manipulation" ]
[ "const rangeBitwiseAnd = function(m, n) {\n while(m<n) n = n & (n-1);\n return n;\n};", "const rangeBitwiseAnd = function(m, n) {\n let s = 0\n while(m !== n) {\n m >>= 1\n n >>= 1\n s++\n }\n return m << s\n};" ]
202
happy-number
[]
/** * @param {number} n * @return {boolean} */ var isHappy = function(n) { };
Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy. Return true if n is a happy number, and false if not.   Example 1: Input: n = 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 Example 2: Input: n = 2 Output: false   Constraints: 1 <= n <= 231 - 1
Easy
[ "hash-table", "math", "two-pointers" ]
[ "const isHappy = function(n) {\n const arr = [];\n let tmp = n;\n while (arr.indexOf(tmp) === -1) {\n arr.push(tmp);\n let res = (\"\" + tmp)\n .split(\"\")\n .reduce((ac, str) => ac + Math.pow(+str, 2), 0);\n if (res === 1) {\n return true;\n }\n tmp = res;\n }\n return false;\n};" ]
203
remove-linked-list-elements
[]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @param {number} val * @return {ListNode} */ var removeElements = function(head, val) { };
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.   Example 1: Input: head = [1,2,6,3,4,5,6], val = 6 Output: [1,2,3,4,5] Example 2: Input: head = [], val = 1 Output: [] Example 3: Input: head = [7,7,7,7], val = 7 Output: []   Constraints: The number of nodes in the list is in the range [0, 104]. 1 <= Node.val <= 50 0 <= val <= 50
Easy
[ "linked-list", "recursion" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "const removeElements = function(head, val) {\n const dummy = new ListNode(Infinity)\n if(head == null) return null\n dummy.next = head\n let cur = head\n let prev = dummy\n while(cur) {\n if(cur.val === val) {\n prev.next = cur.next\n cur = cur.next\n } else {\n prev = cur\n cur = cur.next\n }\n }\n return dummy.next\n};", "const removeElements = function(head, val) {\n if (head === null) return null;\n head.next = removeElements(head.next, val);\n return head.val === val ? head.next : head;\n};" ]
204
count-primes
[ "Checking all the integers in the range [1, n - 1] is not efficient. Think about a better approach.", "Since most of the numbers are not primes, we need a fast approach to exclude the non-prime integers.", "Use Sieve of Eratosthenes." ]
/** * @param {number} n * @return {number} */ var countPrimes = function(n) { };
Given an integer n, return the number of prime numbers that are strictly less than n.   Example 1: Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. Example 2: Input: n = 0 Output: 0 Example 3: Input: n = 1 Output: 0   Constraints: 0 <= n <= 5 * 106
Medium
[ "array", "math", "enumeration", "number-theory" ]
[ "const countPrimes = function (n) {\n const memo = Array(n).fill(false)\n let res = 0\n for (let i = 2; i < n; i++) {\n if (memo[i] === false) {\n res++\n for (let j = 2; i * j < n; j++) {\n memo[i * j] = true\n }\n }\n }\n\n return res\n}", "const countPrimes = function(n) {\n \n if (n < 3) return 0;\n\n \n let c = Math.floor(n / 2);\n\n \n let s = [];\n\n \n for (let i = 3; i * i < n; i += 2) {\n if (s[i]) {\n // c has already been decremented for this composite odd\n continue;\n }\n\n \n for (let j = i * i; j < n; j += 2 * i) {\n if (!s[j]) {\n c--;\n s[j] = true;\n }\n }\n }\n return c;\n};" ]
205
isomorphic-strings
[]
/** * @param {string} s * @param {string} t * @return {boolean} */ var isIsomorphic = function(s, t) { };
Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.   Example 1: Input: s = "egg", t = "add" Output: true Example 2: Input: s = "foo", t = "bar" Output: false Example 3: Input: s = "paper", t = "title" Output: true   Constraints: 1 <= s.length <= 5 * 104 t.length == s.length s and t consist of any valid ascii character.
Easy
[ "hash-table", "string" ]
[ "const isIsomorphic = function(s, t) {\n if (s.length !== t.length) {\n return false;\n }\n const smap = {};\n const tmap = {};\n\n for (let i = 0; i < s.length; i++) {\n if (!smap.hasOwnProperty(s[i])) {\n smap[s[i]] = t[i];\n }\n if (!tmap.hasOwnProperty(t[i])) {\n tmap[t[i]] = s[i];\n }\n\n if (smap[s[i]] !== t[i] || tmap[t[i]] !== s[i]) return false;\n\n }\n\n return true;\n};" ]
206
reverse-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 reverseList = function(head) { };
Given the head of a singly linked list, reverse the list, and return the reversed list.   Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: Input: head = [1,2] Output: [2,1] Example 3: Input: head = [] Output: []   Constraints: The number of nodes in the list is the range [0, 5000]. -5000 <= Node.val <= 5000   Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
Easy
[ "linked-list", "recursion" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "const reverseList = function(head) {\n if(head == null) return head\n const pre = new ListNode(null, head)\n let cur = head\n while(cur.next) {\n const tmp = pre.next\n pre.next = cur.next\n cur.next = cur.next.next\n pre.next.next = tmp\n }\n\n return pre.next\n};", "const reverseList = function(head) {\n let prev = null;\n let cur = head;\n let tmp;\n let tmpNext;\n while (cur !== null) {\n tmp = cur;\n tmpNext = cur.next;\n cur.next = prev;\n prev = tmp;\n cur = tmpNext;\n }\n\n return prev;\n};" ]
207
course-schedule
[ "This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.", "<a href=\"https://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/03Graphs.pdf\" target=\"_blank\">Topological Sort via DFS</a> - A great tutorial explaining the basic concepts of Topological Sort.", "Topological sort could also be done via <a href=\"http://en.wikipedia.org/wiki/Topological_sorting#Algorithms\" target=\"_blank\">BFS</a>." ]
/** * @param {number} numCourses * @param {number[][]} prerequisites * @return {boolean} */ var canFinish = function(numCourses, prerequisites) { };
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return true if you can finish all courses. Otherwise, return false.   Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2: Input: numCourses = 2, prerequisites = [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.   Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= 5000 prerequisites[i].length == 2 0 <= ai, bi < numCourses All the pairs prerequisites[i] are unique.
Medium
[ "depth-first-search", "breadth-first-search", "graph", "topological-sort" ]
[ "const canFinish = function (numCourses, prerequisites) {\n const set = new Set()\n const indegree = Array(numCourses).fill(0)\n const graph = {}\n\n for (const [s, e] of prerequisites) {\n indegree[e]++\n if (graph[s] == null) graph[s] = []\n graph[s].push(e)\n }\n\n let q = []\n for (let i = 0; i < numCourses; i++) {\n if (indegree[i] === 0) q.push(i)\n }\n\n while (q.length) {\n const nxt = []\n for (let i = 0, size = q.length; i < size; i++) {\n const cur = q[i]\n set.add(cur)\n for (const e of graph[cur] || []) {\n indegree[e]--\n if (indegree[e] === 0 && !set.has(e)) {\n nxt.push(e)\n }\n }\n }\n\n q = nxt\n }\n\n return set.size === numCourses\n}", "const canFinish = function(numCourses, prerequisites) {\n const [graph, inDegree] = buildGraph(numCourses, prerequisites)\n \n const q = []\n for(let i = 0; i < numCourses; i++) {\n if(inDegree.get(i) == null) q.push(i)\n }\n let num = 0\n while(q.length) {\n const pre = q.pop()\n num++\n for(const next of (graph.get(pre) || [])) {\n inDegree.set(next, inDegree.get(next) - 1)\n if(inDegree.get(next) === 0) q.push(next)\n }\n }\n return num === numCourses\n \n \n function buildGraph(n, arr) {\n const res = new Map(), inDegree = new Map()\n for(const [cur, pre] of arr) {\n if(res.get(pre) == null) res.set(pre, new Set())\n res.get(pre).add(cur)\n if(inDegree.get(cur) == null) inDegree.set(cur, 0)\n inDegree.set(cur, inDegree.get(cur) + 1)\n }\n return [res, inDegree]\n }\n};", "const canFinish = function(numCourses, prerequisites) {\n const seen = new Set()\n const seeing = new Set()\n const adj = [...Array(numCourses)].map(r => [])\n for (let [u, v] of prerequisites) {\n adj[v].push(u)\n }\n for (let c = 0; c < numCourses; c++) {\n if (!dfs(c)) {\n return false\n }\n }\n return true\n function dfs(v) {\n if (seen.has(v)) return true\n if (seeing.has(v)) return false\n seeing.add(v)\n for (let nv of adj[v]) {\n if (!dfs(nv)) {\n return false\n }\n }\n seeing.delete(v)\n seen.add(v)\n return true\n }\n}", "const canFinish = function(vertices, edges) {\n const sortedOrder = []\n if (vertices <= 0) {\n return sortedOrder\n }\n const inDegree = Array(vertices).fill(0)\n const graph = Array(vertices)\n .fill(0)\n .map(() => Array())\n edges.forEach(edge => {\n let parent = edge[0]\n let child = edge[1]\n graph[parent].push(child)\n inDegree[child]++\n })\n const sources = []\n for (let i = 0; i < inDegree.length; i++) {\n if (inDegree[i] === 0) {\n sources.push(i)\n }\n }\n while (sources.length > 0) {\n const vertex = sources.shift()\n sortedOrder.push(vertex)\n\n graph[vertex].forEach(child => {\n inDegree[child] -= 1\n if (inDegree[child] === 0) {\n sources.push(child)\n }\n })\n }\n return sortedOrder.length === vertices ? true : false\n}", "const canFinish = function(numCourses, prerequisites) {\n const set = new Set(), hash = {}\n for(let i = 0; i < prerequisites.length; i++) {\n const [cur, pre] = prerequisites[i]\n if(hash[cur] == null) hash[cur] = new Set()\n hash[cur].add(pre)\n }\n const q = []\n\n for(let i = 0; i < numCourses; i++) {\n if(hash[i] == null) q.push(i)\n }\n let visited = 0\n\n while(q.length) {\n const cur = q.shift()\n visited++\n Object.keys(hash).forEach(k => {\n if(hash[k].has(cur)) {\n hash[k].delete(cur)\n }\n if(hash[k].size === 0) {\n delete hash[k]\n q.push(+k)\n }\n })\n }\n return visited === numCourses\n};" ]
208
implement-trie-prefix-tree
[]
var Trie = function() { }; /** * @param {string} word * @return {void} */ Trie.prototype.insert = function(word) { }; /** * @param {string} word * @return {boolean} */ Trie.prototype.search = function(word) { }; /** * @param {string} prefix * @return {boolean} */ Trie.prototype.startsWith = function(prefix) { }; /** * Your Trie object will be instantiated and called as such: * var obj = new Trie() * obj.insert(word) * var param_2 = obj.search(word) * var param_3 = obj.startsWith(prefix) */
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class: Trie() Initializes the trie object. void insert(String word) Inserts the string word into the trie. boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise. boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.   Example 1: Input ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] Output [null, null, true, false, true, null, true] Explanation Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // return True trie.search("app"); // return False trie.startsWith("app"); // return True trie.insert("app"); trie.search("app"); // return True   Constraints: 1 <= word.length, prefix.length <= 2000 word and prefix consist only of lowercase English letters. At most 3 * 104 calls in total will be made to insert, search, and startsWith.
Medium
[ "hash-table", "string", "design", "trie" ]
[ "const Trie = function() {\n this.root = {}\n};\n\n\nTrie.prototype.insert = function(word) {\n let curr = this.root\n word.split('').forEach(ch => (curr = curr[ch] = curr[ch] || {}))\n curr.isWord = true\n};\n\n\nTrie.prototype.search = function(word) {\n let node = this.traverse(word)\n return !!node && !!node.isWord \n};\n\n\nTrie.prototype.startsWith = function(prefix) {\n return !!this.traverse(prefix) \n};\n\n\n\nTrie.prototype.traverse = function(word) {\n let curr = this.root\n for (let i = 0; i < word.length; i++) {\n if (!curr) return null\n curr = curr[word[i]]\n }\n return curr\n}", "class Trie {\n constructor() {\n this.links = new Map();\n this.isWord = false;\n }\n insert(word) {\n let node = this;\n for (const c of word) {\n if (!node.links.has(c)) node.links.set(c, new Trie());\n node = node.links.get(c);\n }\n node.isWord = true;\n }\n search(word) {\n const node = this.traverse(word);\n return node ? node.isWord : false;\n }\n startsWith(prefix) {\n const node = this.traverse(prefix);\n return node !== null;\n }\n traverse(word) {\n let node = this;\n for (const c of word) {\n if (node.links.has(c)) node = node.links.get(c);\n else return null;\n }\n return node;\n }\n}", "const Trie = function () {\n this.root = new Node(null)\n}\n\n\nTrie.prototype.insert = function (word) {\n let cur = this.root\n for (let i = 0, len = word.length; i < len; i++) {\n if (!cur.children.has(word[i])) cur.children.set(word[i], new Node(null))\n cur = cur.children.get(word[i])\n if (i === len - 1) cur.word = true\n }\n}\n\n\nTrie.prototype.search = function (word) {\n let cur = this.root\n for (let i = 0, len = word.length; i < len; i++) {\n if (cur.children.has(word[i])) cur = cur.children.get(word[i])\n else return false\n if (i === len - 1) return cur.word === true\n }\n}\n\n\nTrie.prototype.startsWith = function (prefix) {\n let cur = this.root\n for (let i = 0, len = prefix.length; i < len; i++) {\n if (cur.children.has(prefix[i])) cur = cur.children.get(prefix[i])\n else return false\n if (i === len - 1) return true\n }\n}\n\nclass Node {\n constructor(v) {\n this.val = v\n this.word = false\n this.children = new Map()\n }\n}" ]
209
minimum-size-subarray-sum
[]
/** * @param {number} target * @param {number[]} nums * @return {number} */ var minSubArrayLen = function(target, nums) { };
Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.   Example 1: Input: target = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: The subarray [4,3] has the minimal length under the problem constraint. Example 2: Input: target = 4, nums = [1,4,4] Output: 1 Example 3: Input: target = 11, nums = [1,1,1,1,1,1,1,1] Output: 0   Constraints: 1 <= target <= 109 1 <= nums.length <= 105 1 <= nums[i] <= 104   Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)).
Medium
[ "array", "binary-search", "sliding-window", "prefix-sum" ]
[ "const minSubArrayLen = function(s, nums) {\n let sum = 0, from = 0, win = Number.MAX_SAFE_INTEGER;\n for (let i = 0; i < nums.length; i++) {\n sum += nums[i];\n while (sum >= s) {\n win = Math.min(win, i - from + 1);\n sum -= nums[from++];\n }\n }\n return (win === Number.MAX_SAFE_INTEGER) ? 0 : win;\n};" ]
210
course-schedule-ii
[ "This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.", "<a href=\"https://class.coursera.org/algo-003/lecture/52\" target=\"_blank\">Topological Sort via DFS</a> - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.", "Topological sort could also be done via <a href=\"http://en.wikipedia.org/wiki/Topological_sorting#Algorithms\" target=\"_blank\">BFS</a>." ]
/** * @param {number} numCourses * @param {number[][]} prerequisites * @return {number[]} */ var findOrder = function(numCourses, prerequisites) { };
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.   Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: [0,1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. Example 2: Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0,2,1,3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. Example 3: Input: numCourses = 1, prerequisites = [] Output: [0]   Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= numCourses * (numCourses - 1) prerequisites[i].length == 2 0 <= ai, bi < numCourses ai != bi All the pairs [ai, bi] are distinct.
Medium
[ "depth-first-search", "breadth-first-search", "graph", "topological-sort" ]
[ "const findOrder = function(numCourses, prerequisites) {\n const graph = {}, inDegree = Array(numCourses).fill(0)\n for(const [s, e] of prerequisites) {\n inDegree[s]++\n if(graph[e] == null) graph[e] = []\n graph[e].push(s)\n }\n \n const res = []\n let q = []\n for(let i = 0; i < numCourses; i++) {\n if(inDegree[i] === 0) q.push(i)\n }\n \n while(q.length) {\n const nxt = []\n for(let i = 0; i < q.length; i++) {\n const cur = q[i]\n res.push(cur)\n for(const e of (graph[cur] || [])) {\n inDegree[e]--\n if(inDegree[e] === 0) nxt.push(e)\n }\n }\n q = nxt\n }\n \n return res.length === numCourses ? res : []\n}", "const findOrder = function(numCourses, prerequisites) {\n const indegree = new Array(numCourses).fill(0)\n const graph = {}\n for (let [course, prereq] of prerequisites) {\n indegree[course]++\n graph[prereq] === undefined\n ? (graph[prereq] = [course])\n : graph[prereq].push(course)\n }\n const queue = [],\n ans = []\n for (let i = 0; i < indegree.length; i++) if (!indegree[i]) queue.push(i)\n while (queue.length) {\n let cur = queue.shift()\n ans.push(cur)\n for (let neigbhors of graph[cur] || []) {\n if (!--indegree[neigbhors]) queue.push(neigbhors)\n }\n }\n return ans.length === numCourses ? ans : []\n}", "const findOrder = function(numCourses, prerequisites) {\n const seen = new Set()\n const seeing = new Set()\n const res = []\n\n const adj = [...Array(numCourses)].map(r => [])\n for (let [u, v] of prerequisites) {\n adj[v].push(u)\n }\n for (let c = 0; c < numCourses; c++) {\n if (!dfs(c)) {\n return []\n }\n }\n return res.reverse()\n\n function dfs(v) {\n if (seen.has(v)) {\n return true\n }\n if (seeing.has(v)) {\n return false\n }\n seeing.add(v)\n for (let nv of adj[v]) {\n if (!dfs(nv)) {\n return false\n }\n }\n seeing.delete(v)\n seen.add(v)\n res.push(v)\n return true\n }\n}" ]
211
design-add-and-search-words-data-structure
[ "You should be familiar with how a Trie works. If not, please work on this problem: <a href=\"https://leetcode.com/problems/implement-trie-prefix-tree/\">Implement Trie (Prefix Tree)</a> first." ]
var WordDictionary = function() { }; /** * @param {string} word * @return {void} */ WordDictionary.prototype.addWord = function(word) { }; /** * @param {string} word * @return {boolean} */ WordDictionary.prototype.search = function(word) { }; /** * Your WordDictionary object will be instantiated and called as such: * var obj = new WordDictionary() * obj.addWord(word) * var param_2 = obj.search(word) */
Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: WordDictionary() Initializes the object. void addWord(word) Adds word to the data structure, it can be matched later. bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.   Example: Input ["WordDictionary","addWord","addWord","addWord","search","search","search","search"] [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] Output [null,null,null,null,false,true,true,true] Explanation WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord("bad"); wordDictionary.addWord("dad"); wordDictionary.addWord("mad"); wordDictionary.search("pad"); // return False wordDictionary.search("bad"); // return True wordDictionary.search(".ad"); // return True wordDictionary.search("b.."); // return True   Constraints: 1 <= word.length <= 25 word in addWord consists of lowercase English letters. word in search consist of '.' or lowercase English letters. There will be at most 2 dots in word for search queries. At most 104 calls will be made to addWord and search.
Medium
[ "string", "depth-first-search", "design", "trie" ]
[ "class TrieNode {\n constructor() {\n this.children = [];\n this.isWord = false;\n }\n}\n\nconst WordDictionary = function() {\n this.root = new TrieNode();\n this.aCode = \"a\".charCodeAt(0);\n};\n\n\nWordDictionary.prototype.addWord = function(word) {\n let node = this.root;\n for (let c of word.split(\"\")) {\n let code = c.charCodeAt(0);\n if (node.children[code - this.aCode] == null) {\n node.children[code - this.aCode] = new TrieNode();\n }\n node = node.children[code - this.aCode];\n }\n node.isWord = true;\n};\n\n\nWordDictionary.prototype.search = function(word) {\n return this._match(word.split(\"\"), 0, this.root);\n};\nWordDictionary.prototype._match = function(arr, k, node) {\n if (k == arr.length) {\n return node && node.isWord;\n }\n if (arr[k] === \".\") {\n for (let i = 0; node != null && i < node.children.length; i++) {\n if (\n node.children[i] !== null &&\n this._match(arr, k + 1, node.children[i])\n ) {\n return true;\n }\n }\n } else {\n return (\n node != null && node.children[arr[k].charCodeAt(0) - this.aCode] != null &&\n this._match(arr, k + 1, node.children[arr[k].charCodeAt(0) - this.aCode])\n );\n }\n return false;\n};" ]
212
word-search-ii
[ "You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?", "If the current candidate does not exist in all words&#39; prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: <a href=\"https://leetcode.com/problems/implement-trie-prefix-tree/\">Implement Trie (Prefix Tree)</a> first." ]
/** * @param {character[][]} board * @param {string[]} words * @return {string[]} */ var findWords = function(board, words) { };
Given an m x n board of characters and a list of strings words, return all words on the board. Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.   Example 1: Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] Output: ["eat","oath"] Example 2: Input: board = [["a","b"],["c","d"]], words = ["abcb"] Output: []   Constraints: m == board.length n == board[i].length 1 <= m, n <= 12 board[i][j] is a lowercase English letter. 1 <= words.length <= 3 * 104 1 <= words[i].length <= 10 words[i] consists of lowercase English letters. All the strings of words are unique.
Hard
[ "array", "string", "backtracking", "trie", "matrix" ]
[ "class Trie {\n constructor() {\n this.word = null\n this.children = new Map()\n }\n add(word) {\n let cur = this\n for (let i = 0; i < word.length; i++) {\n if (!cur.children.has(word[i])) {\n cur.children.set(word[i], new Trie())\n }\n cur = cur.children.get(word[i])\n }\n cur.word = word\n }\n addArr(words) {\n words.forEach(word => this.add(word))\n }\n}\n\nconst findWords = function(board, words) {\n const trie = new Trie()\n trie.addArr(words)\n const results = []\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[0].length; j++) {\n dfs(board, i, j, trie, results, dirs)\n }\n }\n return results\n}\n\nconst dfs = (board, i, j, trie, results, dirs) => {\n if(i < 0 || j < 0 || i >= board.length || j >= board[0].length) return\n const char = board[i][j]\n if (!trie.children.has(char)) return\n\n const nextTrie = trie.children.get(char)\n if (nextTrie.word) {\n results.push(nextTrie.word)\n nextTrie.word = null\n }\n \n for(let dir of dirs) {\n board[i][j] = '#'\n dfs(board, i + dir[0], j + dir[1], nextTrie, results, dirs)\n board[i][j] = char\n }\n \n}" ]
213
house-robber-ii
[ "Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the <a href =\"https://leetcode.com/problems/house-robber/description/\">House Robber</a>, which is already been solved." ]
/** * @param {number[]} nums * @return {number} */ var rob = function(nums) { };
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.   Example 1: Input: nums = [2,3,2] Output: 3 Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. Example 2: Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. Example 3: Input: nums = [1,2,3] Output: 3   Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 1000
Medium
[ "array", "dynamic-programming" ]
[ "const rob = function(nums) {\n if(nums.length === 0) return 0\n if(nums.length < 3) return Math.max(...nums)\n \n const startFromFirst = [0,nums[0]]\n const startFromSecond = [0,0]\n \n for(let i = 2; i <= nums.length; i++) {\n startFromFirst[i] = Math.max(startFromFirst[i - 1], startFromFirst[i - 2] + nums[i - 1])\n startFromSecond[i] = Math.max(startFromSecond[i - 1], startFromSecond[i - 2] + nums[i - 1])\n }\n \n return Math.max(startFromFirst[nums.length - 1], startFromSecond[nums.length])\n \n};", "const rob = function(nums) {\n if(nums.length === 1) return nums[0]\n return Math.max(helper(0, nums.length - 2), helper(1, nums.length - 1))\n\n function helper(l, r) {\n let inc = 0, exc = 0\n for(let i = l; i <= r; i++) {\n const pi = inc, pe = exc\n inc = exc + nums[i]\n exc = Math.max(pi, pe)\n }\n return Math.max(inc, exc)\n }\n};", "const rob = function(nums) {\n const n = nums.length\n nums = nums.concat(nums)\n let res = 0\n for(let i = 0; i < n; i++) {\n let tmp = nums[i]\n let pp = 0\n let p = 0\n for(let j = i; j < n + i - 1; j++) {\n tmp = Math.max(tmp, pp + nums[j], p);\n [pp, p] = [p, tmp]\n }\n res = Math.max(res, tmp)\n }\n \n return res\n};" ]
214
shortest-palindrome
[]
/** * @param {string} s * @return {string} */ var shortestPalindrome = function(s) { };
You are given a string s. You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation.   Example 1: Input: s = "aacecaaa" Output: "aaacecaaa" Example 2: Input: s = "abcd" Output: "dcbabcd"   Constraints: 0 <= s.length <= 5 * 104 s consists of lowercase English letters only.
Hard
[ "string", "rolling-hash", "string-matching", "hash-function" ]
[ "const shortestPalindrome = function(s) {\n let j = 0;\n for (let i = s.length - 1; i >= 0; i--) {\n if (s.charAt(i) === s.charAt(j)) { j += 1; }\n }\n if (j === s.length) { return s; }\n let suffix = s.substring(j);\n return suffix.split('').reverse().join('') + shortestPalindrome(s.substring(0, j)) + suffix;\n};", "const shortestPalindrome = function (s) {\n const tmp = s + '#' + s.split('').reverse().join('')\n const fail = getFail(tmp)\n return (\n s\n .split('')\n .slice(fail[fail.length - 1])\n .reverse()\n .join('') + s\n )\n}\n\nfunction getFail(s) {\n const n = s.length\n const table = new Array(n).fill(0)\n let index = 0\n for (let i = 1; i < n; ) {\n if (s.charAt(index) === s.charAt(i)) {\n table[i] = ++index\n i++\n } else {\n if (index > 0) {\n index = table[index - 1]\n } else {\n index = 0\n i++\n }\n }\n }\n return table\n}", "const shortestPalindrome = function(s) {\n const tmp = `${s}#${reverse(s)}`\n const table = kmp(tmp)\n return `${reverse(s.slice(table[table.length - 1]))}${s}`\n};\nfunction reverse(str) {\n return [...str].reverse().join('')\n}\n\nfunction kmp(s) {\n const n = s.length, table = Array(n).fill(0)\n let idx = 0\n for(let i = 1; i < n; ) {\n if(s[i] === s[idx]) {\n idx++\n table[i] = idx\n i++\n } else {\n if(idx > 0) {\n idx = table[idx - 1]\n } else {\n idx = 0\n i++\n }\n }\n }\n return table\n}" ]
215
kth-largest-element-in-an-array
[]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var findKthLargest = function(nums, k) { };
Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Can you solve it without sorting?   Example 1: Input: nums = [3,2,1,5,6,4], k = 2 Output: 5 Example 2: Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4   Constraints: 1 <= k <= nums.length <= 105 -104 <= nums[i] <= 104
Medium
[ "array", "divide-and-conquer", "sorting", "heap-priority-queue", "quickselect" ]
[ "const findKthLargest = function(nums, k) {\n if (!nums || k > nums.length) return 0;\n\n const larger = [];\n const smaller = [];\n const pivot = nums[parseInt(nums.length / 2)];\n let pivotCount = 0;\n\n for (let i = 0; i < nums.length; i++) {\n const ele = nums[i];\n\n if (ele > pivot) larger.push(ele);\n else if (ele === pivot) pivotCount++;\n else smaller.push(ele);\n }\n\n if (larger.length >= k) return findKthLargest(larger, k);\n else if (k - larger.length - pivotCount <= 0) return pivot;\n else return findKthLargest(smaller, k - larger.length - pivotCount);\n};", "const findKthLargest = function(nums, k) {\n return quickselect(nums, 0, nums.length - 1, k)\n};\nfunction quickselect(arr, lo, hi, k) {\n let pivtIdx = Math.floor(Math.random() * (hi - lo + 1)) + lo\n let pivtVal = arr[pivtIdx]\n ;[arr[hi], arr[pivtIdx]] = [arr[pivtIdx], arr[hi]]\n let i = lo\n let j = hi - 1\n\n while (i <= j) {\n if (arr[i] <= pivtVal) {\n i++\n } else {\n ;[arr[j], arr[i]] = [arr[i], arr[j]]\n j--\n }\n }\n\n ;[arr[i], arr[hi]] = [arr[hi], arr[i]]\n\n pivtIdx = i\n\n if (pivtIdx === arr.length - k) return arr[pivtIdx]\n if (pivtIdx < arr.length - k) return quickselect(arr, pivtIdx + 1, hi, k)\n return quickselect(arr, lo, pivtIdx - 1, k)\n}", "const findKthLargest = function(nums, k) {\n const n = nums.length\n let l = 0, r = n - 1, t = n - k\n while(l < r) {\n const mid = partition(nums, l, r)\n if(mid < t) {\n l = mid + 1\n } else {\n if(mid === t) break\n else r = mid - 1\n }\n }\n return nums[t]\n};\n\nfunction partition(arr, left, right) {\n let pivot = arr[right]\n let l = left, r = right - 1, j = left\n for(let i = left; i < right; i++) {\n if(arr[i] <= pivot) {\n swap(arr, i, j)\n j++\n }\n }\n swap(arr, j, right)\n return j\n}\n\nfunction swap(arr, i, j) {\n const tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n}", "const findKthLargest = function(nums, k) {\n const n = nums.length\n let l = 0, r = n - 1, t = n - k\n while(l < r) {\n const idx = partition(nums, l, r)\n if (idx === t) return nums[t]\n if (idx < t) l = idx + 1\n else r = idx - 1\n }\n return nums[l]\n};\n\nfunction partition(arr, l, r) {\n let tmp = l, pivot = arr[l]\n while(l < r) {\n while(l < r && arr[r] >= pivot) r--\n while(l < r && arr[l] <= pivot) l++\n swap(arr, l, r)\n }\n swap(arr, l, tmp)\n return l\n}\n\nfunction swap(arr, i, j) {\n const tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n}" ]
216
combination-sum-iii
[]
/** * @param {number} k * @param {number} n * @return {number[][]} */ var combinationSum3 = function(k, n) { };
Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Only numbers 1 through 9 are used. Each number is used at most once. Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.   Example 1: Input: k = 3, n = 7 Output: [[1,2,4]] Explanation: 1 + 2 + 4 = 7 There are no other valid combinations. Example 2: Input: k = 3, n = 9 Output: [[1,2,6],[1,3,5],[2,3,4]] Explanation: 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. Example 3: Input: k = 4, n = 1 Output: [] Explanation: There are no valid combinations. Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.   Constraints: 2 <= k <= 9 1 <= n <= 60
Medium
[ "array", "backtracking" ]
[ "const combinationSum3 = function(k, n) {\n const ans = [];\n combination(ans, [], k, 1, n);\n return ans;\n};\n\nfunction combination(ans, comb, k, start, n) {\n if (comb.length > k) {\n return;\n }\n if (comb.length === k && n === 0) {\n ans.push(comb.slice(0));\n return;\n }\n for (let i = start; i <= n && i <= 9; i++) {\n comb.push(i);\n combination(ans, comb, k, i + 1, n - i);\n comb.pop();\n }\n}" ]
217
contains-duplicate
[]
/** * @param {number[]} nums * @return {boolean} */ var containsDuplicate = function(nums) { };
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.   Example 1: Input: nums = [1,2,3,1] Output: true Example 2: Input: nums = [1,2,3,4] Output: false Example 3: Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: true   Constraints: 1 <= nums.length <= 105 -109 <= nums[i] <= 109
Easy
[ "array", "hash-table", "sorting" ]
[ "const containsDuplicate = function(nums) {\n const hash = {};\n for (let el of nums) {\n if (hash.hasOwnProperty(el)) {\n return true;\n } else {\n hash[el] = 1;\n }\n }\n return false;\n};" ]
218
the-skyline-problem
[]
/** * @param {number[][]} buildings * @return {number[][]} */ var getSkyline = function(buildings) { };
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively. The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]: lefti is the x coordinate of the left edge of the ith building. righti is the x coordinate of the right edge of the ith building. heighti is the height of the ith building. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]   Example 1: Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]] Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]] Explanation: Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. Example 2: Input: buildings = [[0,2,3],[2,5,3]] Output: [[0,3],[5,0]]   Constraints: 1 <= buildings.length <= 104 0 <= lefti < righti <= 231 - 1 1 <= heighti <= 231 - 1 buildings is sorted by lefti in non-decreasing order.
Hard
[ "array", "divide-and-conquer", "binary-indexed-tree", "segment-tree", "line-sweep", "heap-priority-queue", "ordered-set" ]
[ "const getSkyline = function getSkyline(\n buildings,\n begin = 0,\n end = buildings.length\n) {\n if (begin === end) {\n return []\n } else if (end - begin === 1) {\n const [Li, Ri, Hi] = buildings[begin]\n return [[Li, Hi], [Ri, 0]]\n } else {\n const pivotIndex = begin + Math.ceil((end - begin) / 2)\n return combineOutputs(\n getSkyline(buildings, begin, pivotIndex),\n getSkyline(buildings, pivotIndex, end)\n )\n }\n}\n\nfunction combineOutputs(a, b) {\n let aIndex = 0\n const aLength = a.length\n let bIndex = 0\n const bLength = b.length\n let aHeight = 0\n let bHeight = 0\n const combined = []\n while (aIndex < aLength || bIndex < bLength) {\n if (aIndex < aLength && bIndex === bLength) {\n return combined.concat(a.slice(aIndex))\n } else if (bIndex < bLength && aIndex === aLength) {\n return combined.concat(b.slice(bIndex))\n } else {\n const previousMax = Math.max(aHeight, bHeight)\n const nextX = Math.min(a[aIndex][0], b[bIndex][0])\n if (a[aIndex][0] === nextX) {\n aHeight = a[aIndex][1]\n aIndex++\n }\n if (b[bIndex][0] === nextX) {\n bHeight = b[bIndex][1]\n bIndex++\n }\n const newMax = Math.max(aHeight, bHeight)\n if (newMax !== previousMax) {\n combined.push([nextX, newMax])\n }\n }\n }\n return combined\n}" ]
219
contains-duplicate-ii
[]
/** * @param {number[]} nums * @param {number} k * @return {boolean} */ var containsNearbyDuplicate = function(nums, k) { };
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.   Example 1: Input: nums = [1,2,3,1], k = 3 Output: true Example 2: Input: nums = [1,0,1,1], k = 1 Output: true Example 3: Input: nums = [1,2,3,1,2,3], k = 2 Output: false   Constraints: 1 <= nums.length <= 105 -109 <= nums[i] <= 109 0 <= k <= 105
Easy
[ "array", "hash-table", "sliding-window" ]
[ "const containsNearbyDuplicate = function(nums, k) {\n const map = new Map();\n for (let i = 0; i < nums.length; i++) {\n if (map.has(nums[i])) {\n if (i - map.get(nums[i]) <= k) {\n return true;\n } else {\n map.set(nums[i], i);\n }\n } else {\n map.set(nums[i], i);\n }\n }\n return false;\n};" ]
220
contains-duplicate-iii
[ "Time complexity O(n logk) - This will give an indication that sorting is involved for k elements.", "Use already existing state to evaluate next state - Like, a set of k sorted numbers are only needed to be tracked. When we are processing the next number in array, then we can utilize the existing sorted state and it is not necessary to sort next overlapping set of k numbers again." ]
/** * @param {number[]} nums * @param {number} indexDiff * @param {number} valueDiff * @return {boolean} */ var containsNearbyAlmostDuplicate = function(nums, indexDiff, valueDiff) { };
You are given an integer array nums and two integers indexDiff and valueDiff. Find a pair of indices (i, j) such that: i != j, abs(i - j) <= indexDiff. abs(nums[i] - nums[j]) <= valueDiff, and Return true if such pair exists or false otherwise.   Example 1: Input: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0 Output: true Explanation: We can choose (i, j) = (0, 3). We satisfy the three conditions: i != j --> 0 != 3 abs(i - j) <= indexDiff --> abs(0 - 3) <= 3 abs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0 Example 2: Input: nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3 Output: false Explanation: After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false.   Constraints: 2 <= nums.length <= 105 -109 <= nums[i] <= 109 1 <= indexDiff <= nums.length 0 <= valueDiff <= 109
Hard
[ "array", "sliding-window", "sorting", "bucket-sort", "ordered-set" ]
[ "const containsNearbyAlmostDuplicate = function(nums, k, t) {\n if (k < 1 || t < 0) {\n return false\n }\n const array = new Map()\n const num = 10 ** 10\n for (let i = 0, iL = nums.length; i < iL; ++i) {\n const noNegative = nums[i] + num\n const factor = Math.floor(noNegative / (t + 1))\n if (\n array.has(factor) ||\n (array.has(factor - 1) && noNegative - array.get(factor - 1) <= t) ||\n (array.has(factor + 1) && array.get(factor + 1) - noNegative <= t)\n ) {\n return true\n }\n if (array.size >= k) {\n array.delete(Math.floor((nums[i - k] + num) / (t + 1)))\n }\n array.set(factor, noNegative)\n }\n return false\n}", "const containsNearbyAlmostDuplicate = function(nums, k, t) {\n const map = nums\n .map((val, idx) => ({ val, idx }))\n .sort((a, b) => a.val - b.val)\n let l = 0\n let r = 1\n while (r < map.length) {\n const diff = Math.abs(map[r].val - map[l].val)\n const range = Math.abs(map[r].idx - map[l].idx)\n if (diff <= t && range <= k) return true\n else if (diff > t) l++\n else if (range > k) r++\n if (l === r) r++\n }\n return false\n}" ]
221
maximal-square
[]
/** * @param {character[][]} matrix * @return {number} */ var maximalSquare = function(matrix) { };
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.   Example 1: Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] Output: 4 Example 2: Input: matrix = [["0","1"],["1","0"]] Output: 1 Example 3: Input: matrix = [["0"]] Output: 0   Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 300 matrix[i][j] is '0' or '1'.
Medium
[ "array", "dynamic-programming", "matrix" ]
[ "const maximalSquare = function(matrix) {\n const rows = matrix.length\n const cols = rows > 0 ? matrix[0].length : 0\n const dp = Array.from(new Array(rows + 1), el => new Array(cols + 1).fill(0))\n let maxLen = 0\n for(let i = 1; i <= rows; i++) {\n for(let j = 1; j <= cols; j++) {\n if(matrix[i - 1][j - 1] === '1') {\n dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1\n maxLen = Math.max(maxLen, dp[i][j])\n }\n }\n }\n \n return maxLen * maxLen\n};", "const maximalSquare = function(matrix) {\n const rows = matrix.length\n if(rows === 0) return 0\n const cols = matrix[0].length\n const dp = new Array(cols + 1).fill(0)\n let max = 0\n let prev = 0\n let tmp\n for(let i = 1; i <= rows; i++) {\n for(let j = 1; j <= cols; j++) {\n tmp = dp[j]\n if(matrix[i - 1][j - 1] === '1') {\n dp[j] = Math.min(dp[j - 1], dp[j], prev) + 1\n if(dp[j] > max) max = dp[j]\n } else {\n dp[j] = 0\n }\n prev = tmp\n }\n }\n return max ** 2\n};" ]
222
count-complete-tree-nodes
[]
/** * 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 countNodes = function(root) { };
Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Design an algorithm that runs in less than O(n) time complexity.   Example 1: Input: root = [1,2,3,4,5,6] Output: 6 Example 2: Input: root = [] Output: 0 Example 3: Input: root = [1] Output: 1   Constraints: The number of nodes in the tree is in the range [0, 5 * 104]. 0 <= Node.val <= 5 * 104 The tree is guaranteed to be complete.
Easy
[ "binary-search", "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 countNodes = function(root) {\n if (root == null) return 0;\n const payload = { depth: 0, numOfLast: 0, total: 0 };\n traverse([root], 0, payload);\n return payload.total;\n};\n\nfunction traverse(row, depth, obj) {\n const next = [];\n for (let i = 0; i < row.length; i++) {\n if (row[i].left) next.push(row[i].left);\n if (row[i].right) next.push(row[i].right);\n }\n if (Math.pow(2, depth + 1) !== next.length) {\n obj.total = Math.pow(2, depth + 1) - 1 + next.length;\n return;\n }\n if (next.length) traverse(next, depth + 1, obj);\n}", "const countNodes = function(root) {\n if (!root) {\n return 0;\n }\n\n return 1 + countNodes(root.left) + countNodes(root.right);\n};" ]
223
rectangle-area
[]
/** * @param {number} ax1 * @param {number} ay1 * @param {number} ax2 * @param {number} ay2 * @param {number} bx1 * @param {number} by1 * @param {number} bx2 * @param {number} by2 * @return {number} */ var computeArea = function(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2) { };
Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles. The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2). The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).   Example 1: Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 Output: 45 Example 2: Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 Output: 16   Constraints: -104 <= ax1 <= ax2 <= 104 -104 <= ay1 <= ay2 <= 104 -104 <= bx1 <= bx2 <= 104 -104 <= by1 <= by2 <= 104
Medium
[ "math", "geometry" ]
[ "const computeArea = function(A, B, C, D, E, F, G, H) {\n const areaA = (C - A) * (D - B)\n const areaB = (G - E) * (H - F)\n const intersectionArea =\n Math.max(0, Math.min(C, G) - Math.max(A, E)) *\n Math.max(0, Math.min(D, H) - Math.max(B, F))\n return areaA + areaB - intersectionArea\n}", "const computeArea = function(A, B, C, D, E, F, G, H) {\n const x1 = A,\n x2 = C,\n x3 = E,\n x4 = G\n const y1 = B,\n y2 = D,\n y3 = F,\n y4 = H\n return (\n area(x1, y1, x2, y2) +\n area(x3, y3, x4, y4) -\n delta(x1, x2, x3, x4) * delta(y1, y2, y3, y4)\n )\n}\n\nfunction area(x1, y1, x2, y2) {\n return Math.abs(x1 - x2) * Math.abs(y1 - y2)\n}\n\nfunction delta(v1, v2, v3, v4) {\n if (v1 > v2) {\n let tmp = v1\n v1 = v2\n v2 = tmp\n }\n if (v3 > v4) {\n let tmp = v3\n v3 = v4\n v4 = tmp\n }\n if (v3 >= v2 || v4 <= v1) return 0\n return Math.min(v2, v4) - Math.max(v1, v3)\n}" ]
224
basic-calculator
[]
/** * @param {string} s * @return {number} */ var calculate = function(s) { };
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().   Example 1: Input: s = "1 + 1" Output: 2 Example 2: Input: s = " 2-1 + 2 " Output: 3 Example 3: Input: s = "(1+(4+5+2)-3)+(6+8)" Output: 23   Constraints: 1 <= s.length <= 3 * 105 s consists of digits, '+', '-', '(', ')', and ' '. s represents a valid expression. '+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid). '-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid). There will be no two consecutive operators in the input. Every number and running calculation will fit in a signed 32-bit integer.
Hard
[ "math", "string", "stack", "recursion" ]
[ "const calculate = function(s) {\n let stack = []\n let num = 0\n let sign = 1\n let res = 0\n for (let i = 0; i < s.length; i++) {\n let char = s.charAt(i)\n if (char >= '0' && char <= '9') {\n num = num * 10 + parseInt(char, 10)\n } else if (char === '+') {\n res += sign * num\n sign = 1\n num = 0\n } else if (char === '-') {\n res += sign * num\n sign = -1\n num = 0\n } else if (char === '(') {\n stack.push(res)\n stack.push(sign)\n sign = 1\n res = 0\n num = 0\n } else if (char === ')') {\n res += sign * num\n res *= stack.pop()\n res += stack.pop()\n num = 0\n }\n }\n return res + sign * num\n}", "const calculate = function(s) {\n s = s.split(' ').join('')\n const n = s.length, stack = []\n const isNum = ch => ch >= '0' && ch <= '9'\n let num = 0, op = 1, res = 0\n for(let i = 0; i < n; i++) {\n const ch = s[i]\n if(isNum(ch)) {\n num = num * 10 + (+ch)\n } else {\n if(ch === '(') {\n stack.push(res)\n stack.push(op)\n num = 0\n op = 1\n res = 0\n } else if(ch === ')') {\n res += num * op\n res *= stack.pop()\n res += stack.pop()\n num = 0\n op = 1\n } else if(ch === '+') {\n res += op * num\n op = 1\n num = 0\n } else if(ch === '-') {\n res += op * num\n op = -1\n num = 0\n }\n }\n }\n \n return res + op * num\n};", "const calculate = function(s) {\n s = s.trim()\n \n let res = 0, num = 0, op = 1\n const isDigit = ch => ch >= '0' && ch <= '9'\n const stk = []\n for(let i = 0, n = s.length; i < n; i++) {\n \n const e = s[i]\n if(e === ' ') continue\n if(isDigit(e)) num = num * 10 + (+e)\n else {\n \n if(e === '(') {\n stk.push(res)\n stk.push(op)\n \n res = 0\n num = 0\n op = 1\n } else if(e === ')') {\n res += num * op\n res *= stk.pop()\n res += stk.pop()\n op = 1\n num = 0\n } else if(e === '-') {\n res += num * op\n op = -1\n num = 0\n } else if(e === '+') {\n res += num * op\n op = 1\n num = 0\n }\n }\n }\n \n return res + num * op\n};" ]