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
991
broken-calculator
[]
/** * @param {number} startValue * @param {number} target * @return {number} */ var brokenCalc = function(startValue, target) { };
There is a broken calculator that has the integer startValue on its display initially. In one operation, you can: multiply the number on display by 2, or subtract 1 from the number on display. Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator.   Example 1: Input: startValue = 2, target = 3 Output: 2 Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}. Example 2: Input: startValue = 5, target = 8 Output: 2 Explanation: Use decrement and then double {5 -> 4 -> 8}. Example 3: Input: startValue = 3, target = 10 Output: 3 Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.   Constraints: 1 <= startValue, target <= 109
Medium
[ "math", "greedy" ]
null
[]
992
subarrays-with-k-different-integers
[]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var subarraysWithKDistinct = function(nums, k) { };
Given an integer array nums and an integer k, return the number of good subarrays of nums. A good array is an array where the number of different integers in that array is exactly k. For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3. A subarray is a contiguous part of an array.   Example 1: Input: nums = [1,2,1,2,3], k = 2 Output: 7 Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2] Example 2: Input: nums = [1,2,1,3,4], k = 3 Output: 3 Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].   Constraints: 1 <= nums.length <= 2 * 104 1 <= nums[i], k <= nums.length
Hard
[ "array", "hash-table", "sliding-window", "counting" ]
[ "const subarraysWithKDistinct = function(A, K) {\n let res = 0\n let prefix = 0\n const m = new Array(A.length + 1).fill(0)\n for (let i = 0, j = 0, cnt = 0, len = A.length; i < len; i++) {\n if (m[A[i]]++ === 0) cnt++\n if (cnt > K) {\n m[A[j++]]--\n cnt--\n prefix = 0\n }\n while (m[A[j]] > 1) {\n prefix++\n m[A[j++]]--\n }\n if (cnt === K) res += prefix + 1\n }\n return res\n}", "const subarraysWithKDistinct = function (A, K) {\n return mostK(K) - mostK(K - 1)\n function mostK(num) {\n const m = {}, len = A.length\n let i = 0, j = 0, res = 0\n for(j = 0; j < len; j++) {\n if(!m[A[j]]) m[A[j]] = 0, num--\n m[A[j]]++\n while(num < 0) {\n m[A[i]]--\n if(!m[A[i]]) num++\n i++\n }\n res += j - i + 1\n }\n return res\n }\n}" ]
993
cousins-in-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 * @param {number} x * @param {number} y * @return {boolean} */ var isCousins = function(root, x, y) { };
Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise. Two nodes of a binary tree are cousins if they have the same depth with different parents. Note that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1.   Example 1: Input: root = [1,2,3,4], x = 4, y = 3 Output: false Example 2: Input: root = [1,2,3,null,4,null,5], x = 5, y = 4 Output: true Example 3: Input: root = [1,2,3,null,4], x = 2, y = 3 Output: false   Constraints: The number of nodes in the tree is in the range [2, 100]. 1 <= Node.val <= 100 Each node has a unique value. x != y x and y are exist in the tree.
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 isCousins = (root, x, y, depth = 1, P = {}, D = {}) => {\n let q = [root]\n while (q.length) {\n let K = q.length\n while (K--) {\n let p = q.shift()\n if (p.left) {\n if (p.left.val === x) (P.x = p.val), (D.x = depth)\n if (p.left.val === y) (P.y = p.val), (D.y = depth)\n q.push(p.left)\n }\n if (p.right) {\n if (p.right.val === x) (P.x = p.val), (D.x = depth)\n if (p.right.val === y) (P.y = p.val), (D.y = depth)\n q.push(p.right)\n }\n }\n ++depth\n }\n return P.x !== P.y && D.x === D.y\n}", "const isCousins = function(root, x, y) {\n if(root == null) return false\n const res = []\n chk(root, x, [], res)\n chk(root, y, [], res)\n if(res.length < 2) return false\n return chkRes(res, x, y)\n};\nfunction chkRes(arr, x, y) {\n let ci = 0, xi = -1, yi = -1\n let len = Math.max(arr[0].length, arr[1].length)\n for(let i = 0; i < len; i++) {\n if(arr[0][i] === arr[1][i]) ci = i\n if(arr[0][i] === x || arr[1][i] === x) xi = i\n if(arr[0][i] === y || arr[1][i] === y) yi = i\n }\n if(xi - yi === 0 && xi - ci > 1) {\n return true\n } else {\n return false\n }\n}\n\nfunction chk(node, val, path, res) {\n if(node == null) return\n path.push(node.val)\n if(node.val === val) {\n res.push(path.slice(0))\n return\n }\n chk(node.left, val, path.slice(0), res)\n chk(node.right, val, path.slice(0), res)\n}" ]
994
rotting-oranges
[]
/** * @param {number[][]} grid * @return {number} */ var orangesRotting = function(grid) { };
You are given an m x n grid where each cell can have one of three values: 0 representing an empty cell, 1 representing a fresh orange, or 2 representing a rotten orange. Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.   Example 1: Input: grid = [[2,1,1],[1,1,0],[0,1,1]] Output: 4 Example 2: Input: grid = [[2,1,1],[0,1,1],[1,0,1]] Output: -1 Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. Example 3: Input: grid = [[0,2]] Output: 0 Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 10 grid[i][j] is 0, 1, or 2.
Medium
[ "array", "breadth-first-search", "matrix" ]
[ "const orangesRotting = function(grid) {\n const m = grid.length, n = grid[0].length\n const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]]\n const visited = new Set()\n let q = []\n let num = 0\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j] === 2) q.push([i, j]), visited.add(`${i},${j}`)\n if(grid[i][j] !== 0) num++\n }\n }\n let res = 0\n while(q.length) {\n const size = q.length\n const tmp = []\n for(let i = 0; i < size; i++) {\n const [x, y] = q[i]\n for(let [dx, dy] of dirs) {\n const nx = x + dx, ny = y + dy\n if(nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] === 1 && !visited.has(`${nx},${ny}`)) {\n tmp.push([nx, ny])\n visited.add(`${nx},${ny}`)\n }\n }\n }\n q = tmp\n if(q.length) res++\n }\n return visited.size === num ? res : -1\n};", "const orangesRotting = function(grid) {\n let count = 0\n const p = {s: 2}\n const rows = grid.length\n const cols = grid[0].length\n while(!chk(grid, rows, cols)) {\n loop(grid, rows, cols, p)\n count++\n if(count> rows * cols) return -1\n }\n \n return count\n};\n\nfunction loop(grid, rows, cols, p) {\n let cur = p.s\n let next = cur + 1\n for(let i = 0; i < rows; i++) {\n for(let j = 0; j < cols; j++) {\n if(grid[i][j] === cur) rotten(i, j, grid, next)\n }\n }\n p.s += 1\n}\n\nfunction rotten(row, col, grid, p) { \n if(grid[row] && col > 0 && grid[row][col - 1] === 1) grid[row][col - 1] = p\n if(grid[row] && col < (grid[0] || []).length - 1 && grid[row][col + 1] === 1) grid[row][col + 1] = p\n if(grid[row] && row > 0 && grid[row - 1][col] === 1) grid[row - 1][col] = p\n if(grid[row] && row < grid.length - 1 && grid[row + 1][col] === 1) grid[row + 1][col] = p\n}\n\nfunction chk(grid, rows, cols) {\n for(let i = 0; i < rows; i++) {\n for(let j = 0; j < cols; j++) {\n if(grid[i][j] === 1) return false\n }\n }\n return true\n}" ]
995
minimum-number-of-k-consecutive-bit-flips
[]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var minKBitFlips = function(nums, k) { };
You are given a binary array nums and an integer k. A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0. Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1. A subarray is a contiguous part of an array.   Example 1: Input: nums = [0,1,0], k = 1 Output: 2 Explanation: Flip nums[0], then flip nums[2]. Example 2: Input: nums = [1,1,0], k = 2 Output: -1 Explanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1]. Example 3: Input: nums = [0,0,0,1,0,1,1,0], k = 3 Output: 3 Explanation: Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0] Flip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0] Flip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]   Constraints: 1 <= nums.length <= 105 1 <= k <= nums.length
Hard
[ "array", "bit-manipulation", "queue", "sliding-window", "prefix-sum" ]
[ "const minKBitFlips = function(nums, k) {\n let cur = 0, res = 0\n const n = nums.length\n for(let i = 0; i < n; i++) {\n if(i >= k && nums[i - k] === 2) cur--\n if(cur % 2 === nums[i]) {\n if(i + k > n) return -1\n nums[i] = 2\n cur++\n res++\n }\n }\n return res\n};", "const minKBitFlips = function(A, K) {\n let cur = 0, res = 0;\n for (let i = 0; i < A.length; ++i) {\n if (i >= K) cur -= (A[i - K] / 2) >> 0;\n if ((cur & 1 ^ A[i]) === 0) {\n if (i + K > A.length) return -1;\n A[i] += 2;\n cur++;\n res++;\n }\n }\n return res;\n};", "const minKBitFlips = function(nums, k) {\n const n = nums.length, q = []\n let res = 0\n for(let i = 0; i < n; i++) {\n if(nums[i] === 0) {\n if(q.length === 0 || q.length % 2 === 0) {\n res++\n q.push(i + k - 1)\n }\n } else {\n if(q.length % 2 === 1) {\n res++\n q.push(i + k - 1)\n }\n }\n if(q.length && i >= q[0]) q.shift()\n }\n return q.length ? -1 : res\n};" ]
996
number-of-squareful-arrays
[]
/** * @param {number[]} nums * @return {number} */ var numSquarefulPerms = function(nums) { };
An array is squareful if the sum of every pair of adjacent elements is a perfect square. Given an integer array nums, return the number of permutations of nums that are squareful. Two permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i].   Example 1: Input: nums = [1,17,8] Output: 2 Explanation: [1,8,17] and [17,8,1] are the valid permutations. Example 2: Input: nums = [2,2,2] Output: 1   Constraints: 1 <= nums.length <= 12 0 <= nums[i] <= 109
Hard
[ "array", "math", "dynamic-programming", "backtracking", "bit-manipulation", "bitmask" ]
[ "const numSquarefulPerms = function (A) {\n const cntMap = {}\n const squareMap = {}\n let cnt = 0\n for (let num of A) {\n if (!cntMap.hasOwnProperty(num)) {\n cntMap[num] = 1\n squareMap[num] = new Set()\n } else {\n cntMap[num] = cntMap[num] + 1\n }\n }\n\n for (let num1 of Object.keys(cntMap)) {\n for (let num2 of Object.keys(cntMap)) {\n let c = Math.sqrt(+num1 + +num2)\n if (c === Math.floor(c)) {\n squareMap[num1].add(+num2)\n squareMap[num2].add(+num1)\n }\n }\n }\n for (let num of Object.keys(cntMap)) {\n countPerm(num, A.length - 1)\n }\n return cnt\n function countPerm(num, left) {\n cntMap[num] = cntMap[num] - 1\n if (left === 0) {\n cnt++\n } else {\n for (let next of squareMap[num]) {\n if (cntMap[next] !== 0) {\n countPerm(next, left - 1)\n }\n }\n }\n cntMap[num] = cntMap[num] + 1\n }\n}" ]
997
find-the-town-judge
[]
/** * @param {number} n * @param {number[][]} trust * @return {number} */ var findJudge = function(n, trust) { };
In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: The town judge trusts nobody. Everybody (except for the town judge) trusts the town judge. There is exactly one person that satisfies properties 1 and 2. You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi. If a trust relationship does not exist in trust array, then such a trust relationship does not exist. Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.   Example 1: Input: n = 2, trust = [[1,2]] Output: 2 Example 2: Input: n = 3, trust = [[1,3],[2,3]] Output: 3 Example 3: Input: n = 3, trust = [[1,3],[2,3],[3,1]] Output: -1   Constraints: 1 <= n <= 1000 0 <= trust.length <= 104 trust[i].length == 2 All the pairs of trust are unique. ai != bi 1 <= ai, bi <= n
Easy
[ "array", "hash-table", "graph" ]
[ "const findJudge = function(N, trust) {\n const arr = new Array(N + 1).fill(0)\n for(let [t, ted] of trust) {\n arr[t]--\n arr[ted]++\n }\n for(let i = 1; i <= N; i++) {\n if(arr[i] === N - 1) return i\n }\n return -1\n};", "const findJudge = function(N, trust) {\n const m = new Map()\n for(let i = 1; i<= N; i++) {\n const e = new Map()\n e.set('t', new Set())\n e.set('ted', new Set())\n m.set(i, e)\n }\n for(let [t, ted] of trust) {\n m.get(t).get('t').add(ted)\n m.get(ted).get('ted').add(t)\n }\n for(let [k,v] of m) {\n if(v.get('t').size === 0 && v.get('ted').size === N - 1) return k\n }\n return -1\n};" ]
998
maximum-binary-tree-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} val * @return {TreeNode} */ var insertIntoMaxTree = function(root, val) { };
A maximum tree is a tree where every node has a value greater than any other value in its subtree. You are given the root of a maximum binary tree and an integer val. Just as in the previous problem, the given tree was constructed from a list a (root = Construct(a)) recursively with the following Construct(a) routine: If a is empty, return null. Otherwise, let a[i] be the largest element of a. Create a root node with the value a[i]. The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]). The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]). Return root. Note that we were not given a directly, only a root node root = Construct(a). Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values. Return Construct(b).   Example 1: Input: root = [4,1,3,null,null,2], val = 5 Output: [5,4,null,1,3,null,null,2] Explanation: a = [1,4,2,3], b = [1,4,2,3,5] Example 2: Input: root = [5,2,4,null,1], val = 3 Output: [5,2,4,null,1,null,3] Explanation: a = [2,1,5,4], b = [2,1,5,4,3] Example 3: Input: root = [5,2,3,null,1], val = 4 Output: [5,2,4,null,1,3] Explanation: a = [2,1,5,3], b = [2,1,5,3,4]   Constraints: The number of nodes in the tree is in the range [1, 100]. 1 <= Node.val <= 100 All the values of the tree are unique. 1 <= val <= 100
Medium
[ "tree", "binary-tree" ]
null
[]
999
available-captures-for-rook
[]
/** * @param {character[][]} board * @return {number} */ var numRookCaptures = function(board) { };
On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B', black pawns 'p', and empty squares '.'. When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking. Return the number of available captures for the white rook.   Example 1: Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 3 Explanation: In this example, the rook is attacking all the pawns. Example 2: Input: board = [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 0 Explanation: The bishops are blocking the rook from attacking any of the pawns. Example 3: Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 3 Explanation: The rook is attacking the pawns at positions b5, d6, and f5.   Constraints: board.length == 8 board[i].length == 8 board[i][j] is either 'R', '.', 'B', or 'p' There is exactly one cell with board[i][j] == 'R'
Easy
[ "array", "matrix", "simulation" ]
[ "const numRookCaptures = function(board) {\n for (let i = 0; i < board.length; ++i)\n for (let j = 0; j < board[i].length; ++j)\n if (board[i][j] == 'R') return cap(board,i,j,0,1)+cap(board,i,j,0,-1)+cap(board,i,j,1,0)+cap(board,i,j,-1,0);\n return 0; \n};\n\nfunction cap(b, x, y, dx, dy) {\n while (x >= 0 && x < b.length && y >= 0 && y < b[x].length && b[x][y] != 'B') {\n if (b[x][y] == 'p') return 1;\n x += dx; y += dy;\n }\n return 0;\n}" ]
1,000
minimum-cost-to-merge-stones
[]
/** * @param {number[]} stones * @param {number} k * @return {number} */ var mergeStones = function(stones, k) { };
There are n piles of stones arranged in a row. The ith pile has stones[i] stones. A move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles. Return the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.   Example 1: Input: stones = [3,2,4,1], k = 2 Output: 20 Explanation: We start with [3, 2, 4, 1]. We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1]. We merge [4, 1] for a cost of 5, and we are left with [5, 5]. We merge [5, 5] for a cost of 10, and we are left with [10]. The total cost was 20, and this is the minimum possible. Example 2: Input: stones = [3,2,4,1], k = 3 Output: -1 Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible. Example 3: Input: stones = [3,5,1,2,6], k = 3 Output: 25 Explanation: We start with [3, 5, 1, 2, 6]. We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6]. We merge [3, 8, 6] for a cost of 17, and we are left with [17]. The total cost was 25, and this is the minimum possible.   Constraints: n == stones.length 1 <= n <= 30 1 <= stones[i] <= 100 2 <= k <= 30
Hard
[ "array", "dynamic-programming", "prefix-sum" ]
[ "const mergeStones = function(stones, K) {\n const KMO = K - 1\n const N = stones.length\n if ((N - 1) % KMO !== 0) return -1\n const sum = [0]\n const dp = stones.map(s => stones.map(s1 => 0))\n stones.forEach(s => {\n sum.push(sum[sum.length - 1] + s)\n })\n for (let e = KMO; e < N; e++) {\n for (let b = e - KMO; b >= 0; b--) {\n for (let split = e - 1; split >= b; split -= KMO) {\n let cost = dp[b][split] + dp[split + 1][e]\n dp[b][e] = dp[b][e] === 0 ? cost : Math.min(dp[b][e], cost)\n }\n if ((e - b) % KMO === 0) {\n dp[b][e] += sum[e + 1] - sum[b]\n }\n }\n }\n return dp[0][N - 1]\n}" ]
1,001
grid-illumination
[]
/** * @param {number} n * @param {number[][]} lamps * @param {number[][]} queries * @return {number[]} */ var gridIllumination = function(n, lamps, queries) { };
There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off. You are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on. When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal. You are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj]. Return an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not.   Example 1: Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]] Output: [1,0] Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4]. The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square. The 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle. Example 2: Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]] Output: [1,1] Example 3: Input: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]] Output: [1,1,0]   Constraints: 1 <= n <= 109 0 <= lamps.length <= 20000 0 <= queries.length <= 20000 lamps[i].length == 2 0 <= rowi, coli < n queries[j].length == 2 0 <= rowj, colj < n
Hard
[ "array", "hash-table" ]
[ "const gridIllumination = function (N, lamps, queries) {\n const rowMap = new Map()\n const colMap = new Map()\n const hillMap = new Map()\n const daleMap = new Map()\n const litMap = new Map()\n const direction = [\n [0, 0],\n [0, 1],\n [1, 0],\n [-1, 0],\n [0, -1],\n [-1, -1],\n [1, 1],\n ]\n //map what areas are lit\n for (let [x, y] of lamps) {\n insert(rowMap, x)\n insert(colMap, y)\n insert(hillMap, x + y)\n insert(daleMap, x - y)\n litMap.set(N * x + y, true)\n }\n const result = new Array(queries.length).fill(0)\n let count = 0\n for (let [x, y] of queries) {\n if (\n rowMap.get(x) > 0 ||\n colMap.get(y) > 0 ||\n hillMap.get(x + y) > 0 ||\n daleMap.get(x - y) > 0\n ) {\n result[count] = 1\n }\n for (let [i, j] of direction) {\n let newX = x + i\n let newY = y + j\n if (litMap.has(N * newX + newY)) {\n decrease(rowMap, newX)\n decrease(colMap, newY)\n decrease(hillMap, newX + newY)\n decrease(daleMap, N * newX + newY)\n litMap.delete(N * newX + newY)\n }\n }\n count++\n }\n return result\n}\nconst insert = (map, value) => {\n if (map.has(value)) {\n map.set(value, map.get(value) + 1)\n } else {\n map.set(value, 1)\n }\n}\nconst decrease = (map, value) => {\n if (map.has(value)) {\n map.set(value, map.get(value) - 1)\n }\n}" ]
1,002
find-common-characters
[]
/** * @param {string[]} words * @return {string[]} */ var commonChars = function(words) { };
Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.   Example 1: Input: words = ["bella","label","roller"] Output: ["e","l","l"] Example 2: Input: words = ["cool","lock","cook"] Output: ["c","o"]   Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 100 words[i] consists of lowercase English letters.
Easy
[ "array", "hash-table", "string" ]
[ "const commonChars = function(A) {\n const minArr = minEl(A)\n const res = []\n for(let i = 0; i < minArr[1]; i++) {\n let target = A[minArr[0]][i]\n let all = true\n for(let j = 0; j < A.length; j++) {\n if(j === minArr[0]) continue\n if(all === false) continue\n let idx\n if( (idx = A[j].indexOf(target)) === -1) {\n all = false\n } else {\n A[j] = A[j].slice(0, idx) + A[j].slice(idx + 1)\n }\n }\n if(all) res.push(target)\n }\n \n return res\n};\n\nfunction minEl(arr) {\n const res = [0, Number.MAX_SAFE_INTEGER] // [idx, len]\n for(let i = 0; i < arr.length; i++) {\n if(arr[i].length < res[1]) {\n res[0] = i\n res[1] = arr[i].length\n }\n }\n return res\n}" ]
1,003
check-if-word-is-valid-after-substitutions
[]
/** * @param {string} s * @return {boolean} */ var isValid = function(s) { };
Given a string s, determine if it is valid. A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times: Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, where t == tleft + tright. Note that tleft and tright may be empty. Return true if s is a valid string, otherwise, return false.   Example 1: Input: s = "aabcbc" Output: true Explanation: "" -> "abc" -> "aabcbc" Thus, "aabcbc" is valid. Example 2: Input: s = "abcabcababcc" Output: true Explanation: "" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc" Thus, "abcabcababcc" is valid. Example 3: Input: s = "abccba" Output: false Explanation: It is impossible to get "abccba" using the operation.   Constraints: 1 <= s.length <= 2 * 104 s consists of letters 'a', 'b', and 'c'
Medium
[ "string", "stack" ]
null
[]
1,004
max-consecutive-ones-iii
[ "One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window!", "Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right?", "We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!).", "The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var longestOnes = function(nums, k) { };
Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.   Example 1: Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 Output: 6 Explanation: [1,1,1,0,0,1,1,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. Example 2: Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3 Output: 10 Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.   Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1. 0 <= k <= nums.length
Medium
[ "array", "binary-search", "sliding-window", "prefix-sum" ]
[ "const longestOnes = function (A, K) {\n let i = 0\n let j = 0\n const len = A.length\n while (j < len) {\n if (A[j] === 0) K--\n if (K < 0) {\n if (A[i] === 0) K++\n i++\n }\n j++\n }\n return j - i\n}" ]
1,005
maximize-sum-of-array-after-k-negations
[]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var largestSumAfterKNegations = function(nums, k) { };
Given an integer array nums and an integer k, modify the array in the following way: choose an index i and replace nums[i] with -nums[i]. You should apply this process exactly k times. You may choose the same index i multiple times. Return the largest possible sum of the array after modifying it in this way.   Example 1: Input: nums = [4,2,3], k = 1 Output: 5 Explanation: Choose index 1 and nums becomes [4,-2,3]. Example 2: Input: nums = [3,-1,0,2], k = 3 Output: 6 Explanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2]. Example 3: Input: nums = [2,-3,-1,5,-4], k = 2 Output: 13 Explanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].   Constraints: 1 <= nums.length <= 104 -100 <= nums[i] <= 100 1 <= k <= 104
Easy
[ "array", "greedy", "sorting" ]
[ "const largestSumAfterKNegations = function(A, K) {\n if (A.length === 0) return 0;\n A.sort((a, b) => a - b);\n let res = 0;\n let posIdx;\n for (let i = 0, num = 0; i < A.length; i++) {\n if (num < K) {\n if (A[i] < 0) {\n A[i] = -A[i];\n } else {\n if (posIdx == null) {\n posIdx = Math.abs(A[i]) - Math.abs(A[i - 1]) > 0 ? i - 1 : i;\n }\n A[posIdx] = -A[posIdx];\n }\n num++;\n }\n }\n res = A.reduce((ac, el) => ac + el, 0);\n return res;\n};" ]
1,006
clumsy-factorial
[]
/** * @param {number} n * @return {number} */ var clumsy = function(n) { };
The factorial of a positive integer n is the product of all positive integers less than or equal to n. For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1. We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*', divide '/', add '+', and subtract '-' in this order. For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1. However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right. Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11. Given an integer n, return the clumsy factorial of n.   Example 1: Input: n = 4 Output: 7 Explanation: 7 = 4 * 3 / 2 + 1 Example 2: Input: n = 10 Output: 12 Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1   Constraints: 1 <= n <= 104
Medium
[ "math", "stack", "simulation" ]
[ "const clumsy = function(N) {\n const ops = [\"*\", \"/\", \"+\", \"-\"];\n const arr = [];\n arr.push(N);\n for (let i = N - 1, idx = 0; i > 0; i--, idx++) {\n let op = ops[idx % 4];\n let arrIdx = arr.length - 1 < 0 ? 0 : arr.length - 1;\n switch (op) {\n case \"*\":\n arr[arrIdx] *= i;\n break;\n case \"/\":\n arr[arrIdx] = Math.floor(arr[arrIdx] / i);\n break;\n case \"+\":\n arr[0] += i;\n break;\n case \"-\":\n arr.push(i);\n break;\n }\n }\n\n let res = arr[0];\n for (let i = 1; i < arr.length; i++) {\n res -= arr[i];\n }\n return res;\n};" ]
1,007
minimum-domino-rotations-for-equal-row
[]
/** * @param {number[]} tops * @param {number[]} bottoms * @return {number} */ var minDominoRotations = function(tops, bottoms) { };
In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the ith domino, so that tops[i] and bottoms[i] swap values. Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same. If it cannot be done, return -1.   Example 1: Input: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2] Output: 2 Explanation: The first figure represents the dominoes as given by tops and bottoms: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. Example 2: Input: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4] Output: -1 Explanation: In this case, it is not possible to rotate the dominoes to make one row of values equal.   Constraints: 2 <= tops.length <= 2 * 104 bottoms.length == tops.length 1 <= tops[i], bottoms[i] <= 6
Medium
[ "array", "greedy" ]
null
[]
1,008
construct-binary-search-tree-from-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 {number[]} preorder * @return {TreeNode} */ var bstFromPreorder = function(preorder) { };
Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val. A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.   Example 1: Input: preorder = [8,5,1,7,10,12] Output: [8,5,10,1,7,null,12] Example 2: Input: preorder = [1,3] Output: [1,null,3]   Constraints: 1 <= preorder.length <= 100 1 <= preorder[i] <= 1000 All the values of preorder are unique.
Medium
[ "array", "stack", "tree", "binary-search-tree", "monotonic-stack", "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 bstFromPreorder = function(preorder) {\n let i = 0;\n return bstFromPreorder(preorder, Number.MAX_VALUE);\n function bstFromPreorder(A, bound) {\n if (i === A.length || A[i] > bound) return null;\n let root = new TreeNode(A[i++]);\n root.left = bstFromPreorder(A, root.val);\n root.right = bstFromPreorder(A, bound);\n return root;\n }\n};" ]
1,009
complement-of-base-10-integer
[ "A binary number plus its complement will equal 111....111 in binary. Also, N = 0 is a corner case." ]
/** * @param {number} n * @return {number} */ var bitwiseComplement = function(n) { };
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. Given an integer n, return its complement.   Example 1: Input: n = 5 Output: 2 Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10. Example 2: Input: n = 7 Output: 0 Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10. Example 3: Input: n = 10 Output: 5 Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.   Constraints: 0 <= n < 109   Note: This question is the same as 476: https://leetcode.com/problems/number-complement/
Easy
[ "bit-manipulation" ]
[ "const bitwiseComplement = function (N) {\n if (N === 0) return 1\n // bitmask has the same length as N and contains only ones 1...1\n let bitmask = N\n bitmask |= bitmask >> 1\n bitmask |= bitmask >> 2\n bitmask |= bitmask >> 4\n bitmask |= bitmask >> 8\n bitmask |= bitmask >> 16\n // flip all bits\n return bitmask ^ N\n}", "const bitwiseComplement = function (N) {\n let X = 1;\n while (N > X) X = X * 2 + 1;\n return N ^ X;\n}", "const bitwiseComplement = function (N) {\n if (N === 0) return 1\n // l is a length of N in binary representation\n const l = Math.floor(Math.log(N) / Math.log(2)) + 1\n // bitmask has the same length as num and contains only ones 1...1\n const bitmask = (1 << l) - 1\n // flip all bits\n return bitmask ^ N\n}" ]
1,010
pairs-of-songs-with-total-durations-divisible-by-60
[ "We only need to consider each song length modulo 60.", "We can count the number of songs with (length % 60) equal to r, and store that in an array of size 60." ]
/** * @param {number[]} time * @return {number} */ var numPairsDivisibleBy60 = function(time) { };
You are given a list of songs where the ith song has a duration of time[i] seconds. Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.   Example 1: Input: time = [30,20,150,100,40] Output: 3 Explanation: Three pairs have a total duration divisible by 60: (time[0] = 30, time[2] = 150): total duration 180 (time[1] = 20, time[3] = 100): total duration 120 (time[1] = 20, time[4] = 40): total duration 60 Example 2: Input: time = [60,60,60] Output: 3 Explanation: All three pairs have a total duration of 120, which is divisible by 60.   Constraints: 1 <= time.length <= 6 * 104 1 <= time[i] <= 500
Medium
[ "array", "hash-table", "counting" ]
null
[]
1,011
capacity-to-ship-packages-within-d-days
[ "Binary search on the answer. We need a function possible(capacity) which returns true if and only if we can do the task in D days." ]
/** * @param {number[]} weights * @param {number} days * @return {number} */ var shipWithinDays = function(weights, days) { };
A conveyor belt has packages that must be shipped from one port to another within days days. The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.   Example 1: Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5 Output: 15 Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. Example 2: Input: weights = [3,2,2,4,1,4], days = 3 Output: 6 Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 Example 3: Input: weights = [1,2,3,1,1], days = 4 Output: 3 Explanation: 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1   Constraints: 1 <= days <= weights.length <= 5 * 104 1 <= weights[i] <= 500
Medium
[ "array", "binary-search" ]
[ "const shipWithinDays = function(weights, days) {\n let l = Math.max(...weights)\n let r = weights.reduce((ac, e) => ac + e, 0)\n while(l < r) {\n const mid = Math.floor((l + r) / 2)\n if(valid(mid)) {\n r = mid\n } else l = mid + 1\n }\n \n return l\n \n function valid(mid) {\n let res = 1, cur = 0\n for(let w of weights) {\n if(cur + w > mid) {\n cur = 0\n res++\n }\n cur += w\n }\n return res <= days\n }\n};" ]
1,012
numbers-with-repeated-digits
[ "How many numbers with no duplicate digits? How many numbers with K digits and no duplicates?", "How many numbers with same length as N? How many numbers with same prefix as N?" ]
/** * @param {number} n * @return {number} */ var numDupDigitsAtMostN = function(n) { };
Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit.   Example 1: Input: n = 20 Output: 1 Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11. Example 2: Input: n = 100 Output: 10 Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. Example 3: Input: n = 1000 Output: 262   Constraints: 1 <= n <= 109
Hard
[ "math", "dynamic-programming" ]
[ "const bitwiseComplement = function(N) {\n let binStr = bin(N)\n let str = ''\n for(let i = 0; i < binStr.length; i++) {\n str += binStr[i] === '0' ? '1' : '0'\n }\n return parseInt(str, 2)\n};\n\nfunction bin(N) {\n return (N >>> 0).toString(2)\n}" ]
1,013
partition-array-into-three-parts-with-equal-sum
[ "If we have three parts with the same sum, what is the sum of each?\r\nIf you can find the first part, can you find the second part?" ]
/** * @param {number[]} arr * @return {boolean} */ var canThreePartsEqualSum = function(arr) { };
Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums. Formally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])   Example 1: Input: arr = [0,2,1,-6,6,-7,9,1,2,0,1] Output: true Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1 Example 2: Input: arr = [0,2,1,-6,6,7,9,-1,2,0,1] Output: false Example 3: Input: arr = [3,3,6,5,-2,2,5,1,-9,4] Output: true Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4   Constraints: 3 <= arr.length <= 5 * 104 -104 <= arr[i] <= 104
Easy
[ "array", "greedy" ]
[ "const numPairsDivisibleBy60 = function(time) {\n const count = new Map();\n let n = 0;\n for (let t of time) {\n // two sum like method\n let d = (60 - t % 60) % 60;\n if (count.has(d)) { n += count.get(d); }\n count.set(t % 60, 1 + (count.get(t % 60) || 0));\n }\n return n;\n};" ]
1,014
best-sightseeing-pair
[ "Can you tell the best sightseeing spot in one pass (ie. as you iterate over the input?) What should we store or keep track of as we iterate to do this?" ]
/** * @param {number[]} values * @return {number} */ var maxScoreSightseeingPair = function(values) { };
You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them. The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them. Return the maximum score of a pair of sightseeing spots.   Example 1: Input: values = [8,1,5,2,6] Output: 11 Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11 Example 2: Input: values = [1,2] Output: 2   Constraints: 2 <= values.length <= 5 * 104 1 <= values[i] <= 1000
Medium
[ "array", "dynamic-programming" ]
[ "const shipWithinDays = function(weights, D) {\n let left = 0, right = 0;\n for (let w of weights) {\n left = Math.max(left, w);\n right += w;\n }\n while (left < right) {\n let mid = Math.floor((left + right) / 2), need = 1, cur = 0;\n for (let w of weights) {\n if (cur + w > mid) {\n need += 1;\n cur = 0;\n }\n cur += w;\n }\n if (need > D) left = mid + 1;\n else right = mid;\n }\n return left;\n}" ]
1,015
smallest-integer-divisible-by-k
[ "11111 = 1111 * 10 + 1\r\nWe only need to store remainders modulo K.", "If we never get a remainder of 0, why would that happen, and how would we know that?" ]
/** * @param {number} k * @return {number} */ var smallestRepunitDivByK = function(k) { };
Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1. Return the length of n. If there is no such n, return -1. Note: n may not fit in a 64-bit signed integer.   Example 1: Input: k = 1 Output: 1 Explanation: The smallest answer is n = 1, which has length 1. Example 2: Input: k = 2 Output: -1 Explanation: There is no such positive integer n divisible by 2. Example 3: Input: k = 3 Output: 3 Explanation: The smallest answer is n = 111, which has length 3.   Constraints: 1 <= k <= 105
Medium
[ "hash-table", "math" ]
[ "const numDupDigitsAtMostN = function(N) {\n const L = [];\n for (let x = N + 1; x > 0; x = Math.floor(x / 10)) L.unshift(x % 10);\n\n // Count the number with digits < N\n let res = 0,\n n = L.length;\n for (let i = 1; i < n; ++i) res += 9 * A(9, i - 1);\n\n const seen = new Set();\n for (let i = 0; i < n; ++i) {\n for (let j = i > 0 ? 0 : 1; j < L[i]; ++j)\n if (!seen.has(j)) res += A(9 - i, n - i - 1);\n if (seen.has(L[i])) break;\n seen.add(L[i]);\n }\n return N - res;\n};\n\nfunction A(m, n) {\n return n === 0 ? 1 : A(m, n - 1) * (m - n + 1);\n}" ]
1,016
binary-string-with-substrings-representing-1-to-n
[ "We only need to check substrings of length at most 30, because 10^9 has 30 bits." ]
/** * @param {string} s * @param {number} n * @return {boolean} */ var queryString = function(s, n) { };
Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "0110", n = 3 Output: true Example 2: Input: s = "0110", n = 4 Output: false   Constraints: 1 <= s.length <= 1000 s[i] is either '0' or '1'. 1 <= n <= 109
Medium
[ "string" ]
null
[]
1,017
convert-to-base-2
[ "Figure out whether you need the ones digit placed or not, then shift by two." ]
/** * @param {number} n * @return {string} */ var baseNeg2 = function(n) { };
Given an integer n, return a binary string representing its representation in base -2. Note that the returned string should not have leading zeros unless the string is "0".   Example 1: Input: n = 2 Output: "110" Explantion: (-2)2 + (-2)1 = 2 Example 2: Input: n = 3 Output: "111" Explantion: (-2)2 + (-2)1 + (-2)0 = 3 Example 3: Input: n = 4 Output: "100" Explantion: (-2)2 = 4   Constraints: 0 <= n <= 109
Medium
[ "math" ]
[ "const baseNeg2 = function(N) {\n return negBase(N, -2)\n};\n\nfunction negBase(val, base) {\n if(val === 0) return '0'\n\tlet result = '';\n\twhile (val !== 0) {\n\t\tlet remainder = val % base;\n\t\tval = Math.trunc(val / base);\n\t\tif (remainder < 0) {\n\t\t\tremainder += -base;\n\t\t\tval += 1;\n\t\t}\n\t\tresult = remainder + result;\n\t}\n\treturn result;\n}", "const baseNeg2 = function(N) {\n if (N === 0) return \"0\"; \n let res = ''\n while(N !== 0) {\n res = (N & 1) + res\n N = -(N >> 1)\n }\n return res; \n};" ]
1,018
binary-prefix-divisible-by-5
[ "If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits." ]
/** * @param {number[]} nums * @return {boolean[]} */ var prefixesDivBy5 = function(nums) { };
You are given a binary array nums (0-indexed). We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit). For example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5. Return an array of booleans answer where answer[i] is true if xi is divisible by 5.   Example 1: Input: nums = [0,1,1] Output: [true,false,false] Explanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. Only the first number is divisible by 5, so answer[0] is true. Example 2: Input: nums = [1,1,1] Output: [false,false,false]   Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.
Easy
[ "array" ]
[ "const prefixesDivBy5 = function(A) {\n const res = []\n let pre = 0\n const len = A.length\n for(let i = 0; i < len; i++) {\n pre = (pre % 100) * 2 + A[i]\n res.push(pre % 5 === 0 ? true : false)\n }\n return res\n};" ]
1,019
next-greater-node-in-linked-list
[ "We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j ." ]
/** * 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 {number[]} */ var nextLargerNodes = function(head) { };
You are given the head of a linked list with n nodes. For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.   Example 1: Input: head = [2,1,5] Output: [5,5,0] Example 2: Input: head = [2,7,4,3,5] Output: [7,0,5,5,0]   Constraints: The number of nodes in the list is n. 1 <= n <= 104 1 <= Node.val <= 109
Medium
[ "array", "linked-list", "stack", "monotonic-stack" ]
null
[]
1,020
number-of-enclaves
[ "Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map.", "In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary.\r\nReturn as answer the number of nodes that are not reachable from the exterior node." ]
/** * @param {number[][]} grid * @return {number} */ var numEnclaves = function(grid) { };
You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid. Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.   Example 1: Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] Output: 3 Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. Example 2: Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]] Output: 0 Explanation: All 1s are either on the boundary or can reach the boundary.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 500 grid[i][j] is either 0 or 1.
Medium
[ "array", "depth-first-search", "breadth-first-search", "union-find", "matrix" ]
[ "const canThreePartsEqualSum = function(A) {\n let lo = 0\n let hi = A.length - 1\n let lsum = 0\n let hsum = 0\n const sum = A.reduce((ac, el) => ac + el, 0)\n if(sum % 3 !== 0) return false\n const target = sum / 3\n\n while(lo < hi && lsum !== target) {\n lsum += A[lo]\n lo++\n }\n if(lsum !== target) return false\n while(lo < hi && hsum !== target) {\n hsum += A[hi]\n hi--\n }\n if(hsum !== target) return false\n\n let msum = 0\n for(let i = lo; i <= hi; i++) {\n msum += A[i]\n }\n if(msum !== target) return false\n return true\n};" ]
1,021
remove-outermost-parentheses
[ "Can you find the primitive decomposition? The number of ( and ) characters must be equal." ]
/** * @param {string} s * @return {string} */ var removeOuterParentheses = function(s) { };
A valid parentheses string is either empty "", "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B, with A and B nonempty valid parentheses strings. Given a valid parentheses string s, consider its primitive decomposition: s = P1 + P2 + ... + Pk, where Pi are primitive valid parentheses strings. Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s.   Example 1: Input: s = "(()())(())" Output: "()()()" Explanation: The input string is "(()())(())", with primitive decomposition "(()())" + "(())". After removing outer parentheses of each part, this is "()()" + "()" = "()()()". Example 2: Input: s = "(()())(())(()(()))" Output: "()()()()(())" Explanation: The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". Example 3: Input: s = "()()" Output: "" Explanation: The input string is "()()", with primitive decomposition "()" + "()". After removing outer parentheses of each part, this is "" + "" = "".   Constraints: 1 <= s.length <= 105 s[i] is either '(' or ')'. s is a valid parentheses string.
Easy
[ "string", "stack" ]
[ "const removeOuterParentheses = function(S) {\n let onum = 0\n let oidx = 0\n let cnum = 0\n let cidx = 0\n let res = ''\n const arr = S.split('')\n for(let i = 0, len = S.length; i < len; i++) {\n if(S[i] === '(') onum++\n if(S[i] === ')') cnum++\n if(onum === cnum) {\n res += arr.slice(oidx + 1, oidx + cnum * 2 - 1).join('')\n onum = 0\n cnum = 0\n oidx = i+1\n }\n }\n return res\n};" ]
1,022
sum-of-root-to-leaf-binary-numbers
[ "Find each path, then transform that path to an integer in base 10." ]
/** * 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 sumRootToLeaf = function(root) { };
You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers. The test cases are generated so that the answer fits in a 32-bits integer.   Example 1: Input: root = [1,0,1,0,1,0,1] Output: 22 Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 Example 2: Input: root = [0] Output: 0   Constraints: The number of nodes in the tree is in the range [1, 1000]. Node.val is 0 or 1.
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 smallestRepunitDivByK = function(K) {\n if (K % 2 === 0 || K % 5 === 0) return -1;\n let r = 0;\n for (let N = 1; N <= K; ++N) {\n r = (r * 10 + 1) % K;\n if (r == 0) return N;\n }\n return -1;\n};" ]
1,023
camelcase-matching
[ "Given a single pattern and word, how can we solve it?", "One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word.", "We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2)\r\nThe case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively." ]
/** * @param {string[]} queries * @param {string} pattern * @return {boolean[]} */ var camelMatch = function(queries, pattern) { };
Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.   Example 1: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB" Output: [true,false,true,true,false] Explanation: "FooBar" can be generated like this "F" + "oo" + "B" + "ar". "FootBall" can be generated like this "F" + "oot" + "B" + "all". "FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer". Example 2: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa" Output: [true,false,true,false,false] Explanation: "FooBar" can be generated like this "Fo" + "o" + "Ba" + "r". "FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll". Example 3: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT" Output: [false,true,false,false,false] Explanation: "FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est".   Constraints: 1 <= pattern.length, queries.length <= 100 1 <= queries[i].length <= 100 queries[i] and pattern consist of English letters.
Medium
[ "two-pointers", "string", "trie", "string-matching" ]
[ "const camelMatch = function(queries, pattern) {\n const res = []\n\n queries.forEach(el => {\n let tmp = chk(el, pattern)\n if(tmp) res.push(true)\n else res.push(false)\n })\n \n return res\n};\n\nfunction chk(str, p) {\n let pIdx = 0\n let sIdx = 0\n const sLen = str.length\n const pLen = p.length\n const Acode = ('A').charCodeAt(0)\n const Zcode = ('Z').charCodeAt(0)\n let pEnd = false\n\n for(let i = 0; i < pLen; i++) {\n let target = p.charAt(i)\n \n while(sIdx < sLen && !pEnd) {\n if(str.charCodeAt(sIdx) >= Acode && str.charCodeAt(sIdx) <= Zcode && str.charAt(sIdx) !== target) return false\n if(str.charAt(sIdx) === target) {\n if(i !== pLen - 1) {\n sIdx++\n } else {\n pEnd = true\n }\n break\n } else {\n sIdx++ \n }\n }\n if(sIdx >= sLen) return false\n }\n\n for(let i = sIdx + 1; pEnd && i < sLen; i++) {\n if(str.charCodeAt(i) >= Acode && str.charCodeAt(i) <= Zcode) return false\n }\n return true\n}" ]
1,024
video-stitching
[ "What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming?", "Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section." ]
/** * @param {number[][]} clips * @param {number} time * @return {number} */ var videoStitching = function(clips, time) { };
You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi. We can cut these clips into segments freely. For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7]. Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1.   Example 1: Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10 Output: 3 Explanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips. Then, we can reconstruct the sporting event as follows: We cut [1,9] into segments [1,2] + [2,8] + [8,9]. Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10]. Example 2: Input: clips = [[0,1],[1,2]], time = 5 Output: -1 Explanation: We cannot cover [0,5] with only [0,1] and [1,2]. Example 3: Input: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9 Output: 3 Explanation: We can take clips [0,4], [4,7], and [6,9].   Constraints: 1 <= clips.length <= 100 0 <= starti <= endi <= 100 1 <= time <= 100
Medium
[ "array", "dynamic-programming", "greedy" ]
[ "const videoStitching = function (clips, T) {\n clips.sort((a, b) => a[0] - b[0])\n if(T === 0) return 0\n let laststart = -1,\n curend = 0,\n count = 0\n for (let i = 0; i < clips.length; ) {\n if (clips[i][0] > curend) return -1\n let maxend = curend\n // while one clip's start is before or equal to current end\n while (i < clips.length && clips[i][0] <= curend) {\n maxend = Math.max(maxend, clips[i][1])\n i++\n }\n count++\n curend = maxend\n if (curend >= T) return count\n }\n return -1\n}", "const videoStitching = function (clips, T) {\n clips.sort((a, b) => a[0] - b[0])\n let res = 0\n for(let i = 0, start = 0, end = 0, len = clips.length; start < T; start = end, res++) {\n for(; i < len && clips[i][0] <= start; i++) {\n end = Math.max(end, clips[i][1])\n }\n if(start === end) return -1\n }\n return res\n}", "const videoStitching = function (clips, T) {\n const dp = Array(T + 1).fill( T + 1 )\n dp[0] = 0\n for(let i = 0; i <= T; i++) {\n for(let c of clips) {\n if(i >= c[0] && i <= c[1]) dp[i] = Math.min(dp[i], dp[c[0]] + 1)\n }\n if(dp[i] === T + 1) return -1\n }\n return dp[T]\n}" ]
1,025
divisor-game
[ "If the current number is even, we can always subtract a 1 to make it odd. If the current number is odd, we must subtract an odd number to make it even." ]
/** * @param {number} n * @return {boolean} */ var divisorGame = function(n) { };
Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of: Choosing any x with 0 < x < n and n % x == 0. Replacing the number n on the chalkboard with n - x. Also, if a player cannot make a move, they lose the game. Return true if and only if Alice wins the game, assuming both players play optimally.   Example 1: Input: n = 2 Output: true Explanation: Alice chooses 1, and Bob has no more moves. Example 2: Input: n = 3 Output: false Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.   Constraints: 1 <= n <= 1000
Easy
[ "math", "dynamic-programming", "brainteaser", "game-theory" ]
[ "const divisorGame = function(N) {\n let idx = 0 \n let x\n while(x = chk(N)) {\n idx++\n N = N - x\n }\n if(idx === 0) return false\n return idx % 2 === 1 ? true : false\n};\n\nfunction chk(num) {\n for(let i = 1; i < num; i++) {\n if(num % i === 0) return i\n }\n return false\n}" ]
1,026
maximum-difference-between-node-and-ancestor
[ "For each subtree, find the minimum value and maximum value of its descendants." ]
/** * 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 maxAncestorDiff = function(root) { };
Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b. A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.   Example 1: Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] Output: 7 Explanation: We have various ancestor-node differences, some of which are given below : |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. Example 2: Input: root = [1,null,2,null,0,3] Output: 3   Constraints: The number of nodes in the tree is in the range [2, 5000]. 0 <= Node.val <= 105
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 maxAncestorDiff = function(root) {\n const arr = []\n dfs(root, [], arr)\n let res = Number.MIN_VALUE\n for(let i = 0; i < arr.length; i++) {\n let el = arr[i]\n let max = Number.MIN_VALUE\n let min = Number.MAX_VALUE \n for(let j = 0; j < el.length; j++) {\n if(el[j] < min) min = el[j]\n if(el[j] > max) max = el[j]\n }\n if(Math.abs(max - min) > res) res = Math.abs(max - min)\n }\n return res\n};\n\nfunction dfs(node, arr, res) {\n if(node == null) return\n arr.push(node.val)\n if(node.left === null && node.right === null) {\n res.push(arr.slice(0))\n return\n }\n \n dfs(node.left, arr.slice(0), res)\n dfs(node.right, arr.slice(0), res)\n \n \n}" ]
1,027
longest-arithmetic-subsequence
[]
/** * @param {number[]} nums * @return {number} */ var longestArithSeqLength = function(nums) { };
Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. Note that: A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1).   Example 1: Input: nums = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: nums = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: nums = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= nums.length <= 1000 0 <= nums[i] <= 500
Medium
[ "array", "hash-table", "binary-search", "dynamic-programming" ]
[ "const longestArithSeqLength = function(A) {\n let a = A\n let n = A.length\n if (n <= 2) return n;\n\n let i, j, k, d;\n let mxl = 2;\n let current;\n let last;\n\n //i will be the index of first element of the ap\n for (i = 0; i < n - mxl; i++) {\n //j will be the index of second element of the ap\n for (j = i + 1; j < n - mxl + 1; j++) {\n //common difference\n d = a[j] - a[i];\n last = a[j];\n current = 2;\n\n for (k = j + 1; k < n; k++) {\n if (a[k] - last == d) {\n //here is our element\n current++;\n last = a[k];\n }\n }\n\n mxl = Math.max(mxl, current);\n }\n }\n\n return mxl;\n};" ]
1,028
recover-a-tree-from-preorder-traversal
[ "Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together." ]
/** * 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 {string} traversal * @return {TreeNode} */ var recoverFromPreorder = function(traversal) { };
We run a preorder depth-first search (DFS) on the root of a binary tree. At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.  If the depth of a node is D, the depth of its immediate child is D + 1.  The depth of the root node is 0. If a node has only one child, that child is guaranteed to be the left child. Given the output traversal of this traversal, recover the tree and return its root.   Example 1: Input: traversal = "1-2--3--4-5--6--7" Output: [1,2,5,3,4,6,7] Example 2: Input: traversal = "1-2--3---4-5--6---7" Output: [1,2,5,3,null,6,null,4,null,7] Example 3: Input: traversal = "1-401--349---90--88" Output: [1,401,null,349,88,90]   Constraints: The number of nodes in the original tree is in the range [1, 1000]. 1 <= Node.val <= 109
Hard
[ "string", "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 recoverFromPreorder = function(S) {\n const arr = []\n let tmp = S[0]\n for(let i = 1; i < S.length; i++) {\n if(S[i] === '-') {\n if(S[i-1] === '-') {\n tmp += '-'\n } else {\n arr.push(tmp)\n tmp = '-'\n }\n } else {\n if(S[i-1] === '-') {\n arr.push(tmp)\n tmp = S[i]\n } else {\n tmp += S[i]\n }\n }\n }\n arr.push(tmp)\n const resArr = []\n helper(resArr, arr, 0)\n return resArr[0]\n};\n\n\nfunction helper(nodeArr, strArr, idx) {\n if(idx >= strArr.length) return\n if(idx > 0) {\n \n if(strArr[idx].startsWith('-')) {\n helper(nodeArr, strArr, idx + 1)\n } else {\n nodeArr[idx] = new TreeNode(+strArr[idx])\n let d = strArr[idx - 1].length\n\n let tIdx\n\n for(let i = idx - 1; ; i = i - 2) {\n if(i>= 1) {\n if(strArr[i].length < d) {\n tIdx = i+1\n break\n }\n } else {\n\n tIdx = 0\n break\n }\n }\n \n if(nodeArr[tIdx].left) {\n nodeArr[tIdx].right = nodeArr[idx]\n } else {\n nodeArr[tIdx].left = nodeArr[idx]\n }\n helper(nodeArr, strArr, idx + 1)\n }\n\n } else {\n nodeArr[idx] = new TreeNode(+strArr[idx])\n helper(nodeArr, strArr, idx + 1)\n }\n \n}" ]
1,029
two-city-scheduling
[]
/** * @param {number[][]} costs * @return {number} */ var twoCitySchedCost = function(costs) { };
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti. Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.   Example 1: Input: costs = [[10,20],[30,200],[400,50],[30,20]] Output: 110 Explanation: The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. Example 2: Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]] Output: 1859 Example 3: Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]] Output: 3086   Constraints: 2 * n == costs.length 2 <= costs.length <= 100 costs.length is even. 1 <= aCosti, bCosti <= 1000
Medium
[ "array", "greedy", "sorting" ]
[ "const twoCitySchedCost = function(costs) {\n const N = costs.length / 2\n const dp = Array.from({ length: N + 1 }, () => new Array(N + 1).fill(0))\n for (let i = 1; i <= N; i++) {\n dp[i][0] = dp[i - 1][0] + costs[i - 1][0]\n }\n for (let j = 1; j <= N; j++) {\n dp[0][j] = dp[0][j - 1] + costs[j - 1][1]\n }\n for (let i = 1; i <= N; i++) {\n for (let j = 1; j <= N; j++) {\n dp[i][j] = Math.min(\n dp[i - 1][j] + costs[i + j - 1][0],\n dp[i][j - 1] + costs[i + j - 1][1]\n )\n }\n }\n return dp[N][N]\n}", "const twoCitySchedCost = function(costs) {\n const N = costs.length\n let res = 0\n const refund = []\n for(let i = 0; i < N; i++) {\n refund[i] = costs[i][1] - costs[i][0]\n res += costs[i][0]\n }\n refund.sort((a, b) => a - b)\n for(let i = 0; i < N / 2; i++) {\n res += refund[i]\n }\n return res\n};", "const twoCitySchedCost = function(costs) {\n const len = costs.length\n if(len === 0) return 0\n const N = len / 2\n costs.sort((a, b) => (a[0] - a[1]) - (b[0] - b[1]))\n let res = 0\n for(let i = 0; i < costs.length; i++) {\n if(i < N) {\n res += costs[i][0]\n } else {\n res += costs[i][1]\n }\n }\n return res\n};" ]
1,030
matrix-cells-in-distance-order
[]
/** * @param {number} rows * @param {number} cols * @param {number} rCenter * @param {number} cCenter * @return {number[][]} */ var allCellsDistOrder = function(rows, cols, rCenter, cCenter) { };
You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter). Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition. The distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|.   Example 1: Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0 Output: [[0,0],[0,1]] Explanation: The distances from (0, 0) to other cells are: [0,1] Example 2: Input: rows = 2, cols = 2, rCenter = 0, cCenter = 1 Output: [[0,1],[0,0],[1,1],[1,0]] Explanation: The distances from (0, 1) to other cells are: [0,1,1,2] The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct. Example 3: Input: rows = 2, cols = 3, rCenter = 1, cCenter = 2 Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]] Explanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3] There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].   Constraints: 1 <= rows, cols <= 100 0 <= rCenter < rows 0 <= cCenter < cols
Easy
[ "array", "math", "geometry", "sorting", "matrix" ]
[ "const nextLargerNodes = function(head) {\n const A = []\n while (head != null) A.push(head.val), (head = head.next)\n const res = new Array(A.length).fill(0)\n const stack = []\n for (let i = 0; i < A.length; i++) {\n while (stack.length && A[stack[stack.length - 1]] < A[i])\n res[stack.pop()] = A[i]\n stack.push(i)\n }\n return res\n}" ]
1,031
maximum-sum-of-two-non-overlapping-subarrays
[ "We can use prefix sums to calculate any subarray sum quickly.\r\nFor each L length subarray, find the best possible M length subarray that occurs before and after it." ]
/** * @param {number[]} nums * @param {number} firstLen * @param {number} secondLen * @return {number} */ var maxSumTwoNoOverlap = function(nums, firstLen, secondLen) { };
Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen. The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping. A subarray is a contiguous part of an array.   Example 1: Input: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2 Output: 20 Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2. Example 2: Input: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2 Output: 29 Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2. Example 3: Input: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3 Output: 31 Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.   Constraints: 1 <= firstLen, secondLen <= 1000 2 <= firstLen + secondLen <= 1000 firstLen + secondLen <= nums.length <= 1000 0 <= nums[i] <= 1000
Medium
[ "array", "dynamic-programming", "sliding-window" ]
[ "const maxSumTwoNoOverlap = function(A, L, M) {\n for(let i = 1, len = A.length; i < len; i++) {\n A[i] += A[i - 1]\n }\n let LMax = A[L - 1], MMax = A[M - 1], res = A[L + M - 1]\n for(let i = L + M, len = A.length; i < len; i++) {\n LMax = Math.max(LMax, A[i - M] - A[i - M - L])\n MMax = Math.max(MMax, A[i - L] - A[i - M - L])\n res = Math.max(res, Math.max(LMax + A[i] - A[i - M], MMax + A[i] - A[i - L]))\n }\n return res\n}", "const maxSumTwoNoOverlap = function(A, L, M) {\n let n = A.length\n let sum = []\n sum[0] = 0\n for (let i = 0; i < n; i++) sum[i + 1] = sum[i] + A[i]\n\n let ans = 0\n for (let i = L - 1; i + M < n; ++i) {\n for (let j = i + 1; j + M - 1 < n; ++j) {\n ans = Math.max(ans, sum[i + 1] - sum[i - L + 1] + sum[j + M] - sum[j])\n }\n }\n let tmp = L\n L = M\n M = tmp\n for (let i = L - 1; i + M < n; ++i) {\n for (let j = i + 1; j + M - 1 < n; ++j) {\n ans = Math.max(ans, sum[i + 1] - sum[i - L + 1] + sum[j + M] - sum[j])\n }\n }\n return ans\n}" ]
1,032
stream-of-characters
[ "Put the words into a trie, and manage a set of pointers within that trie." ]
/** * @param {string[]} words */ var StreamChecker = function(words) { }; /** * @param {character} letter * @return {boolean} */ StreamChecker.prototype.query = function(letter) { }; /** * Your StreamChecker object will be instantiated and called as such: * var obj = new StreamChecker(words) * var param_1 = obj.query(letter) */
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words. For example, if words = ["abc", "xyz"] and the stream added the four characters (one by one) 'a', 'x', 'y', and 'z', your algorithm should detect that the suffix "xyz" of the characters "axyz" matches "xyz" from words. Implement the StreamChecker class: StreamChecker(String[] words) Initializes the object with the strings array words. boolean query(char letter) Accepts a new character from the stream and returns true if any non-empty suffix from the stream forms a word that is in words.   Example 1: Input ["StreamChecker", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query"] [[["cd", "f", "kl"]], ["a"], ["b"], ["c"], ["d"], ["e"], ["f"], ["g"], ["h"], ["i"], ["j"], ["k"], ["l"]] Output [null, false, false, false, true, false, true, false, false, false, false, false, true] Explanation StreamChecker streamChecker = new StreamChecker(["cd", "f", "kl"]); streamChecker.query("a"); // return False streamChecker.query("b"); // return False streamChecker.query("c"); // return False streamChecker.query("d"); // return True, because 'cd' is in the wordlist streamChecker.query("e"); // return False streamChecker.query("f"); // return True, because 'f' is in the wordlist streamChecker.query("g"); // return False streamChecker.query("h"); // return False streamChecker.query("i"); // return False streamChecker.query("j"); // return False streamChecker.query("k"); // return False streamChecker.query("l"); // return True, because 'kl' is in the wordlist   Constraints: 1 <= words.length <= 2000 1 <= words[i].length <= 200 words[i] consists of lowercase English letters. letter is a lowercase English letter. At most 4 * 104 calls will be made to query.
Hard
[ "array", "string", "design", "trie", "data-stream" ]
[ "const StreamChecker = function(words) {\n this.maxLen = 0\n this.pos = -1\n this.s = []\n this.root = new Node()\n for (let w of words) {\n this.add(w)\n this.maxLen = Math.max(this.maxLen, w.length)\n }\n}\n\n\nStreamChecker.prototype.query = function(letter) {\n this.s[++this.pos] = letter\n return this.find(this.s, this.pos, Math.min(this.pos + 1, this.maxLen))\n}\n\nStreamChecker.prototype.add = function(word) {\n let len = word.length\n let p = this.root\n for (let i = len - 1; i >= 0; i--) {\n let k = word.charCodeAt(i) - 'a'.charCodeAt(0)\n if (p.child[k] == null) p.child[k] = new Node()\n p = p.child[k]\n }\n p.valid = true\n}\n\nStreamChecker.prototype.find = function(s, pos, len) {\n let p = this.root\n for (let i = 0; i < len; i++) {\n let k = s[pos - i].charCodeAt(0) - 'a'.charCodeAt(0)\n if (p.child[k] == null) return false\n p = p.child[k]\n if (p.valid) return true\n }\n return false\n}\nclass Node {\n constructor() {\n this.child = []\n this.valid = false\n }\n}" ]
1,033
moving-stones-until-consecutive
[ "For the minimum: We can always do it in at most 2 moves, by moving one stone next to another, then the third stone next to the other two. When can we do it in 1 move? 0 moves?\r\n\r\nFor the maximum: Every move, the maximum position minus the minimum position must decrease by at least 1." ]
/** * @param {number} a * @param {number} b * @param {number} c * @return {number[]} */ var numMovesStones = function(a, b, c) { };
There are three stones in different positions on the X-axis. You are given three integers a, b, and c, the positions of the stones. In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x, y, and z with x < y < z. You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y. The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where: answer[0] is the minimum number of moves you can play, and answer[1] is the maximum number of moves you can play.   Example 1: Input: a = 1, b = 2, c = 5 Output: [1,2] Explanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3. Example 2: Input: a = 4, b = 3, c = 2 Output: [0,0] Explanation: We cannot make any moves. Example 3: Input: a = 3, b = 5, c = 1 Output: [1,2] Explanation: Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.   Constraints: 1 <= a, b, c <= 100 a, b, and c have different values.
Medium
[ "math", "brainteaser" ]
[ "const numMovesStones = function(a, b, c) {\n let min = 0\n let min2 = 0\n let max = 0\n const arr= [a,b,c]\n arr.sort((a,b) => a - b)\n \n max = arr[2]-arr[1]-1 + arr[1] - arr[0] - 1\n min = (arr[2] - arr[1] > 1 ? 1 : 0) +(arr[1] - arr[0] > 1 ? 1 : 0)\n min2 = arr[2] - arr[1] === 2 || arr[1] - arr[0] === 2 ? 1 : Number.MAX_VALUE\n \n return [Math.min(min, min2), max]\n};" ]
1,034
coloring-a-border
[ "Use a DFS to find every square in the component. Then for each square, color it if it has a neighbor that is outside the grid or a different color." ]
/** * @param {number[][]} grid * @param {number} row * @param {number} col * @param {number} color * @return {number[][]} */ var colorBorder = function(grid, row, col, color) { };
You are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location. Two squares are called adjacent if they are next to each other in any of the 4 directions. Two squares belong to the same connected component if they have the same color and they are adjacent. The border of a connected component is all the squares in the connected component that are either adjacent to (at least) a square not in the component, or on the boundary of the grid (the first or last row or column). You should color the border of the connected component that contains the square grid[row][col] with color. Return the final grid.   Example 1: Input: grid = [[1,1],[1,2]], row = 0, col = 0, color = 3 Output: [[3,3],[3,2]] Example 2: Input: grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3 Output: [[1,3,3],[2,3,3]] Example 3: Input: grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2 Output: [[2,2,2],[2,1,2],[2,2,2]]   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 50 1 <= grid[i][j], color <= 1000 0 <= row < m 0 <= col < n
Medium
[ "array", "depth-first-search", "breadth-first-search", "matrix" ]
[ "const colorBorder = function(grid, r0, c0, color) {\n const dirs = [[-1,0], [1,0], [0,1], [0,-1]]\n const c = grid[r0][c0]\n const rows = grid.length\n const cols = grid[0].length\n const visited = Array.from({length: rows}, () => new Array(cols).fill(0))\n dfs(r0, c0, c, rows, cols, visited, grid, dirs)\n for(let i = 0; i < rows; i++) {\n for(let j = 0; j < cols; j++) {\n if(visited[i][j] === -1) {\n if(i === 0 || j === 0 || i === rows - 1 || j === cols - 1) {\n visited[i][j] = -2\n } else {\n for(let dir of dirs) {\n if(visited[i + dir[0]][j + dir[1]] === 0) {\n visited[i][j] = -2\n break\n }\n } \n }\n }\n }\n }\n for(let i = 0; i < rows; i++) {\n for(let j = 0; j < cols; j++) {\n if(visited[i][j] === -2) grid[i][j] = color\n }\n }\n \n return grid\n};\n\nfunction dfs(row, col, target, rows, cols, visited, grid, dirs) {\n if(row >= rows || col >= cols || row < 0 || col < 0 || grid[row][col] !== target || visited[row][col] === -1) {\n return \n }\n visited[row][col] = -1\n for(let dir of dirs) {\n dfs(row + dir[0], col+dir[1], target, rows, cols, visited, grid, dirs)\n }\n \n}" ]
1,035
uncrossed-lines
[ "Think dynamic programming. Given an oracle dp(i,j) that tells us how many lines A[i:], B[j:] [the sequence A[i], A[i+1], ... and B[j], B[j+1], ...] are uncrossed, can we write this as a recursion?" ]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var maxUncrossedLines = function(nums1, nums2) { };
You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that: nums1[i] == nums2[j], and the line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line). Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: nums1 = [1,4,2], nums2 = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2. Example 2: Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2] Output: 3 Example 3: Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1] Output: 2   Constraints: 1 <= nums1.length, nums2.length <= 500 1 <= nums1[i], nums2[j] <= 2000
Medium
[ "array", "dynamic-programming" ]
[ "const maxUncrossedLines = function(A, B) {\n const lenA = A.length\n const lenB = B.length\n const dp = Array.from({length: lenA + 1}, () => new Array(lenB + 1).fill(0))\n for(let i = 1; i <= lenA; i++) {\n for(let j = 1; j <= lenB; j++) {\n if(A[i - 1] === B[j - 1]) {\n dp[i][j] = 1 + dp[i - 1][j - 1]\n } else {\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])\n }\n }\n }\n return dp[lenA][lenB]\n};", "const maxUncrossedLines = function(A, B) {\n const m = A.length,\n n = B.length\n const dp = new Array(n + 1).fill(0)\n let prev\n\n for (let i = 1; i <= m; i++) {\n prev = dp[0]\n for (let j = 1; j <= n; j++) {\n let backup = dp[j]\n if (A[i - 1] == B[j - 1]) dp[j] = prev + 1\n else dp[j] = Math.max(dp[j], dp[j - 1])\n prev = backup\n }\n }\n\n return dp[n]\n}" ]
1,036
escape-a-large-maze
[ "If we become stuck, there's either a loop around the source or around the target.", "If there is a loop around say, the source, what is the maximum number of squares it can have?" ]
/** * @param {number[][]} blocked * @param {number[]} source * @param {number[]} target * @return {boolean} */ var isEscapePossible = function(blocked, source, target) { };
There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y). We start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. There is also an array of blocked squares, where each blocked[i] = [xi, yi] represents a blocked square with coordinates (xi, yi). Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid. Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves.   Example 1: Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2] Output: false Explanation: The target square is inaccessible starting from the source square because we cannot move. We cannot move north or east because those squares are blocked. We cannot move south or west because we cannot go outside of the grid. Example 2: Input: blocked = [], source = [0,0], target = [999999,999999] Output: true Explanation: Because there are no blocked cells, it is possible to reach the target square.   Constraints: 0 <= blocked.length <= 200 blocked[i].length == 2 0 <= xi, yi < 106 source.length == target.length == 2 0 <= sx, sy, tx, ty < 106 source != target It is guaranteed that source and target are not blocked.
Hard
[ "array", "hash-table", "depth-first-search", "breadth-first-search" ]
[ "const isEscapePossible = function(blocked, source, target) {\n const blockedSet = new Set()\n for (let el of blocked) {\n let key = el[0] + \",\" + el[1]\n blockedSet.add(key)\n }\n return canVisit(blockedSet, source, target) && canVisit(blockedSet, target, source)\n}\n\nfunction canVisit(blocked, start, end) {\n const visited = new Set()\n return dfs(blocked, start[0], start[1], end[0], end[1], visited)\n}\nfunction dfs(blocked, i, j, m, n, visited) {\n visited.add(i + \",\" + j)\n const dirs = [[i - 1, j], [i + 1, j], [i, j + 1], [i, j - 1]]\n if ((i == m && j == n) || visited.size >= 20000) {\n return true\n }\n for (let dir of dirs) {\n let nextKey = dir[0] + \",\" + dir[1]\n if (\n dir[0] >= 0 &&\n dir[1] >= 0 &&\n dir[0] < 1e6 &&\n dir[1] < 1e6 &&\n !blocked.has(nextKey) &&\n !visited.has(nextKey)\n ) {\n if (dfs(blocked, dir[0], dir[1], m, n, visited)) {\n return true\n }\n }\n }\n return false\n}", "const isEscapePossible = function(blocked, source, target) {\n if (blocked.length < 2) {\n return true\n }\n// if (blocked[0][0] == 100025) {\n// return false\n// }\n const blockSet = new Set(\n blocked.map(el => {\n return el[0] + \",\" + el[1]\n })\n )\n let targetR, targetC, curR, curC\n ;[targetR, targetC] = target\n let visited = new Set([])\n let DIRS = [[0, 1], [-1, 0], [0, -1], [1, 0]],\n queue = [source]\n const inBound = (r, c) => {\n return r >= 0 && c >= 0 && r < 1000000 && c < 1000000\n }\n let count = 0\n while (queue.length > 0) {\n count++\n ;[curR, curC] = queue.shift()\n\n if (count > 20000) {\n return true\n }\n for (let dir of DIRS) {\n const newR = curR + dir[0],\n newC = curC + dir[1]\n if (\n !inBound(newR, newC) ||\n blockSet.has(newR + \",\" + newC) ||\n visited.has(newR + \",\" + newC)\n ) {\n continue\n }\n\n if (newR == targetR && newC == targetC) {\n return true\n }\n visited.add(newR + \",\" + newC)\n queue.push([newR, newC])\n }\n }\n return false\n}" ]
1,037
valid-boomerang
[ "3 points form a boomerang if and only if the triangle formed from them has non-zero area." ]
/** * @param {number[][]} points * @return {boolean} */ var isBoomerang = function(points) { };
Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang. A boomerang is a set of three points that are all distinct and not in a straight line.   Example 1: Input: points = [[1,1],[2,3],[3,2]] Output: true Example 2: Input: points = [[1,1],[2,2],[3,3]] Output: false   Constraints: points.length == 3 points[i].length == 2 0 <= xi, yi <= 100
Easy
[ "array", "math", "geometry" ]
[ "const isBoomerang = function(points) {\n if(angle(points[0], points[1], points[2]) &&\n angle(points[1], points[2], points[0]) &&\n angle(points[1], points[0], points[2]) ) return false\n return true\n};\n\n// distinct or in a line\nfunction angle(p1, p2, p3) {\n if((p1[0] === p2[0] && p1[1] === p2[1]) ||\n (p2[0] === p3[0] && p2[1] === p3[1]) ||\n (p1[0] === p3[0] && p1[1] === p3[1]) ) return true\n \n return collinear(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1])\n}\nfunction collinear(x1, y1, x2, y2, x3, y3) { \n return (y3 - y2) * (x2 - x1) === (y2 - y1) * (x3 - x2)\n} " ]
1,038
binary-search-tree-to-greater-sum-tree
[ "What traversal method organizes all nodes in sorted order?" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {TreeNode} */ var bstToGst = function(root) { };
Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a binary search tree is a tree that satisfies these constraints: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.   Example 1: Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] Example 2: Input: root = [0,null,1] Output: [1,null,1]   Constraints: The number of nodes in the tree is in the range [1, 100]. 0 <= Node.val <= 100 All the values in the tree are unique.   Note: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/
Medium
[ "tree", "depth-first-search", "binary-search-tree", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const bstToGst = function(root) {\n const arr = []\n dfs(root, arr)\n let v = 0\n for(let i = arr.length - 1; i >= 0; i--) {\n arr[i].val = arr[i].val + v\n v = arr[i].val\n }\n return root\n};\n\nfunction dfs(node, arr) {\n if(node == null) return\n dfs(node.left, arr)\n arr.push(node)\n dfs(node.right, arr)\n}" ]
1,039
minimum-score-triangulation-of-polygon
[ "Without loss of generality, there is a triangle that uses adjacent vertices A[0] and A[N-1] (where N = A.length). Depending on your choice K of it, this breaks down the triangulation into two subproblems A[1:K] and A[K+1:N-1]." ]
/** * @param {number[]} values * @return {number} */ var minScoreTriangulation = function(values) { };
You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex (i.e., clockwise order). You will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation. Return the smallest possible total score that you can achieve with some triangulation of the polygon.   Example 1: Input: values = [1,2,3] Output: 6 Explanation: The polygon is already triangulated, and the score of the only triangle is 6. Example 2: Input: values = [3,7,4,5] Output: 144 Explanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144. The minimum score is 144. Example 3: Input: values = [1,3,1,4,1,5] Output: 13 Explanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.   Constraints: n == values.length 3 <= n <= 50 1 <= values[i] <= 100
Medium
[ "array", "dynamic-programming" ]
[ "const minScoreTriangulation = function(A) {\n if(A.length <= 2) return 0\n if(A.length === 3) return A[0] * A[1] * A[2]\n return chk(A, A.length)\n};\n\nfunction cost(points, i, j, k) {\n let p1 = points[i],\n p2 = points[j],\n p3 = points[k]\n return p1 * p2 * p3\n}\n\nfunction chk(points, n) {\n if (n < 3) return 0\n\n const table = Array.from({ length: n }, () => new Array(n).fill(0))\n\n for (let gap = 0; gap < n; gap++) {\n for (let i = 0, j = gap; j < n; i++, j++) {\n if (j < i + 2) table[i][j] = 0\n else {\n table[i][j] = Number.MAX_VALUE\n for (let k = i + 1; k < j; k++) {\n let val = table[i][k] + table[k][j] + cost(points, i, j, k)\n if (table[i][j] > val) table[i][j] = val\n }\n }\n }\n }\n return table[0][n - 1]\n}" ]
1,040
moving-stones-until-consecutive-ii
[ "For the minimum, how many cows are already in place?\r\nFor the maximum, we have to lose either the gap A[1] - A[0] or A[N-1] - A[N-2] (where N = A.length), but every other space can be occupied." ]
/** * @param {number[]} stones * @return {number[]} */ var numMovesStonesII = function(stones) { };
There are some stones in different positions on the X-axis. You are given an integer array stones, the positions of the stones. Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone. In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone. The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where: answer[0] is the minimum number of moves you can play, and answer[1] is the maximum number of moves you can play.   Example 1: Input: stones = [7,4,9] Output: [1,2] Explanation: We can move 4 -> 8 for one move to finish the game. Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game. Example 2: Input: stones = [6,5,4,3,10] Output: [2,3] Explanation: We can move 3 -> 8 then 10 -> 7 to finish the game. Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game. Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.   Constraints: 3 <= stones.length <= 104 1 <= stones[i] <= 109 All the values of stones are unique.
Medium
[ "array", "math", "two-pointers", "sorting" ]
[ "const numMovesStonesII = function(stones) {\nstones.sort((a, b) => a - b)\nlet n = stones.length;\nlet least = Number.MAX_VALUE, most = Number.MIN_VALUE;\n\nfor (let i = 0, j = 0; i < n; i++) {\n while (j + 1 < n && stones[j + 1] - stones[i] < n) j++;\n let now = n - (j - i + 1);\n if (j - i == n - 2 && stones[j] - stones[i] == j - i) now++;\n least = Math.min(least, now);\n}\n\nmost = Math.max(stones[n - 1] - stones[1], stones[n - 2] - stones[0]) - (n - 2);\nreturn [least, most];\n};" ]
1,041
robot-bounded-in-circle
[ "Calculate the final vector of how the robot travels after executing all instructions once - it consists of a change in position plus a change in direction.", "The robot stays in the circle if and only if (looking at the final vector) it changes direction (ie. doesn't stay pointing north), or it moves 0." ]
/** * @param {string} instructions * @return {boolean} */ var isRobotBounded = function(instructions) { };
On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that: The north direction is the positive direction of the y-axis. The south direction is the negative direction of the y-axis. The east direction is the positive direction of the x-axis. The west direction is the negative direction of the x-axis. The robot can receive one of three instructions: "G": go straight 1 unit. "L": turn 90 degrees to the left (i.e., anti-clockwise direction). "R": turn 90 degrees to the right (i.e., clockwise direction). The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.   Example 1: Input: instructions = "GGLLGG" Output: true Explanation: The robot is initially at (0, 0) facing the north direction. "G": move one step. Position: (0, 1). Direction: North. "G": move one step. Position: (0, 2). Direction: North. "L": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West. "L": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South. "G": move one step. Position: (0, 1). Direction: South. "G": move one step. Position: (0, 0). Direction: South. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0). Based on that, we return true. Example 2: Input: instructions = "GG" Output: false Explanation: The robot is initially at (0, 0) facing the north direction. "G": move one step. Position: (0, 1). Direction: North. "G": move one step. Position: (0, 2). Direction: North. Repeating the instructions, keeps advancing in the north direction and does not go into cycles. Based on that, we return false. Example 3: Input: instructions = "GL" Output: true Explanation: The robot is initially at (0, 0) facing the north direction. "G": move one step. Position: (0, 1). Direction: North. "L": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West. "G": move one step. Position: (-1, 1). Direction: West. "L": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South. "G": move one step. Position: (-1, 0). Direction: South. "L": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East. "G": move one step. Position: (0, 0). Direction: East. "L": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0). Based on that, we return true.   Constraints: 1 <= instructions.length <= 100 instructions[i] is 'G', 'L' or, 'R'.
Medium
[ "math", "string", "simulation" ]
[ "const isRobotBounded = function(instructions) {\n let x = 0, y = 0, i = 0, d = [[0, 1], [1, 0], [0, -1], [ -1, 0]];\n for (let j = 0; j < instructions.length; ++j)\n if (instructions.charAt(j) === 'R') i = (i + 1) % 4;\n else if (instructions .charAt(j) === 'L') i = (i + 3) % 4;\n else {\n x += d[i][0]; y += d[i][1];\n }\n return x == 0 && y == 0 || i > 0;\n};", "const isRobotBounded = function(instructions) {\n let x = 0, y = 0, i = 0\n const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]] // U, R, D, L\n for(let e of instructions) {\n if(e === 'R') {\n i = (i + 1) % 4\n } else if(e === 'L') {\n i = (i + 3) % 4\n } else {\n x += dirs[i][0]\n y += dirs[i][1]\n }\n }\n return x === 0 && y === 0 || i > 0\n};", "const isRobotBounded = function(instructions) {\n const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n let x = 0, y = 0, i = 0\n for(let ins of instructions) {\n if(ins === 'G') {\n const dir = dirs[i]\n x += dir[0]\n y += dir[1]\n } else if(ins === 'L') {\n i = i - 1 < 0 ? 3 : i - 1 \n } else if(ins === 'R') {\n i = i + 1 > 3 ? 0 : i + 1\n }\n }\n return x === 0 && y === 0 || i !== 0\n};" ]
1,042
flower-planting-with-no-adjacent
[ "Since each garden is connected to at most 3 gardens, there's always an available color for each garden. For example, if one garden is next to gardens with colors 1, 3, 4, then color #2 is available." ]
/** * @param {number} n * @param {number[][]} paths * @return {number[]} */ var gardenNoAdj = function(n, paths) { };
You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers. All gardens have at most 3 paths coming into or leaving it. Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.   Example 1: Input: n = 3, paths = [[1,2],[2,3],[3,1]] Output: [1,2,3] Explanation: Gardens 1 and 2 have different types. Gardens 2 and 3 have different types. Gardens 3 and 1 have different types. Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1]. Example 2: Input: n = 4, paths = [[1,2],[3,4]] Output: [1,2,1,2] Example 3: Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]] Output: [1,2,3,4]   Constraints: 1 <= n <= 104 0 <= paths.length <= 2 * 104 paths[i].length == 2 1 <= xi, yi <= n xi != yi Every garden has at most 3 paths coming into or leaving it.
Medium
[ "depth-first-search", "breadth-first-search", "graph" ]
[ "const gardenNoAdj = function(N, paths) {\n const map = {};\n for (let i = 0; i < N; i++) {\n map[i] = [];\n }\n for (let path of paths) {\n let l = path[0] - 1;\n let r = path[1] - 1;\n map[l].push(r);\n map[r].push(l);\n }\n const result = new Array(N).fill(-1);\n for (let i = 0; i < N; i++) {\n let colors = new Array(4).fill(false);\n for (let neighbor of map[i]) {\n if (result[neighbor] !== -1) {\n colors[result[neighbor]] = true;\n }\n }\n for (let j = 0; j < colors.length; j++) {\n if (!colors[j]) {\n result[i] = j;\n break;\n }\n }\n }\n return result.map(i => ++i);\n};" ]
1,043
partition-array-for-maximum-sum
[ "Think dynamic programming: dp[i] will be the answer for array A[0], ..., A[i-1].", "For j = 1 .. k that keeps everything in bounds, dp[i] is the maximum of dp[i-j] + max(A[i-1], ..., A[i-j]) * j ." ]
/** * @param {number[]} arr * @param {number} k * @return {number} */ var maxSumAfterPartitioning = function(arr, k) { };
Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray. Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.   Example 1: Input: arr = [1,15,7,9,2,5,10], k = 3 Output: 84 Explanation: arr becomes [15,15,15,9,10,10,10] Example 2: Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4 Output: 83 Example 3: Input: arr = [1], k = 1 Output: 1   Constraints: 1 <= arr.length <= 500 0 <= arr[i] <= 109 1 <= k <= arr.length
Medium
[ "array", "dynamic-programming" ]
[ "const maxSumAfterPartitioning = function(A, K) {\n const N = A.length\n const dp = new Array(N).fill(0);\n for (let i = 0; i < N; ++i) {\n let curMax = 0;\n for (let j = 1; j <= K && i - j + 1 >= 0; j++) {\n curMax = Math.max(curMax, A[i - j + 1]);\n dp[i] = Math.max(dp[i], (i >= j ? dp[i - j] : 0) + curMax * j);\n }\n }\n return dp[N - 1];\n};", "const maxSumAfterPartitioning = function(arr, k) {\n const n = arr.length, memo = Array(n + 1)\n memo[0] = 0\n return dp(n)\n \n function dp(i) {\n if(i === 0) return 0\n if(memo[i] != null) return memo[i]\n \n let sum = 0, max = 0, res = 0\n for(let j = i; j > 0 && i - j < k; j--) {\n max = Math.max(max, arr[j - 1])\n sum = (i - j + 1) * max\n res = Math.max(res, dp(j - 1) + sum)\n }\n return memo[i] = res\n }\n};" ]
1,044
longest-duplicate-substring
[ "Binary search for the length of the answer. (If there's an answer of length 10, then there are answers of length 9, 8, 7, ...)", "To check whether an answer of length K exists, we can use Rabin-Karp 's algorithm." ]
/** * @param {string} s * @return {string} */ var longestDupSubstring = function(s) { };
Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap. Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is "".   Example 1: Input: s = "banana" Output: "ana" Example 2: Input: s = "abcd" Output: ""   Constraints: 2 <= s.length <= 3 * 104 s consists of lowercase English letters.
Hard
[ "string", "binary-search", "sliding-window", "rolling-hash", "suffix-array", "hash-function" ]
[ "const longestDupSubstring = function(s) {\n const n = s.length\n let l = 0, r = n, res = ''\n while(l < r) {\n const mid = (l + r + 1) >> 1\n const [chk, str] = valid(s, mid)\n if(chk) {\n l = mid\n res = str\n } else {\n r = mid - 1\n }\n }\n return res\n};\n\nfunction valid(s, len) {\n const set = new Set()\n for(let i = 0, n = s.length; i <= n - len; i++) {\n const tmp = s.substr(i, len)\n if(set.has(tmp)) return [true, tmp]\n set.add(tmp)\n }\n \n return [false, '']\n}", "const longestDupSubstring = function(S) {\n const R = 26,\n MOD = 1e9 + 7\n let lo = 0,\n hi = S.length - 1,\n res = ''\n while (lo < hi) {\n const len = Math.ceil((lo + hi) / 2)\n const sub = rabinKarp(S, len)\n if (sub !== '') {\n lo = len\n res = sub\n } else {\n hi = len - 1\n }\n }\n return res\n\n function rabinKarp(str, len) {\n const aCode = ('a').charCodeAt(0)\n let RM = 1\n // 等价于RM=Math.pow(R,M-1) % MOD\n // 由于JS精度问题拆解计算\n for (let i = 1; i < len; i++) {\n RM = (RM * R) % MOD\n }\n const map = new Map()\n let num = 0\n // 计算前len个字符串的散列值\n for (let i = 0; i < len; i++) {\n const code = str.charCodeAt(i) - aCode\n num = (num * R + code) % MOD\n }\n map.set(num, 0)\n // 后续计算散列值\n for (let i = 0; i < str.length - len; i++) {\n const preCode = str.charCodeAt(i) - aCode,\n curCode = str.charCodeAt(i + len) - aCode\n num = (num + MOD - ((preCode * RM) % MOD)) % MOD\n num = (num * R + curCode) % MOD\n if (map.has(num)) {\n const sub = str.substring(i + 1, i + 1 + len)\n const preId = map.get(num),\n preSub = str.substring(preId, preId + len)\n if (sub === preSub) return sub\n }\n map.set(num, i + 1)\n }\n return ''\n }\n}" ]
1,046
last-stone-weight
[ "Simulate the process. We can do it with a heap, or by sorting some list of stones every time we take a turn." ]
/** * @param {number[]} stones * @return {number} */ var lastStoneWeight = function(stones) { };
You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is: If x == y, both stones are destroyed, and If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x. At the end of the game, there is at most one stone left. Return the weight of the last remaining stone. If there are no stones left, return 0.   Example 1: Input: stones = [2,7,4,1,8,1] Output: 1 Explanation: We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone. Example 2: Input: stones = [1] Output: 1   Constraints: 1 <= stones.length <= 30 1 <= stones[i] <= 1000
Easy
[ "array", "heap-priority-queue" ]
[ "const lastStoneWeight = function(stones) {\n stones.sort((a, b) => a - b)\n while (stones.length > 1) {\n const num = Math.abs(stones.pop() - stones.pop())\n stones.splice(stones.findIndex(item => item >= num), 0, num)\n }\n return stones[0] \n};" ]
1,047
remove-all-adjacent-duplicates-in-string
[ "Use a stack to process everything greedily." ]
/** * @param {string} s * @return {string} */ var removeDuplicates = function(s) { };
You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. We repeatedly make duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.   Example 1: Input: s = "abbaca" Output: "ca" Explanation: For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". Example 2: Input: s = "azxxzy" Output: "ay"   Constraints: 1 <= s.length <= 105 s consists of lowercase English letters.
Easy
[ "string", "stack" ]
[ "const removeDuplicates = function(S) {\n const queue = []\n for(let i = 0; i < S.length; i++) {\n if(queue.length > 0 && queue[queue.length - 1] === S[i]) {\n queue.pop()\n } else {\n queue.push(S[i])\n }\n }\n return queue.join('')\n};" ]
1,048
longest-string-chain
[ "Instead of adding a character, try deleting a character to form a chain in reverse.", "For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1)." ]
/** * @param {string[]} words * @return {number} */ var longestStrChain = function(words) { };
You are given an array of words where each word consists of lowercase English letters. wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB. For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad". A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1. Return the length of the longest possible word chain with words chosen from the given list of words.   Example 1: Input: words = ["a","b","ba","bca","bda","bdca"] Output: 4 Explanation: One of the longest word chains is ["a","ba","bda","bdca"]. Example 2: Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"] Output: 5 Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"]. Example 3: Input: words = ["abcd","dbqca"] Output: 1 Explanation: The trivial word chain ["abcd"] is one of the longest word chains. ["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.   Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 16 words[i] only consists of lowercase English letters.
Medium
[ "array", "hash-table", "two-pointers", "string", "dynamic-programming" ]
[ "const longestStrChain = function(words) {\n words.sort((a, b) => a.length - b.length)\n const dp = {}\n for(let el of words) {\n dp[el] = 1\n }\n \n let res = Number.MIN_VALUE\n for(let w of words) {\n for(let i = 0; i < w.length; i++) {\n let prev = w.slice(0, i) + w.slice(i + 1)\n dp[w] = Math.max(dp[w], (dp[prev] || 0) + 1 )\n }\n if(dp[w] > res) res = dp[w]\n }\n return res\n};" ]
1,049
last-stone-weight-ii
[ "Think of the final answer as a sum of weights with + or - sign symbols infront of each weight. Actually, all sums with 1 of each sign symbol are possible.", "Use dynamic programming: for every possible sum with N stones, those sums +x or -x is possible with N+1 stones, where x is the value of the newest stone. (This overcounts sums that are all positive or all negative, but those don't matter.)" ]
/** * @param {number[]} stones * @return {number} */ var lastStoneWeightII = function(stones) { };
You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: If x == y, both stones are destroyed, and If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x. At the end of the game, there is at most one stone left. Return the smallest possible weight of the left stone. If there are no stones left, return 0.   Example 1: Input: stones = [2,7,4,1,8,1] Output: 1 Explanation: We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then, we can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then, we can combine 2 and 1 to get 1, so the array converts to [1,1,1] then, we can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value. Example 2: Input: stones = [31,26,33,21,40] Output: 5   Constraints: 1 <= stones.length <= 30 1 <= stones[i] <= 100
Medium
[ "array", "dynamic-programming" ]
[ "const lastStoneWeightII = function(stones) {\n let sum=stones.reduce((a,b)=>a+b)\n let dp=Array(sum+1).fill(0)\n dp[0]=1\n for(let i=0;i<stones.length;i++){\n let cur=stones[i]\n for(let j=dp.length-1;j>=0;j--){\n if(j-stones[i]<0)break\n if(dp[j-stones[i]]){\n dp[j]=1\n }\n }\n }\n\n let minLen=Infinity\n for(let i=0;i<dp.length;i++){\n if(dp[i]){\n if(i*2-sum>=0)minLen=Math.min(minLen,i*2-sum)\n }\n }\n return minLen\n};" ]
1,051
height-checker
[ "Build the correct order of heights by sorting another array, then compare the two arrays." ]
/** * @param {number[]} heights * @return {number} */ var heightChecker = function(heights) { };
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line. You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed). Return the number of indices where heights[i] != expected[i].   Example 1: Input: heights = [1,1,4,2,1,3] Output: 3 Explanation: heights: [1,1,4,2,1,3] expected: [1,1,1,2,3,4] Indices 2, 4, and 5 do not match. Example 2: Input: heights = [5,1,2,3,4] Output: 5 Explanation: heights: [5,1,2,3,4] expected: [1,2,3,4,5] All indices do not match. Example 3: Input: heights = [1,2,3,4,5] Output: 0 Explanation: heights: [1,2,3,4,5] expected: [1,2,3,4,5] All indices match.   Constraints: 1 <= heights.length <= 100 1 <= heights[i] <= 100
Easy
[ "array", "sorting", "counting-sort" ]
[ "const heightChecker = function(heights) {\n const arr = heights.slice(0).sort((a, b) => a - b)\n let res = 0\n for(let i = 0, len = heights.length; i < len; i++) {\n if(arr[i] !== heights[i]) res++\n }\n \n return res\n};" ]
1,052
grumpy-bookstore-owner
[ "Say the store owner uses their power in minute 1 to X and we have some answer A. If they instead use their power from minute 2 to X+1, we only have to use data from minutes 1, 2, X and X+1 to update our answer A." ]
/** * @param {number[]} customers * @param {number[]} grumpy * @param {number} minutes * @return {number} */ var maxSatisfied = function(customers, grumpy, minutes) { };
There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end of that minute. On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once. Return the maximum number of customers that can be satisfied throughout the day.   Example 1: Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3 Output: 16 Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16. Example 2: Input: customers = [1], grumpy = [0], minutes = 1 Output: 1   Constraints: n == customers.length == grumpy.length 1 <= minutes <= n <= 2 * 104 0 <= customers[i] <= 1000 grumpy[i] is either 0 or 1.
Medium
[ "array", "sliding-window" ]
[ "const maxSatisfied = function(customers, grumpy, X) {\n if (customers.length === 1) return customers[0]\n const totalSatisfiedCustomers = customers.reduce(\n (ac, el, idx) => ac + (grumpy[idx] === 0 ? el : 0),\n 0\n )\n const arr = customers.map((el, idx) => (grumpy[idx] === 1 ? el : 0))\n const acArr = []\n let ac = 0\n for (let i = 0, len = arr.length; i < len; i++) {\n acArr[i] = ac = ac + arr[i]\n }\n let max = 0\n for (let i = X - 1, len = grumpy.length; i < len; i++) {\n let tmp = i - X < 0 ? 0 : acArr[i - X]\n if (acArr[i] - tmp > max) max = acArr[i] - tmp\n }\n\n return totalSatisfiedCustomers + max\n}", "const maxSatisfied = function (customers, grumpy, X) {\n let satisfied = 0,\n maxMakeSatisfied = 0\n for (let i = 0, winOfMakeSatisfied = 0; i < grumpy.length; ++i) {\n if (grumpy[i] === 0) {\n satisfied += customers[i]\n } else {\n winOfMakeSatisfied += customers[i]\n }\n if (i >= X) {\n winOfMakeSatisfied -= grumpy[i - X] * customers[i - X]\n }\n maxMakeSatisfied = Math.max(winOfMakeSatisfied, maxMakeSatisfied)\n }\n return satisfied + maxMakeSatisfied\n}" ]
1,053
previous-permutation-with-one-swap
[ "You need to swap two values, one larger than the other. Where is the larger one located?" ]
/** * @param {number[]} arr * @return {number[]} */ var prevPermOpt1 = function(arr) { };
Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap. If it cannot be done, then return the same array. Note that a swap exchanges the positions of two numbers arr[i] and arr[j]   Example 1: Input: arr = [3,2,1] Output: [3,1,2] Explanation: Swapping 2 and 1. Example 2: Input: arr = [1,1,5] Output: [1,1,5] Explanation: This is already the smallest permutation. Example 3: Input: arr = [1,9,4,6,7] Output: [1,7,4,6,9] Explanation: Swapping 9 and 7.   Constraints: 1 <= arr.length <= 104 1 <= arr[i] <= 104
Medium
[ "array", "greedy" ]
[ "const prevPermOpt1 = function(A) {\n let n = A.length, left = n - 2, right = n - 1;\n while (left >= 0 && A[left] <= A[left + 1]) left--;\n if (left < 0) return A;\n while (A[left] <= A[right]) right--;\n while (A[right - 1] == A[right]) right--;\n swap(A,left,right)\n return A;\n};\nfunction swap(a, i, j) {\n let tmp = a[i]\n a[i] = a[j]\n a[j] = tmp\n}" ]
1,054
distant-barcodes
[ "We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?" ]
/** * @param {number[]} barcodes * @return {number[]} */ var rearrangeBarcodes = function(barcodes) { };
In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i]. Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.   Example 1: Input: barcodes = [1,1,1,2,2,2] Output: [2,1,2,1,2,1] Example 2: Input: barcodes = [1,1,1,1,2,2,3,3] Output: [1,3,1,3,1,2,1,2]   Constraints: 1 <= barcodes.length <= 10000 1 <= barcodes[i] <= 10000
Medium
[ "array", "hash-table", "greedy", "sorting", "heap-priority-queue", "counting" ]
[ "const rearrangeBarcodes = function(barcodes) {\n const hash = {}\n let maxFreq = 0, max = 0\n for(const e of barcodes) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n if(hash[e] > maxFreq) {\n maxFreq = hash[e]\n max = e\n }\n }\n const n = barcodes.length\n const entries = Object.entries(hash)\n const res = Array(n)\n let idx = 0\n while(maxFreq) {\n res[idx] = max\n idx += 2\n maxFreq--\n }\n for(let [v, f] of entries) {\n if(+v === max) continue\n while(f) {\n if(idx >= n) idx = 1\n res[idx] = +v\n idx += 2\n f--\n }\n }\n \n return res\n};", "const rearrangeBarcodes = function(barcodes) {\n\tconst map = {};\n\tbarcodes.forEach(b => map[b] = (map[b] || 0) + 1);\n\tconst keys = Object.keys(map).sort((k1, k2) => map[k1] - map[k2]);\n\n\tlet idx = 1;\n\tfor (let k of keys) {\n\t\tlet t = map[k];\n\n\t\tfor (let i = 0; i < t; i++) {\n\t\t\tif (idx >= barcodes.length) idx = 0;\n\t\t\tbarcodes[idx] = k;\n\t\t\tidx += 2;\n\t\t}\n\t}\n\n\treturn barcodes;\n};", "const rearrangeBarcodes = function(barcodes) {\n const hash = {}, n = barcodes.length\n for(let e of barcodes) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n const res = Array(n)\n let max = 0, idx = -1\n for(let k in hash) {\n if(hash[k] > max) {\n max = hash[k]\n idx = +k\n }\n }\n let i = 0\n // max freq first\n while(max > 0) {\n res[i] = idx\n max--\n i += 2\n }\n // the rest\n const keys = Object.keys(hash).map(e => +e)\n for(let j = 0, len = keys.length; j < len; j++) {\n if(keys[j] !== idx) {\n const k = keys[j]\n let freq = hash[k]\n while(freq > 0) {\n if(i >= n) i = 1\n res[i] = k\n freq--\n i += 2\n }\n }\n }\n \n return res\n};" ]
1,061
lexicographically-smallest-equivalent-string
[ "Model these equalities as edges of a graph.", "Group each connected component of the graph and assign each node of this component to the node with the lowest lexicographically character.", "Finally convert the string with the precalculated information." ]
/** * @param {string} s1 * @param {string} s2 * @param {string} baseStr * @return {string} */ var smallestEquivalentString = function(s1, s2, baseStr) { };
You are given two strings of the same length s1 and s2 and a string baseStr. We say s1[i] and s2[i] are equivalent characters. For example, if s1 = "abc" and s2 = "cde", then we have 'a' == 'c', 'b' == 'd', and 'c' == 'e'. Equivalent characters follow the usual rules of any equivalence relation: Reflexivity: 'a' == 'a'. Symmetry: 'a' == 'b' implies 'b' == 'a'. Transitivity: 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'. For example, given the equivalency information from s1 = "abc" and s2 = "cde", "acd" and "aab" are equivalent strings of baseStr = "eed", and "aab" is the lexicographically smallest equivalent string of baseStr. Return the lexicographically smallest equivalent string of baseStr by using the equivalency information from s1 and s2.   Example 1: Input: s1 = "parker", s2 = "morris", baseStr = "parser" Output: "makkek" Explanation: Based on the equivalency information in s1 and s2, we can group their characters as [m,p], [a,o], [k,r,s], [e,i]. The characters in each group are equivalent and sorted in lexicographical order. So the answer is "makkek". Example 2: Input: s1 = "hello", s2 = "world", baseStr = "hold" Output: "hdld" Explanation: Based on the equivalency information in s1 and s2, we can group their characters as [h,w], [d,e,o], [l,r]. So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld". Example 3: Input: s1 = "leetcode", s2 = "programs", baseStr = "sourcecode" Output: "aauaaaaada" Explanation: We group the equivalent characters in s1 and s2 as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada".   Constraints: 1 <= s1.length, s2.length, baseStr <= 1000 s1.length == s2.length s1, s2, and baseStr consist of lowercase English letters.
Medium
[ "string", "union-find" ]
[ "var smallestEquivalentString = function (s1, s2, baseStr) {\n if (s1.length === 0 || s2.length === 0) return ''\n const uf = new UnionFind()\n for (let i = 0; i < s1.length; i++) {\n uf.union(s1[i], s2[i])\n }\n let res = ''\n for (const ch of baseStr) {\n res += uf.find(ch) || ch // some letters don't have connected component\n }\n return res\n}\nclass UnionFind {\n constructor() {\n this.parents = new Map()\n }\n find(x) {\n if (this.parents.get(x) === x) return x\n this.parents.set(x, this.find(this.parents.get(x))) // path compression\n return this.parents.get(x)\n }\n union(u, v) {\n // init\n if (!this.parents.has(u)) {\n this.parents.set(u, u)\n }\n if (!this.parents.has(v)) {\n this.parents.set(v, v)\n }\n // find root\n const rootU = this.find(u)\n const rootV = this.find(v)\n if (rootU === rootV) return // connected already\n // set smallest lex as the root\n if (rootU > rootV) {\n this.parents.set(rootU, rootV)\n } else {\n this.parents.set(rootV, rootU)\n }\n }\n}" ]
1,071
greatest-common-divisor-of-strings
[ "The greatest common divisor must be a prefix of each string, so we can try all prefixes." ]
/** * @param {string} str1 * @param {string} str2 * @return {string} */ var gcdOfStrings = function(str1, str2) { };
For two strings s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.   Example 1: Input: str1 = "ABCABC", str2 = "ABC" Output: "ABC" Example 2: Input: str1 = "ABABAB", str2 = "ABAB" Output: "AB" Example 3: Input: str1 = "LEET", str2 = "CODE" Output: ""   Constraints: 1 <= str1.length, str2.length <= 1000 str1 and str2 consist of English uppercase letters.
Easy
[ "math", "string" ]
[ "const gcdOfStrings = function(str1, str2) {\n let res = \"\";\n\n if (str1[0] !== str2[0]) return res;\n if (str1[str1.length - 1] !== str2[str2.length - 1]) return res;\n let s = str1[0];\n let e = str1[str1.length - 1];\n\n let loopStr = str1.length > str2.length ? str2 : str1;\n for (let i = 1, len = loopStr.length; i < len; i++) {\n if (loopStr[i] !== e) continue;\n let tmp = loopStr.slice(0, i + 1);\n let ok1 = false;\n let ok2 = false;\n let t1 = \"\";\n let t2 = \"\";\n while (t1.length < str1.length) {\n t1 += tmp;\n if (t1 === str1) {\n ok1 = true;\n break;\n }\n }\n while (t2.length < str2.length) {\n t2 += tmp;\n if (t2 === str2) {\n ok2 = true;\n break;\n }\n }\n\n if (ok1 && ok2 && tmp.length > res.length) res = tmp;\n }\n\n return res;\n};" ]
1,072
flip-columns-for-maximum-number-of-equal-rows
[ "Flipping a subset of columns is like doing a bitwise XOR of some number K onto each row. We want rows X with X ^ K = all 0s or all 1s. This is the same as X = X^K ^K = (all 0s or all 1s) ^ K, so we want to count rows that have opposite bits set. For example, if K = 1, then we count rows X = (00000...001, or 1111....110)." ]
/** * @param {number[][]} matrix * @return {number} */ var maxEqualRowsAfterFlips = function(matrix) { };
You are given an m x n binary matrix matrix. You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa). Return the maximum number of rows that have all values equal after some number of flips.   Example 1: Input: matrix = [[0,1],[1,1]] Output: 1 Explanation: After flipping no values, 1 row has all values equal. Example 2: Input: matrix = [[0,1],[1,0]] Output: 2 Explanation: After flipping values in the first column, both rows have equal values. Example 3: Input: matrix = [[0,0,0],[0,0,1],[1,1,0]] Output: 2 Explanation: After flipping values in the first two columns, the last two rows have equal values.   Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 300 matrix[i][j] is either 0 or 1.
Medium
[ "array", "hash-table", "matrix" ]
[ "const maxEqualRowsAfterFlips = function(matrix) {\n let n = matrix.length,\n m = matrix[0].length;\n let ret = 0;\n for (let i = 0; i < n; i++) {\n let ct = 0;\n inner: for (let j = i; j < n; j++) {\n if (ae(matrix[i], matrix[j])) {\n ct++;\n } else {\n for (let k = 0; k < m; k++) {\n if (matrix[i][k] + matrix[j][k] !== 1) continue inner;\n }\n ct++;\n }\n }\n ret = Math.max(ret, ct);\n }\n return ret;\n};\n\nfunction ae(a1, a2) {\n if (a1.length !== a2.length) return false;\n for (let i = 0; i < a1.length; i++) {\n if (a1[i] !== a2[i]) return false;\n }\n return true;\n}" ]
1,073
adding-two-negabinary-numbers
[ "We can try to determine the last digit of the answer, then divide everything by 2 and repeat." ]
/** * @param {number[]} arr1 * @param {number[]} arr2 * @return {number[]} */ var addNegabinary = function(arr1, arr2) { };
Given two numbers arr1 and arr2 in base -2, return the result of adding them together. Each number is given in array format:  as an array of 0s and 1s, from most significant bit to least significant bit.  For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3.  A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1. Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.   Example 1: Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1] Output: [1,0,0,0,0] Explanation: arr1 represents 11, arr2 represents 5, the output represents 16. Example 2: Input: arr1 = [0], arr2 = [0] Output: [0] Example 3: Input: arr1 = [0], arr2 = [1] Output: [1]   Constraints: 1 <= arr1.length, arr2.length <= 1000 arr1[i] and arr2[i] are 0 or 1 arr1 and arr2 have no leading zeros
Medium
[ "array", "math" ]
[ "const addNegabinary = function(arr1, arr2) {\n let ret = [];\n arr1.reverse();\n arr2.reverse();\n let n = arr1.length,\n m = arr2.length,\n g = 0;\n for (let i = 0; i < Math.max(n, m); i++) {\n let s = g;\n if (i < n) s += arr1[i];\n if (i < m) s += arr2[i];\n g = (s / -2) >> 0;\n if (s + g * 2 < 0) g++;\n ret.push(s + g * 2);\n }\n while (g) {\n let s = g;\n g = (s / -2) >> 0;\n if (s + g * 2 < 0) g++;\n ret.push(s + g * 2);\n }\n while (ret.length > 1 && ret[ret.length - 1] == 0) ret.pop();\n ret.reverse();\n return ret;\n};" ]
1,074
number-of-submatrices-that-sum-to-target
[ "Using a 2D prefix sum, we can query the sum of any submatrix in O(1) time.\r\nNow for each (r1, r2), we can find the largest sum of a submatrix that uses every row in [r1, r2] in linear time using a sliding window." ]
/** * @param {number[][]} matrix * @param {number} target * @return {number} */ var numSubmatrixSumTarget = function(matrix, target) { };
Given a matrix and a target, return the number of non-empty submatrices that sum to target. A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2. Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.   Example 1: Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0 Output: 4 Explanation: The four 1x1 submatrices that only contain 0. Example 2: Input: matrix = [[1,-1],[-1,1]], target = 0 Output: 5 Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix. Example 3: Input: matrix = [[904]], target = 0 Output: 0   Constraints: 1 <= matrix.length <= 100 1 <= matrix[0].length <= 100 -1000 <= matrix[i] <= 1000 -10^8 <= target <= 10^8
Hard
[ "array", "hash-table", "matrix", "prefix-sum" ]
[ "const numSubmatrixSumTarget = function(matrix, target) {\n let a = matrix\n let n = a.length, m = a[0].length;\n const cum = Array.from({length: n + 1}, () => new Array(m + 1).fill(0));\n for(let i = 0;i < n;i++){\n for(let j = 0;j < m;j++){\n cum[i+1][j+1] = cum[i+1][j] + cum[i][j+1] - cum[i][j] + a[i][j];\n }\n }\n\n let ans = 0;\n for(let i = 0;i < n;i++){\n for(let j = i;j < n;j++){\n let map = new Map();\n for(let k = 0;k <= m;k++){\n let v = cum[j+1][k] - cum[i][k];\n if(map.has(v - target)){\n ans += map.get(v-target);\n }\n if(map.has(v)){\n map.set(v, map.get(v)+1);\n }else{\n map.set(v, 1);\n }\n }\n }\n }\n return ans;\n};" ]
1,078
occurrences-after-bigram
[ "Split the string into words, then look at adjacent triples of words." ]
/** * @param {string} text * @param {string} first * @param {string} second * @return {string[]} */ var findOcurrences = function(text, first, second) { };
Given two strings first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second. Return an array of all the words third for each occurrence of "first second third".   Example 1: Input: text = "alice is a good girl she is a good student", first = "a", second = "good" Output: ["girl","student"] Example 2: Input: text = "we will we will rock you", first = "we", second = "will" Output: ["we","rock"]   Constraints: 1 <= text.length <= 1000 text consists of lowercase English letters and spaces. All the words in text a separated by a single space. 1 <= first.length, second.length <= 10 first and second consist of lowercase English letters.
Easy
[ "string" ]
null
[]
1,079
letter-tile-possibilities
[ "Try to build the string with a backtracking DFS by considering what you can put in every position." ]
/** * @param {string} tiles * @return {number} */ var numTilePossibilities = function(tiles) { };
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
Medium
[ "hash-table", "string", "backtracking", "counting" ]
[ "const numTilePossibilities = function(tiles) {\n const obj = { count: 0 };\n dfs(tiles, new Array(tiles.length).fill(false), new Set(), \"\", obj);\n return obj.count;\n};\n\nfunction dfs(tiles, used, visited, path, obj) {\n if (path !== \"\" && !visited.has(path)) obj.count++;\n visited.add(path)\n\n for (let i = 0; i < tiles.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n dfs(tiles, used, visited, path + tiles.charAt(i), obj);\n used[i] = false;\n }\n}", "const numTilePossibilities = function(tiles) {\n let used = new Array(tiles.length).fill(false);\n let visited = new Set();\n let cnt = 0;\n const dfs = (path) => {\n if (path.length && !visited.has(path)) {\n visited.add(path);\n cnt++;\n }\n for (let i = 0; i < tiles.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n dfs(path + tiles[i]);\n used[i] = false;\n }\n }\n dfs('');\n return cnt;\n};", "const numTilePossibilities = function(tiles) {\n const count = new Array(26).fill(0)\n const ACode = 'A'.charCodeAt(0)\n for (let i = 0, len = tiles.length; i < len; i++) {\n count[tiles.charCodeAt(i) - ACode]++\n }\n return dfs(count)\n}\n\nfunction dfs(arr) {\n let sum = 0\n for (let i = 0; i < 26; i++) {\n if (arr[i] === 0) continue\n sum++\n arr[i]--\n sum += dfs(arr)\n arr[i]++\n }\n return sum\n}" ]
1,080
insufficient-nodes-in-root-to-leaf-paths
[ "Consider a DFS traversal of the tree. You can keep track of the current path sum from root to this node, and you can also use DFS to return the minimum value of any path from this node to the leaf. This will tell you if this node is insufficient." ]
/** * 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} limit * @return {TreeNode} */ var sufficientSubset = function(root, limit) { };
Given the root of a binary tree and an integer limit, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree. A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit. A leaf is a node with no children.   Example 1: Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1 Output: [1,2,3,4,null,null,7,8,9,null,14] Example 2: Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22 Output: [5,4,8,11,null,17,4,7,null,null,null,5] Example 3: Input: root = [1,2,-3,-5,null,4,null], limit = -1 Output: [1,null,-3,4]   Constraints: The number of nodes in the tree is in the range [1, 5000]. -105 <= Node.val <= 105 -109 <= limit <= 109
Medium
[ "tree", "depth-first-search", "binary-tree" ]
null
[]
1,081
smallest-subsequence-of-distinct-characters
[ "Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i." ]
/** * @param {string} s * @return {string} */ var smallestSubsequence = function(s) { };
Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.   Example 1: Input: s = "bcabc" Output: "abc" Example 2: Input: s = "cbacdcbc" Output: "acdb"   Constraints: 1 <= s.length <= 1000 s consists of lowercase English letters.   Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/
Medium
[ "string", "stack", "greedy", "monotonic-stack" ]
[ "const smallestSubsequence = function(text) {\n if (text === '') return ''\n let counter = new Array(128).fill(0)\n for (let i = 0; i < text.length; i++) counter[text.charCodeAt(i)]++\n let minChar = 128\n let minIndex = 0\n for (let i = 0; i < text.length; i++) {\n let c = text.charCodeAt(i)\n if (c < minChar) {\n minChar = c\n minIndex = i\n }\n if (--counter[c] === 0) {\n return (\n String.fromCharCode(minChar) +\n smallestSubsequence(\n text\n .slice(minIndex + 1)\n .replace(new RegExp(String.fromCharCode(minChar), 'g'), '')\n )\n )\n }\n }\n return ''\n}", "const smallestSubsequence = function(s) {\n let res = []\n const count = new Array(26).fill(0)\n const used = new Array(26).fill(0)\n const aCode = 'a'.charCodeAt(0)\n for (let el of s) count[el.charCodeAt(0) - aCode]++\n for (let el of s) {\n count[el.charCodeAt(0) - aCode]--\n if (used[el.charCodeAt(0) - aCode]++ > 0) continue\n while (\n res.length &&\n res[res.length - 1].charCodeAt(0) > el.charCodeAt(0) &&\n count[res[res.length - 1].charCodeAt(0) - aCode] > 0\n ) {\n used[res[res.length - 1].charCodeAt(0) - aCode] = 0\n res.pop()\n }\n res.push(el)\n }\n return res.join('') \n};\n\n// anoother\n\n\n\nconst smallestSubsequence = function(text) {\n const n = text.length, stack = [], last = {}, visited = {}\n for(let i = 0; i < n; i++) last[text[i]] = i\n for(let i = 0; i < n; i++) {\n const ch = text[i]\n if (visited[ch]) continue\n while(stack.length && stack[stack.length - 1] > ch && last[stack[stack.length - 1]] > i) {\n visited[stack[stack.length - 1]] = 0\n stack.pop()\n }\n visited[ch] = 1\n stack.push(ch)\n }\n\n return stack.join('')\n};" ]
1,089
duplicate-zeros
[ "This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything.", "A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory.", "The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that?", "If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?" ]
/** * @param {number[]} arr * @return {void} Do not return anything, modify arr in-place instead. */ var duplicateZeros = function(arr) { };
Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.   Example 1: Input: arr = [1,0,2,3,0,4,5,0] Output: [1,0,0,2,3,0,0,4] Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4] Example 2: Input: arr = [1,2,3] Output: [1,2,3] Explanation: After calling your function, the input array is modified to: [1,2,3]   Constraints: 1 <= arr.length <= 104 0 <= arr[i] <= 9
Easy
[ "array", "two-pointers" ]
[ "const duplicateZeros = function(arr) {\n const len = arr.length\n for (let i = len - 1; i >= 0; i--) {\n if (arr[i] === 0) arr.splice(i, 0, 0)\n }\n while (arr.length > len) {\n arr.pop()\n }\n}" ]
1,090
largest-values-from-labels
[ "Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table." ]
/** * @param {number[]} values * @param {number[]} labels * @param {number} numWanted * @param {number} useLimit * @return {number} */ var largestValsFromLabels = function(values, labels, numWanted, useLimit) { };
There is a set of n items. You are given two integer arrays values and labels where the value and the label of the ith element are values[i] and labels[i] respectively. You are also given two integers numWanted and useLimit. Choose a subset s of the n elements such that: The size of the subset s is less than or equal to numWanted. There are at most useLimit items with the same label in s. The score of a subset is the sum of the values in the subset. Return the maximum score of a subset s.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth items. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third items. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1 Output: 16 Explanation: The subset chosen is the first and fourth items.   Constraints: n == values.length == labels.length 1 <= n <= 2 * 104 0 <= values[i], labels[i] <= 2 * 104 1 <= numWanted, useLimit <= n
Medium
[ "array", "hash-table", "greedy", "sorting", "counting" ]
[ "const largestValsFromLabels = function(values, labels, num_wanted, use_limit) {\n return Object.entries(\n labels.reduce((ret, l, i) => {\n ret[l] = (ret[l] || []).concat(values[i])\n return ret\n }, {})\n )\n .reduce(\n (candi, [k, vals]) =>\n candi.concat(vals.sort((a, b) => b - a).slice(0, use_limit)),\n []\n )\n .sort((a, b) => b - a)\n .slice(0, num_wanted)\n .reduce((ret, n) => ret + n, 0)\n};" ]
1,091
shortest-path-in-binary-matrix
[ "Do a breadth first search to find the shortest path." ]
/** * @param {number[][]} grid * @return {number} */ var shortestPathBinaryMatrix = function(grid) { };
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1. A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that: All the visited cells of the path are 0. All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner). The length of a clear path is the number of visited cells of this path.   Example 1: Input: grid = [[0,1],[1,0]] Output: 2 Example 2: Input: grid = [[0,0,0],[1,1,0],[1,1,0]] Output: 4 Example 3: Input: grid = [[1,0,0],[1,1,0],[1,1,0]] Output: -1   Constraints: n == grid.length n == grid[i].length 1 <= n <= 100 grid[i][j] is 0 or 1
Medium
[ "array", "breadth-first-search", "matrix" ]
[ "const shortestPathBinaryMatrix = function(grid) {\n if(grid == null || grid.length === 0 || grid[0][0] === 1) return -1 \n let res = 1\n const n = grid.length\n const dirs = [\n [1, 0],\n [-1, 0],\n [0, 1],\n [0, -1],\n [-1, -1],\n [-1, 1],\n [1, 1],\n [1, -1],\n ]\n let q = [[0, 0]]\n while(q.length) {\n const tmp = q\n q = []\n for(let [x, y] of tmp) {\n if (x < 0 || x >= n || y < 0 || y >= n || grid[x][y] !== 0) continue\n if(x === n - 1 && y === n - 1) return res\n grid[x][y] = 1\n for(let [dx, dy] of dirs) { \n q.push([x + dx, y + dy])\n }\n }\n res++\n }\n return -1\n};", "const shortestPathBinaryMatrix = function(grid) {\n if(grid == null || grid.length === 0 || grid[0][0] === 1) return -1 \n let res = 1\n const n = grid.length\n const dirs = [\n [1, 0],\n [-1, 0],\n [0, 1],\n [0, -1],\n [-1, -1],\n [-1, 1],\n [1, 1],\n [1, -1],\n ]\n let q = [[0, 0]]\n while(q.length) {\n let ref = q\n q = []\n for(let [x, y] of ref) {\n if(x === n - 1 && y === n - 1) return res\n grid[x][y] = 1\n for(let [dx, dy] of dirs) {\n const nx = x + dx, ny = y + dy\n if(helper(grid, nx, ny)) {\n q.push([nx, ny])\n grid[nx][ny] = 1 // very important\n }\n }\n }\n res++\n }\n return -1\n};\n\nfunction helper(grid, i, j) {\n const n = grid.length\n if(i < 0 || i >= n || j < 0 || j >= n || grid[i][j] !== 0) return false\n return true\n}" ]
1,092
shortest-common-supersequence
[ "We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming.", "We can use this information to recover the shortest common supersequence." ]
/** * @param {string} str1 * @param {string} str2 * @return {string} */ var shortestCommonSupersequence = function(str1, str2) { };
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.   Example 1: Input: str1 = "abac", str2 = "cab" Output: "cabac" Explanation: str1 = "abac" is a subsequence of "cabac" because we can delete the first "c". str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac". The answer provided is the shortest such string that satisfies these properties. Example 2: Input: str1 = "aaaaaaaa", str2 = "aaaaaaaa" Output: "aaaaaaaa"   Constraints: 1 <= str1.length, str2.length <= 1000 str1 and str2 consist of lowercase English letters.
Hard
[ "string", "dynamic-programming" ]
[ "const shortestCommonSupersequence = function(str1, str2) {\n const len1 = str1.length\n const len2 = str2.length\n const mat = Array.from({ length: len1 + 1 }, () =>\n new Array(len2 + 1).fill(0)\n )\n for (let i = 0; i <= len1; i++) {\n for (let j = 0; j <= len2; j++) {\n if (i == 0) {\n mat[i][j] = str2.slice(0, j)\n continue\n }\n if (j == 0) {\n mat[i][j] = str1.slice(0, i)\n continue\n }\n mat[i][j] = mat[i - 1][j] + str1[i - 1]\n let cand1 = mat[i][j - 1] + str2[j - 1]\n if (cand1.length < mat[i][j].length) mat[i][j] = cand1\n if (str1[i - 1] === str2[j - 1]) {\n let cand2 = mat[i - 1][j - 1] + str1[i - 1]\n if (cand2.length < mat[i][j].length) mat[i][j] = cand2\n }\n }\n }\n return mat[len1][len2]\n}" ]
1,093
statistics-from-a-large-sample
[ "The hard part is the median. Write a helper function which finds the k-th element from the sample." ]
/** * @param {number[]} count * @return {number[]} */ var sampleStats = function(count) { };
You are given a large sample of integers in the range [0, 255]. Since the sample is so large, it is represented by an array count where count[k] is the number of times that k appears in the sample. Calculate the following statistics: minimum: The minimum element in the sample. maximum: The maximum element in the sample. mean: The average of the sample, calculated as the total sum of all elements divided by the total number of elements. median: If the sample has an odd number of elements, then the median is the middle element once the sample is sorted. If the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted. mode: The number that appears the most in the sample. It is guaranteed to be unique. Return the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode]. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] Output: [1.00000,3.00000,2.37500,2.50000,3.00000] Explanation: The sample represented by count is [1,2,2,2,3,3,3,3]. The minimum and maximum are 1 and 3 respectively. The mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375. Since the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5. The mode is 3 as it appears the most in the sample. Example 2: Input: count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] Output: [1.00000,4.00000,2.18182,2.00000,1.00000] Explanation: The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4]. The minimum and maximum are 1 and 4 respectively. The mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182). Since the size of the sample is odd, the median is the middle element 2. The mode is 1 as it appears the most in the sample.   Constraints: count.length == 256 0 <= count[i] <= 109 1 <= sum(count) <= 109 The mode of the sample that count represents is unique.
Medium
[ "array", "math", "probability-and-statistics" ]
[ "const sampleStats = function(count) {\n const n = count.length\n let numElems = 0\n let sum = 0\n let min = n - 1\n let max = 0\n let modVal = 0\n let modIdx = 0\n for (let i = 0; i < n; i++) {\n if (count[i]) {\n min = Math.min(i, min)\n max = Math.max(i, max)\n if (count[i] > modVal) {\n modVal = count[i]\n modIdx = i\n }\n sum += i * count[i]\n numElems += count[i]\n }\n }\n const half = Math.floor(numElems / 2)\n let median\n for (let i = 0, c = 0, last = 0; i < n; i++) {\n if (count[i]) {\n c += count[i]\n if (c > half) {\n if (numElems % 2 === 0 && c - count[i] === half) {\n median = (i + last) / 2\n } else {\n median = i\n }\n break\n }\n last = i\n }\n }\n return [min, max, sum / numElems, median, modIdx]\n}" ]
1,094
car-pooling
[ "Sort the pickup and dropoff events by location, then process them in order." ]
/** * @param {number[][]} trips * @param {number} capacity * @return {boolean} */ var carPooling = function(trips, capacity) { };
There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location. Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.   Example 1: Input: trips = [[2,1,5],[3,3,7]], capacity = 4 Output: false Example 2: Input: trips = [[2,1,5],[3,3,7]], capacity = 5 Output: true   Constraints: 1 <= trips.length <= 1000 trips[i].length == 3 1 <= numPassengersi <= 100 0 <= fromi < toi <= 1000 1 <= capacity <= 105
Medium
[ "array", "sorting", "heap-priority-queue", "simulation", "prefix-sum" ]
[ "const carPooling = function(trips, capacity) {\n const arr = Array(1001).fill(0)\n for(const [num, s, e] of trips) {\n arr[s] += num\n arr[e] -= num\n }\n for(let i = 1; i < 1001; i++) {\n arr[i] += arr[i - 1]\n }\n \n for(let e of arr) {\n if(e > capacity) return false\n }\n return true\n};", "const carPooling = function(trips, capacity) {\n let stops = new Array(1001).fill(0)\n for (let t of trips) {\n stops[t[1]] += t[0]\n stops[t[2]] -= t[0]\n }\n for (let i = 0; capacity >= 0 && i < 1001; ++i) capacity -= stops[i]\n return capacity >= 0\n}", "const carPooling = function(trips, capacity) {\n const arr = Array(1001).fill(0)\n for(let el of trips) {\n const [num, s, e] = el\n arr[s] += num\n arr[e] -= num\n }\n for(let i = 1; i < 1001; i++) {\n if(arr[i] !== 0) arr[i] += arr[i - 1]\n else arr[i] = arr[i - 1]\n }\n for(let e of arr) {\n if(e > capacity) return false\n }\n return true\n};" ]
1,095
find-in-mountain-array
[ "Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.\r\nAfter finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak." ]
/** * // This is the MountainArray's API interface. * // You should not implement it, or speculate about its implementation * function MountainArray() { * @param {number} index * @return {number} * this.get = function(index) { * ... * }; * * @return {number} * this.length = function() { * ... * }; * }; */ /** * @param {number} target * @param {MountainArray} mountainArr * @return {number} */ var findInMountainArray = function(target, mountainArr) { };
(This problem is an interactive problem.) You may recall that an array arr is a mountain array if and only if: arr.length >= 3 There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1. You cannot access the mountain array directly. You may only access the array using a MountainArray interface: MountainArray.get(k) returns the element of the array at index k (0-indexed). MountainArray.length() returns the length of the array. Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.   Example 1: Input: array = [1,2,3,4,5,3,1], target = 3 Output: 2 Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. Example 2: Input: array = [0,1,2,4,2,1], target = 3 Output: -1 Explanation: 3 does not exist in the array, so we return -1.   Constraints: 3 <= mountain_arr.length() <= 104 0 <= target <= 109 0 <= mountain_arr.get(index) <= 109
Hard
[ "array", "binary-search", "interactive" ]
[ "const findInMountainArray = function(target, mountainArr) {\n const p = findPeak(mountainArr)\n if (mountainArr.get(p) === target) {\n return p\n }\n const left = binarySeach(mountainArr, 0, p, target, 'asc')\n if (left > -1) {\n return left\n }\n return binarySeach(mountainArr, p + 1, mountainArr.length(), target, 'dsc')\n}\n\nfunction findPeak(arr) {\n let left = 0\n let right = arr.length()\n while (left < right) {\n const mid = Math.floor((left + right) / 2)\n if (arr.get(mid) < arr.get(mid + 1)) {\n left = mid + 1\n } else {\n right = mid\n }\n }\n return left\n}\n\nfunction binarySeach(mountainArr, start, end, target, order) {\n let left = start\n let right = end\n while (left < right) {\n const mid = Math.floor((left + right) / 2)\n if (target === mountainArr.get(mid)) {\n return mid\n } else if (\n (target > mountainArr.get(mid) && order === 'asc') ||\n (target < mountainArr.get(mid) && order === 'dsc')\n ) {\n left = mid + 1\n } else {\n right = mid\n }\n }\n return -1\n}" ]
1,096
brace-expansion-ii
[ "You can write helper methods to parse the next \"chunk\" of the expression. If you see eg. \"a\", the answer is just the set {a}. If you see \"{\", you parse until you complete the \"}\" (the number of { and } seen are equal) and that becomes a chunk that you find where the appropriate commas are, and parse each individual expression between the commas." ]
/** * @param {string} expression * @return {string[]} */ var braceExpansionII = function(expression) { };
Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents. The grammar can best be understood through simple examples: Single letters represent a singleton set containing that word. R("a") = {"a"} R("w") = {"w"} When we take a comma-delimited list of two or more expressions, we take the union of possibilities. R("{a,b,c}") = {"a","b","c"} R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once) When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression. R("{a,b}{c,d}") = {"ac","ad","bc","bd"} R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"} Formally, the three rules for our grammar: For every lowercase letter x, we have R(x) = {x}. For expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ... For expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, where + denotes concatenation, and × denotes the cartesian product. Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.   Example 1: Input: expression = "{a,b}{c,{d,e}}" Output: ["ac","ad","ae","bc","bd","be"] Example 2: Input: expression = "{{a,z},a{b,c},{ab,z}}" Output: ["a","ab","ac","z"] Explanation: Each distinct word is written only once in the final answer.   Constraints: 1 <= expression.length <= 60 expression[i] consists of '{', '}', ','or lowercase English letters. The given expression represents a set of words based on the grammar given in the description.
Hard
[ "string", "backtracking", "stack", "breadth-first-search" ]
[ "const braceExpansionII = function (expression) {\n expression = expression.replace(/([a-z]){1}/g, '{$1}')\n const stk = new Array()\n for (let char of expression) {\n if (char !== '}') {\n stk.push(char)\n } else {\n let str = '',\n prev = '',\n temp = ''\n while (stk[stk.length - 1] != '{') {\n prev = temp\n temp = stk.pop()\n if (temp == ',' || prev == ',' || str == '') str = temp + str\n else {\n str = str\n .split(',')\n .map((item) => {\n let ar = new Array()\n for (let ch of temp.split(',')) ar.push(ch + item)\n return ar.join(',')\n })\n .join(',')\n }\n }\n stk.pop()\n while (\n stk.length > 0 &&\n stk[stk.length - 1] != ',' &&\n stk[stk.length - 1] != '{'\n ) {\n temp = stk.pop()\n str = str\n .split(',')\n .map((item) => {\n let ar = new Array()\n for (let ch of temp.split(',')) ar.push(ch + item)\n return ar.join(',')\n })\n .join(',')\n }\n\n if (str.length > 0) stk.push(str)\n }\n }\n\n return [...new Set(stk[0].split(','))].sort()\n}" ]
1,103
distribute-candies-to-people
[ "Give candy to everyone each \"turn\" first [until you can't], then give candy to one person per turn." ]
/** * @param {number} candies * @param {number} num_people * @return {number[]} */ var distributeCandies = function(candies, num_people) { };
We distribute some number of candies, to a row of n = num_people people in the following way: We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person. Then, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person. This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies.  The last person will receive all of our remaining candies (not necessarily one more than the previous gift). Return an array (of length num_people and sum candies) that represents the final distribution of candies.   Example 1: Input: candies = 7, num_people = 4 Output: [1,2,3,1] Explanation: On the first turn, ans[0] += 1, and the array is [1,0,0,0]. On the second turn, ans[1] += 2, and the array is [1,2,0,0]. On the third turn, ans[2] += 3, and the array is [1,2,3,0]. On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1]. Example 2: Input: candies = 10, num_people = 3 Output: [5,2,3] Explanation: On the first turn, ans[0] += 1, and the array is [1,0,0]. On the second turn, ans[1] += 2, and the array is [1,2,0]. On the third turn, ans[2] += 3, and the array is [1,2,3]. On the fourth turn, ans[0] += 4, and the final array is [5,2,3].   Constraints: 1 <= candies <= 10^9 1 <= num_people <= 1000
Easy
[ "math", "simulation" ]
[ "const distributeCandies = function(candies, num_people) {\n const n = num_people\n const res = Array(n).fill(0)\n let idx = 0, cur = 0\n while(candies > 0) {\n cur++\n res[idx] += Math.min(cur, candies)\n idx++\n candies -= cur\n if(idx === n) idx = 0\n }\n return res\n};" ]
1,104
path-in-zigzag-labelled-binary-tree
[ "Based on the label of the current node, find what the label must be for the parent of that node." ]
/** * @param {number} label * @return {number[]} */ var pathInZigZagTree = function(label) { };
In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.   Example 1: Input: label = 14 Output: [1,3,4,14] Example 2: Input: label = 26 Output: [1,2,6,10,26]   Constraints: 1 <= label <= 10^6
Medium
[ "math", "tree", "binary-tree" ]
[ "const pathInZigZagTree = function(label) {\n const res = [], { log2, floor, ceil } = Math\n const level = floor(log2(label))\n let compl = 2 ** (level + 1) - 1 + 2 ** level - label\n \n while(label) {\n res.push(label)\n label = floor(label / 2)\n compl = floor(compl / 2)\n ;[label, compl] = [compl, label]\n }\n \n res.reverse()\n \n return res\n};", "const pathInZigZagTree = function(label) {\n const res = [], { log2, floor, ceil } = Math\n \n res.push(label)\n \n // check last row\n const lev = ceil(log2(label + 1))\n const reverse = lev % 2 === 0 ? true : false\n // console.log(reverse, lev)\n if(reverse) {\n const idx = 2 ** lev - 1 - label\n label = 2 ** (lev - 1) + idx\n }\n // console.log(label)\n \n while(label > 1) {\n const level = floor(log2(label))\n const parent = floor(label / 2)\n const parentLevelNum = 2 ** (level - 1)\n const parentReverse = level % 2 === 0 ? true : false\n const parentStart = 2 ** (level - 1)\n const parentEnd = 2 ** level - 1\n // console.log(parentStart, parentEnd, parent)\n const idx = parent - parentStart\n res.push(parentReverse ? parentEnd - idx : parentStart + idx)\n \n label = parent\n }\n \n\n res.reverse()\n return res\n};" ]
1,105
filling-bookcase-shelves
[ "Use dynamic programming: dp(i) will be the answer to the problem for books[i:]." ]
/** * @param {number[][]} books * @param {number} shelfWidth * @return {number} */ var minHeightShelves = function(books, shelfWidth) { };
You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth. We want to place these books in order onto bookcase shelves that have a total width shelfWidth. We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.   Example 1: Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4 Output: 6 Explanation: The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6. Notice that book number 2 does not have to be on the first shelf. Example 2: Input: books = [[1,3],[2,4],[3,2]], shelfWidth = 6 Output: 4   Constraints: 1 <= books.length <= 1000 1 <= thicknessi <= shelfWidth <= 1000 1 <= heighti <= 1000
Medium
[ "array", "dynamic-programming" ]
[ "const minHeightShelves = function(books, shelf_width) {\n const dp = new Array(books.length + 1)\n dp[0] = 0\n for(let i = 1; i <= books.length; i++) {\n let width = books[i - 1][0]\n let height = books[i - 1][1]\n dp[i] = dp[i - 1] + height\n for(let j = i - 1; j > 0 && width + books[j - 1][0] <= shelf_width; j--) {\n height = Math.max(height, books[j - 1][1])\n width += books[j - 1][0]\n dp[i] = Math.min(dp[i], dp[j - 1] + height)\n }\n }\n return dp[books.length]\n};", "const minHeightShelves = function(books, shelf_width) {\n const n = books.length, dp = Array(1001).fill(Infinity)\n dp[0] = 0\n for(let i = 0; i < n; i++) {\n let sum = 0, mx = 0\n for(let j = i; j >= 0 && sum + books[j][0] <= shelf_width; j--) {\n sum += books[j][0]\n mx = Math.max(mx, books[j][1])\n dp[i + 1] = Math.min(dp[i + 1], dp[j] + mx)\n }\n }\n return dp[n]\n};", " const minHeightShelves = function(books, shelf_width) {\n const n = books.length, dp = Array(1001)\n dp[0] = 0\n\n for(let i = 0; i < n; i++) {\n let [w, h] = books[i]\n dp[i + 1] = dp[i] + h\n for(let j = i - 1; j >= 0 && w + books[j][0] <= shelf_width; j--) {\n h = Math.max(h, books[j][1])\n w += books[j][0]\n dp[i + 1] = Math.min(dp[i + 1], dp[j] + h) \n }\n }\n\n return dp[n]\n};" ]
1,106
parsing-a-boolean-expression
[ "Write a function \"parse\" which calls helper functions \"parse_or\", \"parse_and\", \"parse_not\"." ]
/** * @param {string} expression * @return {boolean} */ var parseBoolExpr = function(expression) { };
A boolean expression is an expression that evaluates to either true or false. It can be in one of the following shapes: 't' that evaluates to true. 'f' that evaluates to false. '!(subExpr)' that evaluates to the logical NOT of the inner expression subExpr. '&(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical AND of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1. '|(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical OR of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1. Given a string expression that represents a boolean expression, return the evaluation of that expression. It is guaranteed that the given expression is valid and follows the given rules.   Example 1: Input: expression = "&(|(f))" Output: false Explanation: First, evaluate |(f) --> f. The expression is now "&(f)". Then, evaluate &(f) --> f. The expression is now "f". Finally, return false. Example 2: Input: expression = "|(f,f,f,t)" Output: true Explanation: The evaluation of (false OR false OR false OR true) is true. Example 3: Input: expression = "!(&(f,t))" Output: true Explanation: First, evaluate &(f,t) --> (false AND true) --> false --> f. The expression is now "!(f)". Then, evaluate !(f) --> NOT false --> true. We return true.   Constraints: 1 <= expression.length <= 2 * 104 expression[i] is one following characters: '(', ')', '&', '|', '!', 't', 'f', and ','.
Hard
[ "string", "stack", "recursion" ]
[ "const parseBoolExpr = function(expression) {\n const stack = []\n for (let ch of expression) {\n if (ch === '|' || ch === '&' || ch === '!') stack.push(ch)\n if (ch === 't') stack.push(true)\n if (ch === 'f') stack.push(false)\n if (ch === ')') {\n const tmp = []\n while (stack.length) {\n let t = stack.pop()\n if (t === true || t === false) tmp.push(t)\n else {\n let res = tmp.pop()\n if (t === '|') {\n while (tmp.length) res = tmp.pop() || res\n } else if (t === '&') {\n while (tmp.length) res = tmp.pop() && res\n } else if (t === '!') {\n res = !res\n }\n stack.push(res)\n break\n }\n }\n }\n }\n return stack[0]\n}" ]
1,108
defanging-an-ip-address
[]
/** * @param {string} address * @return {string} */ var defangIPaddr = function(address) { };
Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period "." with "[.]".   Example 1: Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1" Example 2: Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0"   Constraints: The given address is a valid IPv4 address.
Easy
[ "string" ]
[ "const defangIPaddr = function(address) {\n return address.split('.').join('[.]')\n};" ]
1,109
corporate-flight-bookings
[]
/** * @param {number[][]} bookings * @param {number} n * @return {number[]} */ var corpFlightBookings = function(bookings, n) { };
There are n flights that are labeled from 1 to n. You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range. Return an array answer of length n, where answer[i] is the total number of seats reserved for flight i.   Example 1: Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5 Output: [10,55,45,25,25] Explanation: Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = [10,55,45,25,25] Example 2: Input: bookings = [[1,2,10],[2,2,15]], n = 2 Output: [10,25] Explanation: Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = [10,25]   Constraints: 1 <= n <= 2 * 104 1 <= bookings.length <= 2 * 104 bookings[i].length == 3 1 <= firsti <= lasti <= n 1 <= seatsi <= 104
Medium
[ "array", "prefix-sum" ]
[ "const corpFlightBookings = function(bookings, n) {\n const arr = Array(n + 2).fill(0)\n for(const [s, e, num] of bookings) {\n arr[s] += num\n arr[e + 1] -= num\n }\n for(let i = 1; i < n + 2; i++) {\n arr[i] += arr[i - 1]\n }\n arr.pop()\n arr.shift()\n return arr\n};", "const corpFlightBookings = function(bookings, n) {\n let res = new Array(n).fill(0)\n for (let v of bookings) {\n res[v[0] - 1] += v[2]\n if (v[1] < n) res[v[1]] -= v[2]\n }\n for (let i = 1; i < n; ++i) res[i] += res[i - 1]\n return res\n}", "const corpFlightBookings = function(bookings, n) {\n const arr = Array(n + 2).fill(0)\n for(let [s, e, num] of bookings) {\n arr[s] += num\n arr[e + 1] -= num\n }\n for(let i = 1; i <= n; i++) {\n if(arr[i] !== 0) arr[i] += arr[i - 1]\n else arr[i] = arr[i - 1]\n }\n return arr.slice(1, n + 1)\n};" ]
1,110
delete-nodes-and-return-forest
[]
/** * 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[]} to_delete * @return {TreeNode[]} */ var delNodes = function(root, to_delete) { };
Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order.   Example 1: Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output: [[1,2,null,4],[6],[7]] Example 2: Input: root = [1,2,4,null,3], to_delete = [3] Output: [[1,2,4]]   Constraints: The number of nodes in the given tree is at most 1000. Each node has a distinct value between 1 and 1000. to_delete.length <= 1000 to_delete contains distinct values between 1 and 1000.
Medium
[ "array", "hash-table", "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 delNodes = function(root, to_delete) {\n let rst = []\n let dfs = function(node, isRoot) {\n if (!node) return\n let isDel = to_delete.indexOf(node.val) !== -1\n if (node.left) node.left = dfs(node.left, isDel)\n if (node.right) node.right = dfs(node.right, isDel)\n if (isRoot && !isDel) rst.push(node)\n return isDel ? null : node\n }\n if (!root) return []\n dfs(root, true)\n return rst\n}" ]
1,111
maximum-nesting-depth-of-two-valid-parentheses-strings
[]
/** * @param {string} seq * @return {number[]} */ var maxDepthAfterSplit = function(seq) { };
A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and: It is the empty string, or It can be written as AB (A concatenated with B), where A and B are VPS's, or It can be written as (A), where A is a VPS. We can similarly define the nesting depth depth(S) of any VPS S as follows: depth("") = 0 depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's depth("(" + A + ")") = 1 + depth(A), where A is a VPS. For example,  "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.   Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length). Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value. Return an answer array (of length seq.length) that encodes such a choice of A and B:  answer[i] = 0 if seq[i] is part of A, else answer[i] = 1.  Note that even though multiple answers may exist, you may return any of them.   Example 1: Input: seq = "(()())" Output: [0,1,1,1,1,0] Example 2: Input: seq = "()(())()" Output: [0,0,0,1,1,0,1,1]   Constraints: 1 <= seq.size <= 10000
Medium
[ "string", "stack" ]
[ "const maxDepthAfterSplit = function(seq) {\n const n = seq.length\n const res = Array(n).fill(0)\n let depth = 0\n for(let i = 0; i < n; i++) {\n const ch = seq[i]\n if(ch === '(') {\n depth++\n }\n res[i] = depth % 2\n if(ch === ')') depth--\n }\n return res\n};" ]
1,122
relative-sort-array
[ "Using a hashmap, we can map the values of arr2 to their position in arr2.", "After, we can use a custom sorting function." ]
/** * @param {number[]} arr1 * @param {number[]} arr2 * @return {number[]} */ var relativeSortArray = function(arr1, arr2) { };
Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.   Example 1: Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] Output: [2,2,2,1,4,3,3,9,6,7,19] Example 2: Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6] Output: [22,28,8,6,17,44]   Constraints: 1 <= arr1.length, arr2.length <= 1000 0 <= arr1[i], arr2[i] <= 1000 All the elements of arr2 are distinct. Each arr2[i] is in arr1.
Easy
[ "array", "hash-table", "sorting", "counting-sort" ]
[ "const relativeSortArray = function(arr1, arr2) {\n const hash = {}\n const res = []\n arr1.forEach(el => {\n if(hash.hasOwnProperty(el)) hash[el] += 1\n else hash[el] = 1\n })\n for(let i = 0, len = arr2.length; i < len; i++) {\n res.push(...makeArr(arr2[i], hash[arr2[i]]))\n delete hash[arr2[i]]\n }\n const keys = Object.keys(hash).sort((a, b) => a - b)\n for(let i = 0, len = keys.length; i < len; i++) {\n res.push(...makeArr(keys[i], hash[keys[i]]))\n }\n return res\n};\n\nfunction makeArr(el, num) {\n return new Array(num).fill(el)\n}" ]
1,123
lowest-common-ancestor-of-deepest-leaves
[ "Do a postorder traversal.", "Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far).", "The final node marked will be the correct answer." ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {TreeNode} */ var lcaDeepestLeaves = function(root) { };
Given the root of a binary tree, return the lowest common ancestor of its deepest leaves. Recall that: The node of a binary tree is a leaf if and only if it has no children The depth of the root of the tree is 0. if the depth of a node is d, the depth of each of its children is d + 1. The lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A.   Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4] Output: [2,7,4] Explanation: We return the node with value 2, colored in yellow in the diagram. The nodes coloured in blue are the deepest leaf-nodes of the tree. Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3. Example 2: Input: root = [1] Output: [1] Explanation: The root is the deepest node in the tree, and it's the lca of itself. Example 3: Input: root = [0,1,3,null,2] Output: [2] Explanation: The deepest leaf node in the tree is 2, the lca of one node is itself.   Constraints: The number of nodes in the tree will be in the range [1, 1000]. 0 <= Node.val <= 1000 The values of the nodes in the tree are unique.   Note: This question is the same as 865: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/
Medium
[ "hash-table", "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 lcaDeepestLeaves = function(root) {\n let maxDepth = 0, lcaNode = null\n\n function lca(node, depth) {\n if(node == null) return depth - 1\n maxDepth = Math.max(depth, maxDepth)\n const left = lca(node.left, depth + 1)\n const right = lca(node.right, depth + 1)\n if(left === maxDepth && right === maxDepth) {\n lcaNode = node\n }\n return Math.max(left, right)\n }\n\n lca(root, 0)\n return lcaNode\n};", "const lcaDeepestLeaves = function(root) {\n if (root === null) return null\n const getHeight = root => {\n if (root === null) return 0\n const res = Math.max(getHeight(root.left), getHeight(root.right)) + 1\n return res\n }\n if (getHeight(root.left) === getHeight(root.right)) {\n return root\n } else if (getHeight(root.left) > getHeight(root.right)) {\n return lcaDeepestLeaves(root.left)\n } else {\n return lcaDeepestLeaves(root.right)\n }\n}\n\n// BFS\n\nconst lcaDeepestLeaves = function(root) {\n let current = [root];\n let level = 0;\n let last = [];\n while(current.length) {\n let next = [];\n for (var i = 0; i < current.length; i++) {\n if (current[i].left) {\n current[i].left.parent = current[i];\n next.push(current[i].left);\n }\n if (current[i].right) {\n current[i].right.parent = current[i];\n next.push(current[i].right);\n }\n }\n last = current;\n current = next;\n }\n let parent = last[0].parent;\n if (!parent) {\n return last[0];\n }\n while(last.length > 1) {\n let next = [];\n for (var i = 0; i < last.length; i++) {\n newParent = last[i].parent;\n if (!next.includes(newParent)) {\n next.push(newParent);\n }\n }\n last = next;\n }\n return last[0]; \n};" ]
1,124
longest-well-performing-interval
[ "Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum.", "Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j]." ]
/** * @param {number[]} hours * @return {number} */ var longestWPI = function(hours) { };
We are given hours, a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8. A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval.   Example 1: Input: hours = [9,9,6,0,6,6,9] Output: 3 Explanation: The longest well-performing interval is [9,9,6]. Example 2: Input: hours = [6,6,6] Output: 0   Constraints: 1 <= hours.length <= 104 0 <= hours[i] <= 16
Medium
[ "array", "hash-table", "stack", "monotonic-stack", "prefix-sum" ]
[ "const longestWPI = function(hours) {\n const N = hours.length;\n const seen = new Map();\n let res = 0;\n let score = 0;\n for (let i = 0; i < N; i++) {\n score += hours[i] > 8 ? 1 : -1;\n if (score > 0) {\n res = i + 1;\n } else {\n if (!seen.has(score)) {\n seen.set(score, i);\n }\n if (seen.has(score - 1)) {\n res = Math.max(res, i - seen.get(score - 1));\n }\n }\n }\n return res;\n};" ]
1,125
smallest-sufficient-team
[ "Do a bitmask DP.", "For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills." ]
/** * @param {string[]} req_skills * @param {string[][]} people * @return {number[]} */ var smallestSufficientTeam = function(req_skills, people) { };
In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person. For example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3]. Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order. It is guaranteed an answer exists.   Example 1: Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]] Output: [0,2] Example 2: Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]] Output: [1,2]   Constraints: 1 <= req_skills.length <= 16 1 <= req_skills[i].length <= 16 req_skills[i] consists of lowercase English letters. All the strings of req_skills are unique. 1 <= people.length <= 60 0 <= people[i].length <= 16 1 <= people[i][j].length <= 16 people[i][j] consists of lowercase English letters. All the strings of people[i] are unique. Every skill in people[i] is a skill in req_skills. It is guaranteed a sufficient team exists.
Hard
[ "array", "dynamic-programming", "bit-manipulation", "bitmask" ]
[ "const smallestSufficientTeam = function (req_skills, people) {\n const m = req_skills.length,\n n = people.length,\n limit = 1 << m\n const skillIdxMap = {}\n for(let i = 0; i < m; i++) {\n skillIdxMap[req_skills[i]] = i\n }\n const dp = Array(limit)\n\n dp[0] = []\n \n for(let i = 0; i < n; i++) {\n let skillMask = 0\n for(let j = 0; j < people[i].length; j++) {\n skillMask |= (1 << skillIdxMap[people[i][j]])\n }\n\n for(let j = 0; j < dp.length; j++) {\n if(dp[j] == null) continue\n const prev = j\n const comb = prev | skillMask\n\n if(dp[comb] == null || dp[comb].length > dp[prev].length + 1) {\n\n dp[comb] = dp[prev].slice()\n dp[comb].push(i)\n }\n }\n }\n\n return dp[limit - 1]\n}", "const smallestSufficientTeam = function(req_skills, people) {\n const m = req_skills.length\n const n = people.length\n const skill2Bitmap = req_skills\n .map((x, i) => [x, i])\n .reduce((dict, cur) => {\n dict[cur[0]] = 1 << cur[1]\n return dict\n }, {})\n const newPeople = people.map(x => {\n return x.reduce((acc, cur) => {\n const y = skill2Bitmap[cur]\n if (y !== undefined) {\n acc |= y\n }\n return acc\n }, 0)\n })\n\n const all = (1 << m) - 1\n const dp = {}\n for (let j = 0; j < n; j++) {\n if (newPeople[j] > 0) {\n dp[newPeople[j]] = new Set([j])\n }\n }\n if (dp[all]) {\n return Array.from(dp[all]).sort()\n }\n\n for (let k = 0; k < n; k++) {\n for (let s in dp) {\n for (let j = 0; j < n; j++) {\n if (newPeople[j] === 0 || dp[s].has(j)) continue\n const newIdx = s | newPeople[j]\n if (dp[newIdx] === undefined) {\n dp[newIdx] = new Set([...dp[s], j])\n if (newIdx === all) {\n return Array.from(dp[all]).sort()\n }\n }\n }\n }\n }\n return []\n}", "const smallestSufficientTeam = function(req_skills, people) {\n let skill_len = req_skills.length\n\n // 将people转换为id的模式\n let id_people = []\n let hash = {}\n for (let i = 0; i < skill_len; i++) {\n hash[req_skills[i]] = i\n }\n for (let i = 0; i < people.length; i++) {\n id_people[i] = []\n for (let j = 0; j < people[i].length; j++) {\n id_people[i][j] = hash[people[i][j]]\n }\n }\n\n // 过滤掉不可能的选取的人员\n let skip = {}\n for (let i = 0; i < id_people.length; i++) {\n if (skip[i]) continue\n let skills = Array(skill_len).fill(0)\n for (let j = 0; j < id_people[i].length; j++) {\n let curId = id_people[i][j]\n skills[curId]++\n }\n for (let k = i + 1; k < id_people.length; k++) {\n if (skip[k]) continue\n let needSkip = true\n for (let l = 0; l < id_people[k].length; l++) {\n let id = id_people[k][l]\n if (skills[id] === 0) {\n needSkip = false\n break\n }\n }\n if (needSkip) {\n skip[k] = true\n }\n }\n }\n\n // 构造精简后的人员,并且保存对应的index关系\n let slim_people = []\n let idHash = {}\n for (let i = 0; i < id_people.length; i++) {\n if (skip[i]) continue\n idHash[slim_people.length] = i\n slim_people.push(id_people[i])\n }\n\n // 执行回溯\n let res = Infinity\n let remain = {}\n let ans = null\n for (let i = 0; i < slim_people.length; i++) {\n remain[i] = false\n }\n let init_select = Array(skill_len).fill(0)\n\n backtrack(0, init_select, 0, remain)\n\n return ans\n\n function backtrack(id, select, count, remain) {\n if (count >= res) return\n let done = true\n for (let i = 0; i < select.length; i++) {\n if (select[i] === 0) {\n done = false\n }\n }\n if (done) {\n res = count\n let _res_ = []\n for (let k in remain) {\n if (remain[k]) _res_.push(idHash[k])\n }\n ans = _res_\n return\n }\n for (let k = id; k < slim_people.length; k++) {\n let arr = slim_people[k]\n for (let i = 0; i < arr.length; i++) {\n select[arr[i]]++\n }\n remain[k] = true\n backtrack(k + 1, select, count + 1, remain)\n remain[k] = false\n for (let i = 0; i < arr.length; i++) {\n select[arr[i]]--\n }\n }\n }\n}" ]
1,128
number-of-equivalent-domino-pairs
[ "For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent.", "You can keep track of what you've seen using a hashmap." ]
/** * @param {number[][]} dominoes * @return {number} */ var numEquivDominoPairs = function(dominoes) { };
Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j].   Example 1: Input: dominoes = [[1,2],[2,1],[3,4],[5,6]] Output: 1 Example 2: Input: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]] Output: 3   Constraints: 1 <= dominoes.length <= 4 * 104 dominoes[i].length == 2 1 <= dominoes[i][j] <= 9
Easy
[ "array", "hash-table", "counting" ]
[ "const numEquivDominoPairs = function(dominoes) {\n const hash = {}\n for (let dom of dominoes) {\n const [a, b] = dom\n const key = `${a},${b}`, alterKey = `${b},${a}`\n if (hash[key] == null && hash[alterKey] == null) {\n hash[key] = 1\n } else {\n if(hash[key] != null) hash[key] += 1\n else hash[alterKey] += 1\n }\n }\n\n let res = 0\n\n Object.keys(hash).forEach(k => {\n if(hash[k] > 1) res += sum(hash[k])\n })\n\n return res\n};\n\nfunction sum(n) {\n let res = 0\n while(n > 1) {\n res += n - 1\n n--\n }\n return res\n}" ]
1,129
shortest-path-with-alternating-colors
[ "Do a breadth-first search, where the \"nodes\" are actually (Node, color of last edge taken)." ]
/** * @param {number} n * @param {number[][]} redEdges * @param {number[][]} blueEdges * @return {number[]} */ var shortestAlternatingPaths = function(n, redEdges, blueEdges) { };
You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays redEdges and blueEdges where: redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph. Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist.   Example 1: Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = [] Output: [0,1,-1] Example 2: Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]] Output: [0,1,-1]   Constraints: 1 <= n <= 100 0 <= redEdges.length, blueEdges.length <= 400 redEdges[i].length == blueEdges[j].length == 2 0 <= ai, bi, uj, vj < n
Medium
[ "breadth-first-search", "graph" ]
[ "const shortestAlternatingPaths = function(n, red_edges, blue_edges) {\n let d = new Array(n * 2).fill(Number.MAX_SAFE_INTEGER)\n let queue = []\n d[0] = d[n] = 0\n queue.push(0)\n queue.push(n)\n while (queue.length) {\n let cur = queue.shift()\n if (cur < n) {\n for (let r of red_edges) {\n if (r[0] == cur && d[r[1] + n] > d[cur] + 1) {\n d[r[1] + n] = d[cur] + 1\n queue.push(r[1] + n)\n }\n }\n } else {\n for (let b of blue_edges) {\n if (b[0] == cur - n && d[b[1]] > d[cur] + 1) {\n d[b[1]] = d[cur] + 1\n queue.push(b[1])\n }\n }\n }\n }\n let res = new Array(n).fill(-1)\n for (let i = 0; i < n; i++) {\n res[i] =\n Math.min(d[i], d[i + n]) == Number.MAX_SAFE_INTEGER\n ? -1\n : Math.min(d[i], d[i + n])\n }\n return res\n}" ]
1,130
minimum-cost-tree-from-leaf-values
[ "Do a DP, where dp(i, j) is the answer for the subarray arr[i]..arr[j].", "For each possible way to partition the subarray i <= k < j, the answer is max(arr[i]..arr[k]) * max(arr[k+1]..arr[j]) + dp(i, k) + dp(k+1, j)." ]
/** * @param {number[]} arr * @return {number} */ var mctFromLeafValues = function(arr) { };
Given an array arr of positive integers, consider all binary trees such that: Each node has either 0 or 2 children; The values of arr correspond to the values of each leaf in an in-order traversal of the tree. The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively. Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer. A node is a leaf if and only if it has zero children.   Example 1: Input: arr = [6,2,4] Output: 32 Explanation: There are two possible trees shown. The first has a non-leaf node sum 36, and the second has non-leaf node sum 32. Example 2: Input: arr = [4,11] Output: 44   Constraints: 2 <= arr.length <= 40 1 <= arr[i] <= 15 It is guaranteed that the answer fits into a 32-bit signed integer (i.e., it is less than 231).
Medium
[ "array", "dynamic-programming", "stack", "greedy", "monotonic-stack" ]
[ "const mctFromLeafValues = function(arr) {\n let res = 0, n = arr.length;\n let stack = new Array();\n stack.push(Number.MAX_VALUE);\n for (let a of arr) {\n while (stack[stack.length - 1] <= a) {\n let mid = stack.pop();\n res += mid * Math.min(stack[stack.length - 1], a);\n }\n stack.push(a);\n }\n while (stack.length > 2) {\n res += stack.pop() * stack[stack.length - 1];\n }\n return res; \n};" ]
1,131
maximum-of-absolute-value-expression
[ "Use the idea that abs(A) + abs(B) = max(A+B, A-B, -A+B, -A-B)." ]
/** * @param {number[]} arr1 * @param {number[]} arr2 * @return {number} */ var maxAbsValExpr = function(arr1, arr2) { };
Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 <= i, j < arr1.length.   Example 1: Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6] Output: 13 Example 2: Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4] Output: 20   Constraints: 2 <= arr1.length == arr2.length <= 40000 -10^6 <= arr1[i], arr2[i] <= 10^6
Medium
[ "array", "math" ]
null
[]
1,137
n-th-tribonacci-number
[ "Make an array F of length 38, and set F[0] = 0, F[1] = F[2] = 1.", "Now write a loop where you set F[n+3] = F[n] + F[n+1] + F[n+2], and return F[n]." ]
/** * @param {number} n * @return {number} */ var tribonacci = function(n) { };
The Tribonacci sequence Tn is defined as follows:  T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. Given n, return the value of Tn.   Example 1: Input: n = 4 Output: 4 Explanation: T_3 = 0 + 1 + 1 = 2 T_4 = 1 + 1 + 2 = 4 Example 2: Input: n = 25 Output: 1389537   Constraints: 0 <= n <= 37 The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.
Easy
[ "math", "dynamic-programming", "memoization" ]
[ "const hash = {}\nconst tribonacci = function(n) {\n if(n === 0) return 0\n if(n === 2 || n === 1) return 1\n if(hash[n] != null) return hash[n]\n let tmp = tribonacci(n - 3) + tribonacci(n - 2) + tribonacci(n - 1)\n return hash[n] = tmp\n};", "const tribonacci = function(n) {\n if (n < 2) return n\n let prev0 = 0\n let prev1 = 1\n let prev2 = 1\n for (let count = 3; count <= n; count++) {\n let next = prev2 + prev1 + prev0\n prev0 = prev1\n prev1 = prev2\n prev2 = next\n }\n return prev2\n}" ]
1,138
alphabet-board-path
[ "Create a hashmap from letter to position on the board.", "Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board." ]
/** * @param {string} target * @return {string} */ var alphabetBoardPath = function(target) { };
On an alphabet board, we start at position (0, 0), corresponding to character board[0][0]. Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below. We may make the following moves: 'U' moves our position up one row, if the position exists on the board; 'D' moves our position down one row, if the position exists on the board; 'L' moves our position left one column, if the position exists on the board; 'R' moves our position right one column, if the position exists on the board; '!' adds the character board[r][c] at our current position (r, c) to the answer. (Here, the only positions that exist on the board are positions with letters on them.) Return a sequence of moves that makes our answer equal to target in the minimum number of moves.  You may return any path that does so.   Example 1: Input: target = "leet" Output: "DDR!UURRR!!DDD!" Example 2: Input: target = "code" Output: "RR!DDRR!UUL!R!"   Constraints: 1 <= target.length <= 100 target consists only of English lowercase letters.
Medium
[ "hash-table", "string" ]
[ "const alphabetBoardPath = function(target) {\n let sx = 0,\n sy = 0;\n let dir = \"\";\n let a = \"a\".charCodeAt(0);\n for (let c of target) {\n let dx = (c.charCodeAt(0) - a) % 5,\n dy = ((c.charCodeAt(0) - a) / 5) >> 0,\n n;\n if (sx > dx) {\n n = sx - dx;\n while (n--) dir += \"L\";\n }\n if (sy < dy) {\n n = dy - sy;\n while (n--) dir += \"D\";\n }\n if (sy > dy) {\n n = sy - dy;\n while (n--) dir += \"U\";\n }\n if (sx < dx) {\n n = dx - sx;\n while (n--) dir += \"R\";\n }\n dir += \"!\";\n (sx = dx), (sy = dy);\n }\n return dir;\n};" ]
1,139
largest-1-bordered-square
[ "For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming.", "Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1)." ]
/** * @param {number[][]} grid * @return {number} */ var largest1BorderedSquare = function(grid) { };
Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.   Example 1: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 9 Example 2: Input: grid = [[1,1,0,0]] Output: 1   Constraints: 1 <= grid.length <= 100 1 <= grid[0].length <= 100 grid[i][j] is 0 or 1
Medium
[ "array", "dynamic-programming", "matrix" ]
[ "const largest1BorderedSquare = function(grid) {\n let A = grid;\n let m = A.length,\n n = A[0].length;\n let max = 0;\n const hori = Array.from(Array(m)).map(() => Array(n).fill(0));\n const ver = Array.from(Array(m)).map(() => Array(n).fill(0));\n for (let i = 0; i < m; ++i) {\n for (let j = 0; j < n; ++j) {\n if (A[i][j] > 0) {\n hori[i][j] = j > 0 ? hori[i][j - 1] + 1 : 1;\n ver[i][j] = i > 0 ? ver[i - 1][j] + 1 : 1;\n }\n }\n }\n for (let i = m - 1; i >= 0; i--) {\n for (let j = n - 1; j >= 0; j--) {\n let small = Math.min(hori[i][j], ver[i][j]);\n while (small > max) {\n if (ver[i][j - small + 1] >= small && hori[i - small + 1][j] >= small) {\n max = small;\n break\n }\n small--;\n }\n }\n }\n return max * max;\n};" ]
1,140
stone-game-ii
[ "Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m." ]
/** * @param {number[]} piles * @return {number} */ var stoneGameII = function(piles) { };
Alice and Bob continue their games with piles of stones.  There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].  The objective of the game is to end with the most stones.  Alice and Bob take turns, with Alice starting first.  Initially, M = 1. On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M.  Then, we set M = max(M, X). The game continues until all the stones have been taken. Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.   Example 1: Input: piles = [2,7,9,4,4] Output: 10 Explanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. Example 2: Input: piles = [1,2,3,4,5,100] Output: 104   Constraints: 1 <= piles.length <= 100 1 <= piles[i] <= 104
Medium
[ "array", "math", "dynamic-programming", "prefix-sum", "game-theory" ]
[ "const stoneGameII = function(piles) {\n let sums = [] //the sum from piles[i] to the end\n let hash = []\n if (piles == null || piles.length == 0) return 0\n let n = piles.length\n sums = new Array(n)\n sums[n - 1] = piles[n - 1]\n for (let i = n - 2; i >= 0; i--) {\n sums[i] = sums[i + 1] + piles[i] //the sum from piles[i] to the end\n }\n\n hash = Array.from({ length: n }, () => new Array(n).fill(0))\n return helper(piles, 0, 1)\n\n function helper(a, i, M) {\n if (i == a.length) return 0\n if (2 * M >= a.length - i) {\n return sums[i]\n }\n if (hash[i][M] != 0) return hash[i][M]\n let min = Number.MAX_SAFE_INTEGER //the min value the next player can get\n for (let x = 1; x <= 2 * M; x++) {\n min = Math.min(min, helper(a, i + x, Math.max(M, x)))\n }\n hash[i][M] = sums[i] - min //max stones = all the left stones - the min stones next player can get\n return hash[i][M]\n }\n}" ]
1,143
longest-common-subsequence
[ "Try dynamic programming. \r\nDP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j].", "DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j]\r\nDP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise" ]
/** * @param {string} text1 * @param {string} text2 * @return {number} */ var longestCommonSubsequence = function(text1, text2) { };
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde". A common subsequence of two strings is a subsequence that is common to both strings.   Example 1: Input: text1 = "abcde", text2 = "ace" Output: 3 Explanation: The longest common subsequence is "ace" and its length is 3. Example 2: Input: text1 = "abc", text2 = "abc" Output: 3 Explanation: The longest common subsequence is "abc" and its length is 3. Example 3: Input: text1 = "abc", text2 = "def" Output: 0 Explanation: There is no such common subsequence, so the result is 0.   Constraints: 1 <= text1.length, text2.length <= 1000 text1 and text2 consist of only lowercase English characters.
Medium
[ "string", "dynamic-programming" ]
[ "const longestCommonSubsequence = function(text1, text2) {\n let dp = new Array(text1.length + 1)\n for (let i = 0; i < dp.length; i++)\n dp[i] = new Array(text2.length + 1).fill(0)\n for (let i = 1; i < dp.length; i++) {\n for (let j = 1; j < dp[i].length; j++) {\n if (text1[i - 1] == text2[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1]\n else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])\n }\n }\n return dp[dp.length - 1].pop()\n}", "const longestCommonSubsequence = function(text1, text2) {\n const len1 = text1.length\n const len2 = text2.length\n if(len1 === 0 || len2 === 0) return 0\n const dp = Array(len2 + 1).fill(0)\n for(let i = 1; i <= len1; i++) {\n let prev = 0\n for(let j = 1; j <= len2; j++) {\n const tmp = dp[j]\n if(text1[i - 1] === text2[j - 1]) dp[j] = Math.max(dp[j], prev + 1)\n else {\n dp[j] = Math.max(dp[j - 1], dp[j])\n }\n prev = tmp\n }\n }\n return dp[len2]\n};" ]