Datasets:

QID
int64
1
2.85k
titleSlug
stringlengths
3
77
Hints
list
Code
stringlengths
80
1.34k
Body
stringlengths
190
4.55k
Difficulty
stringclasses
3 values
Topics
list
Definitions
stringclasses
14 values
Solutions
list
507
perfect-number
[]
/** * @param {number} num * @return {boolean} */ var checkPerfectNumber = function(num) { };
A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly. Given an integer n, return true if n is a perfect number, otherwise return false.   Example 1: Input: num = 28 Output: true Explanation: 28 = 1 + 2 + 4 + 7 + 14 1, 2, 4, 7, and 14 are all divisors of 28. Example 2: Input: num = 7 Output: false   Constraints: 1 <= num <= 108
Easy
[ "math" ]
[ "const checkPerfectNumber = function(num) {\n if (num === 1) return false;\n return chk(num);\n};\n\nfunction chk(num) {\n let min = 2;\n let max = Math.ceil(Math.sqrt(num));\n const res = [1];\n for (let i = min; i <= max; i++) {\n if (Number.isInteger(num / i) && res.indexOf(i) === -1) {\n res.push(i, num / i);\n }\n }\n if (res.reduce((ac, el) => ac + el, 0) === num) {\n return true;\n } else {\n return false;\n }\n}" ]
508
most-frequent-subtree-sum
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number[]} */ var findFrequentTreeSum = function(root) { };
Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).   Example 1: Input: root = [5,2,-3] Output: [2,-3,4] Example 2: Input: root = [5,2,-5] Output: [2]   Constraints: The number of nodes in the tree is in the range [1, 104]. -105 <= Node.val <= 105
Medium
[ "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 findFrequentTreeSum = function(root) {\n if (root == null) return [];\n const valArr = [];\n calc(root, valArr);\n const hash = {};\n valArr.forEach((el, idx) => {\n if (hash.hasOwnProperty(el)) {\n hash[el] += 1;\n } else {\n hash[el] = 1;\n }\n });\n const arr = Object.entries(hash).sort((a, b) => b[1] - a[1]);\n const max = arr[0][1];\n const res = [+arr[0][0]];\n for (let i = 1; i < arr.length; i++) {\n if (arr[i][1] === max) {\n res.push(+arr[i][0]);\n } else {\n return res;\n }\n }\n return res;\n};\n\nfunction calc(node, arr) {\n let sum = 0;\n if (node.left) {\n sum += calc(node.left, arr);\n }\n if (node.right) {\n sum += calc(node.right, arr);\n }\n sum += node.val;\n arr.push(sum);\n return sum;\n}" ]
509
fibonacci-number
[]
/** * @param {number} n * @return {number} */ var fib = function(n) { };
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given n, calculate F(n).   Example 1: Input: n = 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. Example 2: Input: n = 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. Example 3: Input: n = 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.   Constraints: 0 <= n <= 30
Easy
[ "math", "dynamic-programming", "recursion", "memoization" ]
[ "const cache = {}\nconst fib = function(N) {\n if(cache[N]) return cache[N]\n if(N === 0) return 0\n if(N === 1) return 1\n let res = fib(N - 1) + fib(N - 2)\n cache[N] = res\n return res\n};" ]
513
find-bottom-left-tree-value
[]
/** * 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 findBottomLeftValue = function(root) { };
Given the root of a binary tree, return the leftmost value in the last row of the tree.   Example 1: Input: root = [2,1,3] Output: 1 Example 2: Input: root = [1,2,3,4,null,5,6,null,null,7] Output: 7   Constraints: The number of nodes in the tree is in the range [1, 104]. -231 <= Node.val <= 231 - 1
Medium
[ "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const findBottomLeftValue = function(root) {\n const res = [];\n single(root, 0, res);\n return res[res.length - 1][0].val;\n};\n\nfunction single(node, row, arr) {\n if (node == null) {\n return null;\n }\n if (row < arr.length) {\n arr[row].push(node);\n } else {\n arr[row] = [node];\n }\n single(node.left, row + 1, arr);\n single(node.right, row + 1, arr);\n}" ]
514
freedom-trail
[]
/** * @param {string} ring * @param {string} key * @return {number} */ var findRotateSteps = function(ring, key) { };
In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door. Given a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword. Initially, the first character of the ring is aligned at the "12:00" direction. You should spell all the characters in key one by one by rotating ring clockwise or anticlockwise to make each character of the string key aligned at the "12:00" direction and then by pressing the center button. At the stage of rotating the ring to spell the key character key[i]: You can rotate the ring clockwise or anticlockwise by one place, which counts as one step. The final purpose of the rotation is to align one of ring's characters at the "12:00" direction, where this character must equal key[i]. If the character key[i] has been aligned at the "12:00" direction, press the center button to spell, which also counts as one step. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.   Example 1: Input: ring = "godding", key = "gd" Output: 4 Explanation: For the first key character 'g', since it is already in place, we just need 1 step to spell this character. For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo". Also, we need 1 more step for spelling. So the final output is 4. Example 2: Input: ring = "godding", key = "godding" Output: 13   Constraints: 1 <= ring.length, key.length <= 100 ring and key consist of only lower case English letters. It is guaranteed that key could always be spelled by rotating ring.
Hard
[ "string", "dynamic-programming", "depth-first-search", "breadth-first-search" ]
[ "const findRotateSteps = function(ring, key) {\n function findLeft(i, j) {\n let k = i\n let count = 0\n while (ring[k] !== key[j]) {\n k--\n count++\n if (k === -1) k += ring.length\n }\n return [k, count]\n }\n function findRight(i, j) {\n let k = i\n let count = 0\n while (ring[k] !== key[j]) {\n k++\n count++\n if (k === ring.length) k -= ring.length\n }\n return [k, count]\n }\n const dp = []\n for (let i = 0; i < ring.length; i++) {\n dp[i] = []\n }\n function f(i, j) {\n if (dp[i][j] !== undefined) return dp[i][j]\n if (j === key.length) return (dp[i][j] = 0)\n const [i1, c1] = findLeft(i, j)\n const [i2, c2] = findRight(i, j)\n return (dp[i][j] = Math.min(c1 + 1 + f(i1, j + 1), c2 + 1 + f(i2, j + 1)))\n }\n return f(0, 0)\n}" ]
515
find-largest-value-in-each-tree-row
[]
/** * 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 largestValues = function(root) { };
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).   Example 1: Input: root = [1,3,2,5,3,null,9] Output: [1,3,9] Example 2: Input: root = [1,2,3] Output: [1,3]   Constraints: The number of nodes in the tree will be in the range [0, 104]. -231 <= Node.val <= 231 - 1
Medium
[ "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const largestValues = function(root) {\n const res = [];\n single(root, 0, res);\n return res;\n};\n\nfunction single(node, row, arr) {\n if (node == null) {\n return null;\n }\n if (row < arr.length) {\n if (node.val > arr[row]) {\n arr[row] = node.val;\n }\n } else {\n arr[row] = node.val;\n }\n single(node.left, row + 1, arr);\n single(node.right, row + 1, arr);\n}" ]
516
longest-palindromic-subsequence
[]
/** * @param {string} s * @return {number} */ var longestPalindromeSubseq = function(s) { };
Given a string s, find the longest palindromic subsequence's length in s. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.   Example 1: Input: s = "bbbab" Output: 4 Explanation: One possible longest palindromic subsequence is "bbbb". Example 2: Input: s = "cbbd" Output: 2 Explanation: One possible longest palindromic subsequence is "bb".   Constraints: 1 <= s.length <= 1000 s consists only of lowercase English letters.
Medium
[ "string", "dynamic-programming" ]
[ "// 区间DP\n\n\nconst longestPalindromeSubseq = function(s) {\n const n = s.length\n const dp = Array.from({ length: n }, () => Array(n).fill(0))\n for(let i = 0; i < n; i++) dp[i][i] = 1\n for(let len = 2; len <= n; len++) {\n for(let i = 0; i + len - 1 < n; i++) {\n const j = i + len - 1\n if(s[i] === s[j]) dp[i][j] = 2 + 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[0][n - 1]\n};", "const longestPalindromeSubseq = function(s) {\n const n = s.length\n const dp = Array.from({ length: n }, () => Array(n).fill(0))\n for(let i = 0; i < n; i++) {\n dp[i][i] = 1\n for(let j = i - 1; j >= 0; j--) {\n if(s[i] === s[j]) {\n dp[i][j] = dp[i - 1][j + 1] + 2\n } else {\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j + 1])\n }\n }\n }\n \n return dp[n - 1][0]\n};", "const longestPalindromeSubseq = function(s) {\n const len = s.length\n const dp = Array.from({length: len + 1}, () => new Array(len + 1).fill(0))\n for(let i = len - 1; i >= 0; i--) {\n dp[i][i] = 1\n for(let j = i + 1; j < len; j++) {\n if(s[i] === s[j]) {\n dp[i][j] = dp[i+1][j-1] + 2\n } else {\n dp[i][j] = Math.max(dp[i][j - 1], dp[i+1][j])\n }\n }\n }\n return dp[0][s.length - 1]\n};" ]
517
super-washing-machines
[]
/** * @param {number[]} machines * @return {number} */ var findMinMoves = function(machines) { };
You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. For each move, you could choose any m (1 <= m <= n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time. Given an integer array machines representing the number of dresses in each washing machine from left to right on the line, return the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1.   Example 1: Input: machines = [1,0,5] Output: 3 Explanation: 1st move: 1 0 <-- 5 => 1 1 4 2nd move: 1 <-- 1 <-- 4 => 2 1 3 3rd move: 2 1 <-- 3 => 2 2 2 Example 2: Input: machines = [0,3,0] Output: 2 Explanation: 1st move: 0 <-- 3 0 => 1 2 0 2nd move: 1 2 --> 0 => 1 1 1 Example 3: Input: machines = [0,2,0] Output: -1 Explanation: It's impossible to make all three washing machines have the same number of dresses.   Constraints: n == machines.length 1 <= n <= 104 0 <= machines[i] <= 105
Hard
[ "array", "greedy" ]
[ "const findMinMoves = function(machines) {\n let total = 0\n for (let i of machines) total += i\n if (total % machines.length !== 0) return -1\n let avg = (total / machines.length) >> 0,\n cnt = 0,\n max = 0\n for (let load of machines) {\n cnt += load - avg\n max = Math.max(Math.max(max, Math.abs(cnt)), load - avg)\n }\n return max\n}" ]
518
coin-change-ii
[]
/** * @param {number} amount * @param {number[]} coins * @return {number} */ var change = function(amount, coins) { };
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0. You may assume that you have an infinite number of each kind of coin. The answer is guaranteed to fit into a signed 32-bit integer.   Example 1: Input: amount = 5, coins = [1,2,5] Output: 4 Explanation: there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 Example 2: Input: amount = 3, coins = [2] Output: 0 Explanation: the amount of 3 cannot be made up just with coins of 2. Example 3: Input: amount = 10, coins = [10] Output: 1   Constraints: 1 <= coins.length <= 300 1 <= coins[i] <= 5000 All the values of coins are unique. 0 <= amount <= 5000
Medium
[ "array", "dynamic-programming" ]
[ "function change(amount, coins) {\n const dp = Array.from(new Array(coins.length + 1), () =>\n new Array(amount + 1).fill(0)\n )\n dp[0][0] = 1\n for (let i = 1; i <= coins.length; i++) {\n dp[i][0] = 1\n for (let j = 1; j <= amount; j++) {\n dp[i][j] =\n dp[i - 1][j] + (j >= coins[i - 1] ? dp[i][j - coins[i - 1]] : 0)\n }\n }\n return dp[coins.length][amount]\n}", "const change = function (amount, coins) {\n const dp = Array(amount + 1).fill(0)\n dp[0] = 1\n for (let coin of coins) {\n for (let i = coin; i < amount + 1; i++) dp[i] += dp[i - coin]\n }\n return dp[amount]\n}", "", "const change = function(amount,coins) {\n const n = coins.length\n const dp = Array.from({ length: n + 1 }, () => Array(amount + 1))\n dp[0][0] = 1\n for(let i = 0; i < n; i++) dp[i][0] = 1\n helper(0, amount)\n return dp[0][amount] === undefined ? 0 : dp[0][amount]\n \n function helper(i, rem) {\n if(dp[i][rem] != null) return dp[i][rem]\n if(rem < 0) return 0\n if(rem === 0) return 1\n if(i >= coins.length) return 0\n let res = 0\n \n res += helper(i, rem - coins[i])\n res += helper(i + 1, rem)\n \n dp[i][rem] = res\n \n return res\n } \n}" ]
519
random-flip-matrix
[]
/** * @param {number} m * @param {number} n */ var Solution = function(m, n) { }; /** * @return {number[]} */ Solution.prototype.flip = function() { }; /** * @return {void} */ Solution.prototype.reset = function() { }; /** * Your Solution object will be instantiated and called as such: * var obj = new Solution(m, n) * var param_1 = obj.flip() * obj.reset() */
There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1. All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned. Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity. Implement the Solution class: Solution(int m, int n) Initializes the object with the size of the binary matrix m and n. int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1. void reset() Resets all the values of the matrix to be 0.   Example 1: Input ["Solution", "flip", "flip", "flip", "reset", "flip"] [[3, 1], [], [], [], [], []] Output [null, [1, 0], [2, 0], [0, 0], null, [2, 0]] Explanation Solution solution = new Solution(3, 1); solution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned. solution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0] solution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned. solution.reset(); // All the values are reset to 0 and can be returned. solution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.   Constraints: 1 <= m, n <= 104 There will be at least one free cell for each call to flip. At most 1000 calls will be made to flip and reset.
Medium
[ "hash-table", "math", "reservoir-sampling", "randomized" ]
[ "const Solution = function(n_rows, n_cols) {\n this.r = n_rows\n this.c = n_cols\n this.total = n_rows * n_cols\n this.m = new Map()\n}\n\n\nSolution.prototype.flip = function() {\n const r = (Math.random() * this.total--) >> 0\n const i = this.m.get(r) || r\n this.m.set(r, this.m.get(this.total) || this.total)\n return [(i / this.c) >> 0, i % this.c]\n}\n\n\nSolution.prototype.reset = function() {\n this.m.clear()\n this.total = this.c * this.r\n}" ]
520
detect-capital
[]
/** * @param {string} word * @return {boolean} */ var detectCapitalUse = function(word) { };
We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in this word is capital, like "Google". Given a string word, return true if the usage of capitals in it is right.   Example 1: Input: word = "USA" Output: true Example 2: Input: word = "FlaG" Output: false   Constraints: 1 <= word.length <= 100 word consists of lowercase and uppercase English letters.
Easy
[ "string" ]
[ "const ac = \"A\".charCodeAt(0);\nconst zc = \"Z\".charCodeAt(0);\nconst detectCapitalUse = function(word) {\n if (allCap(word) || noCap(word) || capHead(word)) {\n return true;\n }\n return false;\n};\n\nfunction allCap(str) {\n let c;\n for (let i = 0; i < str.length; i++) {\n c = str.charCodeAt(i);\n if (c < ac || c > zc) {\n return false;\n }\n }\n return true;\n}\n\nfunction noCap(str) {\n let c;\n for (let i = 0; i < str.length; i++) {\n c = str.charCodeAt(i);\n if (c >= ac && c <= zc) {\n return false;\n }\n }\n return true;\n}\n\nfunction capHead(str) {\n let c;\n let first;\n for (let i = 0; i < str.length; i++) {\n c = str.charCodeAt(i);\n if (i === 0) {\n first = c;\n } else if (c >= ac && c <= zc) {\n return false;\n }\n }\n if (first >= ac && first <= zc) {\n return true;\n } else {\n return false;\n }\n}\n\nconsole.log(detectCapitalUse(\"ffffffffffffffffffffF\"));\nconsole.log(detectCapitalUse(\"Leetcode\"));" ]
521
longest-uncommon-subsequence-i
[]
/** * @param {string} a * @param {string} b * @return {number} */ var findLUSlength = function(a, b) { };
Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence does not exist, return -1. An uncommon subsequence between two strings is a string that is a subsequence of one but not the other. A subsequence of a string s is a string that can be obtained after deleting any number of characters from s. For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).   Example 1: Input: a = "aba", b = "cdc" Output: 3 Explanation: One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc". Note that "cdc" is also a longest uncommon subsequence. Example 2: Input: a = "aaa", b = "bbb" Output: 3 Explanation: The longest uncommon subsequences are "aaa" and "bbb". Example 3: Input: a = "aaa", b = "aaa" Output: -1 Explanation: Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.   Constraints: 1 <= a.length, b.length <= 100 a and b consist of lower-case English letters.
Easy
[ "string" ]
[ "const findLUSlength = function(a, b) {\n return a === b ? -1 : Math.max(a.length, b.length);\n};" ]
522
longest-uncommon-subsequence-ii
[]
/** * @param {string[]} strs * @return {number} */ var findLUSlength = function(strs) { };
Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1. An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others. A subsequence of a string s is a string that can be obtained after deleting any number of characters from s. For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).   Example 1: Input: strs = ["aba","cdc","eae"] Output: 3 Example 2: Input: strs = ["aaa","aaa","aa"] Output: -1   Constraints: 2 <= strs.length <= 50 1 <= strs[i].length <= 10 strs[i] consists of lowercase English letters.
Medium
[ "array", "hash-table", "two-pointers", "string", "sorting" ]
[ "const findLUSlength = function(strs) {\n strs.sort((a, b) => b.length - a.length)\n const dup = getDuplicates(strs)\n for(let i = 0; i < strs.length; i++) {\n if(!dup.has(strs[i])) {\n if(i === 0) return strs[0].length\n for(let j = 0; j < i; j++) {\n if(isSubsequence(strs[j], strs[i])) break\n if(j === i - 1) return strs[i].length\n }\n }\n }\n return -1\n};\n\nfunction isSubsequence(a, b) {\n let i = 0, j = 0\n while(i < a.length && j < b.length) {\n if(a.charAt(i) === b.charAt(j)) j++\n i++\n }\n return j === b.length\n}\n\nfunction getDuplicates(arr) {\n const set = new Set()\n const dup = new Set()\n for(let el of arr) {\n if(set.has(el)) dup.add(el)\n else set.add(el)\n }\n return dup\n}" ]
523
continuous-subarray-sum
[]
/** * @param {number[]} nums * @param {number} k * @return {boolean} */ var checkSubarraySum = function(nums, k) { };
Given an integer array nums and an integer k, return true if nums has a good subarray or false otherwise. A good subarray is a subarray where: its length is at least two, and the sum of the elements of the subarray is a multiple of k. Note that: A subarray is a contiguous part of the array. An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.   Example 1: Input: nums = [23,2,4,6,7], k = 6 Output: true Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6. Example 2: Input: nums = [23,2,6,4,7], k = 6 Output: true Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer. Example 3: Input: nums = [23,2,6,4,7], k = 13 Output: false   Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109 0 <= sum(nums[i]) <= 231 - 1 1 <= k <= 231 - 1
Medium
[ "array", "hash-table", "math", "prefix-sum" ]
[ "const checkSubarraySum = function(nums, k) {\n const map = {0: -1}\n let runningSum = 0\n for(let i = 0; i < nums.length; i++) {\n runningSum += nums[i]\n if(k !== 0) runningSum %= k\n let prev = map[runningSum]\n if(prev != null) {\n if(i - prev > 1) return true\n } else {\n map[runningSum] = i\n }\n }\n return false\n};" ]
524
longest-word-in-dictionary-through-deleting
[]
/** * @param {string} s * @param {string[]} dictionary * @return {string} */ var findLongestWord = function(s, dictionary) { };
Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.   Example 1: Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"] Output: "apple" Example 2: Input: s = "abpcplea", dictionary = ["a","b","c"] Output: "a"   Constraints: 1 <= s.length <= 1000 1 <= dictionary.length <= 1000 1 <= dictionary[i].length <= 1000 s and dictionary[i] consist of lowercase English letters.
Medium
[ "array", "two-pointers", "string", "sorting" ]
[ " const findLongestWord = function(s, dictionary) {\n let res = ''\n for (const word of dictionary) {\n let j = 0\n for (let i = 0, len = s.length; i < len; i++) {\n if(word[j] === s[i]) j++\n if(j === word.length) {\n if(word.length > res.length) res = word\n else if(word.length === res.length && word < res) res = word\n break\n }\n }\n }\n return res\n};", "const findLongestWord = function (s, dictionary) {\n const n = dictionary.length\n const idxArr = Array(n).fill(0)\n let res = ''\n for (const ch of s) {\n for (let i = 0; i < n; i++) {\n const idx = idxArr[i]\n if (idx >= dictionary[i].length) continue\n if (ch === dictionary[i][idx]) {\n idxArr[i]++\n }\n\n if (\n idxArr[i] === dictionary[i].length &&\n (dictionary[i].length > res.length ||\n (dictionary[i].length === res.length && dictionary[i] < res))\n ) {\n res = dictionary[i]\n }\n }\n }\n return res\n}", "const findLongestWord = function(s, dictionary) {\n let res = ''\n for(let d of dictionary) {\n let j = 0\n for(let i = 0, n = s.length; i < n; i++) {\n if(d[j] === s[i]) j++\n if(j === d.length && j >= res.length) {\n if(j > res.length || d < res) {\n res = d\n }\n break\n }\n }\n }\n return res\n};", "const findLongestWord = function(s, dictionary) {\n dictionary.sort((a, b) => a.length === b.length ? cmp(a, b) : b.length - a.length)\n let res = ''\n for(let d of dictionary) {\n let j = 0\n for(let i = 0, n = s.length; i < n; i++) {\n if(d[j] === s[i]) j++\n if(j === d.length) return d\n }\n }\n return ''\n function cmp(s1, s2) {\n for(let i = 0, n = s1.length; i < n; i++) {\n if(s1[i] < s2[i]) return -1\n else if(s1[i] > s2[i]) return 1\n }\n return 0\n }\n};", "const findLongestWord = function(s, d) {\n let results = [];\n let maxLen = 0;\n for (const word of d) {\n let j = 0;\n for (let i = 0; i < s.length; i++) {\n if (s[i] === word[j]) {\n j++;\n if (j === word.length) break;\n }\n }\n if (j === word.length && word.length >= maxLen) {\n if (word.length > maxLen) {\n maxLen = word.length;\n results = [];\n }\n results.push(word);\n }\n }\n \n let result = results[0];\n for (let i = 1; i < results.length; i++) {\n if (results[i] < result) result = results[i];\n }\n return result || '';\n}" ]
525
contiguous-array
[]
/** * @param {number[]} nums * @return {number} */ var findMaxLength = function(nums) { };
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.   Example 1: Input: nums = [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. Example 2: Input: nums = [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.   Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.
Medium
[ "array", "hash-table", "prefix-sum" ]
[ "const findMaxLength = function(nums) {\n let res = 0, sum = 0\n const hash = {0: -1}, n = nums.length\n \n for(let i = 0; i < n; i++) {\n const cur = nums[i]\n sum += cur === 0 ? -1 : 1\n if(hash[sum] != null) {\n res = Math.max(res, i - hash[sum])\n } else {\n hash[sum] = i\n }\n \n }\n \n return res\n};", "const findMaxLength = function (nums) {\n const map = new Map()\n map.set(0, -1)\n let count = 0\n let max = 0\n for (let i = 0; i < nums.length; i++) {\n let num = nums[i]\n if (num === 0) {\n count -= 1\n }\n if (num === 1) {\n count += 1\n }\n if (map.has(count)) {\n max = Math.max(max, i - map.get(count))\n } else {\n map.set(count, i)\n }\n }\n return max\n}" ]
526
beautiful-arrangement
[]
/** * @param {number} n * @return {number} */ var countArrangement = function(n) { };
Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true: perm[i] is divisible by i. i is divisible by perm[i]. Given an integer n, return the number of the beautiful arrangements that you can construct.   Example 1: Input: n = 2 Output: 2 Explanation: The first beautiful arrangement is [1,2]: - perm[1] = 1 is divisible by i = 1 - perm[2] = 2 is divisible by i = 2 The second beautiful arrangement is [2,1]: - perm[1] = 2 is divisible by i = 1 - i = 2 is divisible by perm[2] = 1 Example 2: Input: n = 1 Output: 1   Constraints: 1 <= n <= 15
Medium
[ "array", "dynamic-programming", "backtracking", "bit-manipulation", "bitmask" ]
[ "var countArrangement = function(N) {\n let used = Array(N + 1).fill(false)\n let res = 0\n function backtrack(curIdx) {\n if (curIdx === 0) return res++\n for (let i = 1; i <= N; i++) {\n if (used[i]) continue\n if (i % curIdx === 0 || curIdx % i === 0) {\n used[i] = true\n backtrack(curIdx - 1)\n used[i] = false\n }\n }\n }\n backtrack(N)\n return res\n};" ]
528
random-pick-with-weight
[]
/** * @param {number[]} w */ var Solution = function(w) { }; /** * @return {number} */ Solution.prototype.pickIndex = function() { }; /** * Your Solution object will be instantiated and called as such: * var obj = new Solution(w) * var param_1 = obj.pickIndex() */
You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index. You need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w). For example, if w = [1, 3], the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e., 25%), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75%).   Example 1: Input ["Solution","pickIndex"] [[[1]],[]] Output [null,0] Explanation Solution solution = new Solution([1]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. Example 2: Input ["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"] [[[1,3]],[],[],[],[],[]] Output [null,1,1,1,1,0] Explanation Solution solution = new Solution([1, 3]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: [null,1,1,1,1,0] [null,1,1,1,1,1] [null,1,1,1,0,0] [null,1,1,1,0,1] [null,1,0,1,0,0] ...... and so on.   Constraints: 1 <= w.length <= 104 1 <= w[i] <= 105 pickIndex will be called at most 104 times.
Medium
[ "array", "math", "binary-search", "prefix-sum", "randomized" ]
[ "const Solution = function(w) {\n this.a = []\n let sum = 0\n for (let i = 0, len = w.length; i < len; i++) {\n sum += w[i]\n this.a[i] = sum\n }\n}\n\n\nSolution.prototype.pickIndex = function() {\n const len = this.a.length\n const sum = this.a[len - 1]\n const rand = ((Math.random() * sum) >> 0) + 1\n let l = 0,\n h = len - 1\n while (l < h) {\n const mid = (l + h) >> 1\n if (this.a[mid] === rand) return mid\n else if (this.a[mid] < rand) l = mid + 1\n else h = mid\n }\n return l\n}", "const Solution = function(w) {\n this.a = []\n let sum = 0\n for(let i = 0, len = w.length; i < len; i++) {\n sum += w[i]\n this.a[i] = sum\n }\n};\n\n\nSolution.prototype.pickIndex = function() {\n const len = this.a.length\n const sum = this.a[len - 1]\n const rand = ((Math.random() * sum) >> 0) + 1\n let l = 0, h = len - 1\n while(l <= h) {\n const mid = (l + h) >> 1\n if(this.a[mid] === rand) return mid\n else if(this.a[mid] < rand) l = mid + 1\n else h = mid - 1\n }\n return l\n};", "const Solution = function(w) {\n this.a = []\n let sum = 0\n for(let i = 0, len = w.length; i < len; i++) {\n sum += w[i]\n this.a[i] = sum\n }\n};\n\n\nSolution.prototype.pickIndex = function() {\n const len = this.a.length\n const sum = this.a[len - 1]\n const rand = ((Math.random() * sum) >> 0) + 1\n let l = 0, h = len - 1\n while(l < h) {\n const mid = (l + h) >> 1\n if(this.a[mid] < rand) l = mid + 1\n else h = mid\n }\n return l\n};" ]
529
minesweeper
[]
/** * @param {character[][]} board * @param {number[]} click * @return {character[][]} */ var updateBoard = function(board, click) { };
Let's play the minesweeper game (Wikipedia, online game)! You are given an m x n char matrix board representing the game board where: 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals), digit ('1' to '8') represents how many mines are adjacent to this revealed square, and 'X' represents a revealed mine. You are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares ('M' or 'E'). Return the board after revealing this position according to the following rules: If a mine 'M' is revealed, then the game is over. You should change it to 'X'. If an empty square 'E' with no adjacent mines is revealed, then change it to a revealed blank 'B' and all of its adjacent unrevealed squares should be revealed recursively. If an empty square 'E' with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines. Return the board when no more squares will be revealed.   Example 1: Input: board = [["E","E","E","E","E"],["E","E","M","E","E"],["E","E","E","E","E"],["E","E","E","E","E"]], click = [3,0] Output: [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]] Example 2: Input: board = [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]], click = [1,2] Output: [["B","1","E","1","B"],["B","1","X","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]   Constraints: m == board.length n == board[i].length 1 <= m, n <= 50 board[i][j] is either 'M', 'E', 'B', or a digit from '1' to '8'. click.length == 2 0 <= clickr < m 0 <= clickc < n board[clickr][clickc] is either 'M' or 'E'.
Medium
[ "array", "depth-first-search", "breadth-first-search", "matrix" ]
[ "const updateBoard = function(board, click) {\n const visited = new Set();\n const [clickRow, clickCol] = click;\n if (board[clickRow][clickCol] === \"M\") {\n board[clickRow][clickCol] = \"X\";\n return board;\n }\n const directions = [\n [-1, 0], // top\n [1, 0], // down\n [0, -1], // left\n [0, 1], // right\n [-1, -1], // top left\n [1, 1], // bottom right\n [-1, 1], // top right\n [1, -1] // bottom left\n ];\n\n function dfs(row, col) {\n visited.add(`${row},${col}`);\n if (board[row][col] === \"M\") return;\n let numBombs = 0;\n for (let dir of directions) {\n if (\n board[row + dir[0]] === undefined ||\n board[row + dir[0]][col + dir[1]] === undefined\n )\n continue;\n if (board[row + dir[0]][col + dir[1]] === \"M\") {\n numBombs += 1;\n }\n }\n if (numBombs) {\n board[row][col] = `${numBombs}`;\n return;\n }\n board[row][col] = \"B\";\n for (let dir of directions) {\n if (\n board[row + dir[0]] === undefined ||\n board[row + dir[0]][col + dir[1]] === undefined ||\n board[row + dir[0]][col + dir[1]] !== \"E\"\n )\n continue;\n if (!visited.has(`${row + dir[0]},${col + dir[1]}`)) {\n dfs(row + dir[0], col + dir[1]);\n }\n }\n }\n dfs(clickRow, clickCol);\n return board;\n};" ]
530
minimum-absolute-difference-in-bst
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var getMinimumDifference = function(root) { };
Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.   Example 1: Input: root = [4,2,6,1,3] Output: 1 Example 2: Input: root = [1,0,48,null,null,12,49] Output: 1   Constraints: The number of nodes in the tree is in the range [2, 104]. 0 <= Node.val <= 105   Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
Easy
[ "tree", "depth-first-search", "breadth-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 getMinimumDifference = function(root) {\n const arr = [];\n traversal(root, arr);\n let min = Number.MAX_SAFE_INTEGER;\n for (let i = 1; i < arr.length; i++) {\n min = Math.min(min, arr[i] - arr[i - 1]);\n }\n return min;\n};\n\nfunction traversal(node, arr) {\n if (node === null) return;\n if (node.left) {\n traversal(node.left, arr);\n }\n arr.push(node.val);\n if (node.right) {\n traversal(node.right, arr);\n }\n}" ]
532
k-diff-pairs-in-an-array
[]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var findPairs = function(nums, k) { };
Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: 0 <= i, j < nums.length i != j |nums[i] - nums[j]| == k Notice that |val| denotes the absolute value of val.   Example 1: Input: nums = [3,1,4,1,5], k = 2 Output: 2 Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of unique pairs. Example 2: Input: nums = [1,2,3,4,5], k = 1 Output: 4 Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). Example 3: Input: nums = [1,3,1,5,4], k = 0 Output: 1 Explanation: There is one 0-diff pair in the array, (1, 1).   Constraints: 1 <= nums.length <= 104 -107 <= nums[i] <= 107 0 <= k <= 107
Medium
[ "array", "hash-table", "two-pointers", "binary-search", "sorting" ]
[ "const findPairs = function(nums, k) {\n if(k < 0) return 0\n let count = 0\n const hash = {}\n for(let i = 0; i < nums.length; i++) {\n hash[nums[i]] = i\n }\n for(let i = 0; i < nums.length; i++) {\n if(hash.hasOwnProperty(nums[i] + k) && hash[nums[i] + k] !== i) {\n count++\n delete hash[nums[i] + k]\n }\n }\n\n return count\n};" ]
535
encode-and-decode-tinyurl
[]
/** * Encodes a URL to a shortened URL. * * @param {string} longUrl * @return {string} */ var encode = function(longUrl) { }; /** * Decodes a shortened URL to its original URL. * * @param {string} shortUrl * @return {string} */ var decode = function(shortUrl) { }; /** * Your functions will be called as such: * decode(encode(url)); */
Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the Solution class: Solution() Initializes the object of the system. String encode(String longUrl) Returns a tiny URL for the given longUrl. String decode(String shortUrl) Returns the original long URL for the given shortUrl. It is guaranteed that the given shortUrl was encoded by the same object.   Example 1: Input: url = "https://leetcode.com/problems/design-tinyurl" Output: "https://leetcode.com/problems/design-tinyurl" Explanation: Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it.   Constraints: 1 <= url.length <= 104 url is guranteed to be a valid URL.
Medium
[ "hash-table", "string", "design", "hash-function" ]
null
[]
537
complex-number-multiplication
[]
/** * @param {string} num1 * @param {string} num2 * @return {string} */ var complexNumberMultiply = function(num1, num2) { };
A complex number can be represented as a string on the form "real+imaginaryi" where: real is the real part and is an integer in the range [-100, 100]. imaginary is the imaginary part and is an integer in the range [-100, 100]. i2 == -1. Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.   Example 1: Input: num1 = "1+1i", num2 = "1+1i" Output: "0+2i" Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. Example 2: Input: num1 = "1+-1i", num2 = "1+-1i" Output: "0+-2i" Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.   Constraints: num1 and num2 are valid complex numbers.
Medium
[ "math", "string", "simulation" ]
null
[]
538
convert-bst-to-greater-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {TreeNode} */ var convertBST = 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 [0, 104]. -104 <= Node.val <= 104 All the values in the tree are unique. root is guaranteed to be a valid binary search tree.   Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-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 convertBST = function(root) {\n if (root == null) return null;\n convertBST(root.right);\n root.val += sum;\n sum = root.val;\n convertBST(root.left);\n return root;\n};" ]
539
minimum-time-difference
[]
/** * @param {string[]} timePoints * @return {number} */ var findMinDifference = function(timePoints) { };
Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list.   Example 1: Input: timePoints = ["23:59","00:00"] Output: 1 Example 2: Input: timePoints = ["00:00","23:59","00:00"] Output: 0   Constraints: 2 <= timePoints.length <= 2 * 104 timePoints[i] is in the format "HH:MM".
Medium
[ "array", "math", "string", "sorting" ]
[ "const findMinDifference = function(timePoints) {\n const sortedArr = timePoints\n .map(el => {\n const arr = el.trim().split(\":\");\n return arr[0] === \"00\" && arr[1] === \"00\"\n ? 24 * 60\n : +arr[0] * 60 + +arr[1];\n })\n .sort((a, b) => a - b);\n let prev = sortedArr[0];\n let res = Number.MAX_SAFE_INTEGER;\n const mid = 12 * 60;\n for (let i = 1; i < sortedArr.length; i++) {\n res = Math.min(res, Math.abs(sortedArr[i] - prev));\n prev = sortedArr[i];\n }\n if (sortedArr[0] < mid && sortedArr[sortedArr.length - 1] > mid) {\n res = Math.min(\n res,\n sortedArr[0] + 2 * mid - sortedArr[sortedArr.length - 1]\n );\n }\n return res;\n};\n\nconsole.log(findMinDifference([\"23:59\", \"00:00\"]));\nconsole.log(findMinDifference([\"12:12\", \"00:13\"]));\nconsole.log(findMinDifference([\"05:31\", \"22:08\", \"00:35\"]));" ]
540
single-element-in-a-sorted-array
[]
/** * @param {number[]} nums * @return {number} */ var singleNonDuplicate = function(nums) { };
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element that appears only once. Your solution must run in O(log n) time and O(1) space.   Example 1: Input: nums = [1,1,2,3,3,4,4,8,8] Output: 2 Example 2: Input: nums = [3,3,7,7,10,11,11] Output: 10   Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 105
Medium
[ "array", "binary-search" ]
[ "const singleNonDuplicate = function(nums) {\n let i = 0;\n while (true) {\n if (nums[i] == nums[i + 1]) {\n i += 2;\n } else {\n return nums[i];\n }\n }\n};", "const singleNonDuplicate = function(nums) {\n const n = nums.length\n let left = 0, right = n - 1\n while(left < right) {\n const mid = left + ((right - left) >> 1)\n if(nums[mid] === nums[mid ^ 1]) left = mid + 1\n else right = mid\n }\n \n return nums[left]\n};", "const singleNonDuplicate = function(nums) {\n const n = nums.length\n let left = 0, right = n - 1\n while(left < right) {\n const mid = ~~((left + right) / 2)\n if((mid % 2 === 0 && nums[mid] === nums[mid + 1]) || (mid % 2 === 1 && nums[mid] === nums[mid - 1])) left = mid + 1\n else right = mid\n }\n \n return nums[left]\n};", "const singleNonDuplicate = function(nums) {\n if(nums.length === 0) return 0\n let res = nums[0]\n for(let i = 1, len = nums.length; i < len; i++) {\n res ^= nums[i]\n }\n return res\n};" ]
541
reverse-string-ii
[]
/** * @param {string} s * @param {number} k * @return {string} */ var reverseStr = function(s, k) { };
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string. If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.   Example 1: Input: s = "abcdefg", k = 2 Output: "bacdfeg" Example 2: Input: s = "abcd", k = 2 Output: "bacd"   Constraints: 1 <= s.length <= 104 s consists of only lowercase English letters. 1 <= k <= 104
Easy
[ "two-pointers", "string" ]
[ "const reverseStr = function(s, k) {\n const arr = s.split('')\n for(let i = 0, len = s.length; i < len; i += 2 * k) {\n helper(arr, i, k)\n }\n return arr.join('')\n};\n\nfunction helper(arr, start, k) {\n let s = start\n let e = arr.length > start + k - 1 ? start + k - 1 : arr.length\n while(s < e) {\n swap(arr, s, e)\n s++\n e--\n }\n}\n\nfunction swap(arr, s, e) {\n const tmp = arr[s]\n arr[s] = arr[e]\n arr[e] = tmp\n}" ]
542
01-matrix
[]
/** * @param {number[][]} mat * @return {number[][]} */ var updateMatrix = function(mat) { };
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1.   Example 1: Input: mat = [[0,0,0],[0,1,0],[0,0,0]] Output: [[0,0,0],[0,1,0],[0,0,0]] Example 2: Input: mat = [[0,0,0],[0,1,0],[1,1,1]] Output: [[0,0,0],[0,1,0],[1,2,1]]   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 104 1 <= m * n <= 104 mat[i][j] is either 0 or 1. There is at least one 0 in mat.
Medium
[ "array", "dynamic-programming", "breadth-first-search", "matrix" ]
[ "const updateMatrix = function (matrix) {\n const rows = matrix.length, cols = matrix[0].length;\n const maxDist = rows + cols;\n let dist = new Array(rows).fill(null).map(() => new Array(cols).fill(0));\n \n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n if (matrix[i][j] !== 0) {\n dist[i][j] = hasNeighborZero(i, j, matrix, rows, cols) ? 1 : maxDist;\n }\n }\n }\n \n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n if (dist[i][j] === 1) {\n dfs(dist, i, j, -1);\n }\n }\n }\n \n return dist;\n };\n \n const dfs = function (dist, row, col, step) {\n if (row < 0 || row >= dist.length || col < 0 || col >= dist[0].length || dist[row][col] <= step) return;\n \n if (step > 0) dist[row][col] = step;\n \n dfs(dist, row + 1, col, dist[row][col] + 1);\n dfs(dist, row - 1, col, dist[row][col] + 1);\n dfs(dist, row, col + 1, dist[row][col] + 1);\n dfs(dist, row, col - 1, dist[row][col] + 1);\n };\n \n const hasNeighborZero = function (row, col, matrix, rows, cols) {\n if (row < rows - 1 && matrix[row + 1][col] === 0) return true;\n if (row > 0 && matrix[row - 1][col] === 0) return true;\n if (col > 0 && matrix[row][col - 1] === 0) return true;\n if (col < cols - 1 && matrix[row][col + 1] === 0) return true;\n \n return false;\n };" ]
543
diameter-of-binary-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var diameterOfBinaryTree = function(root) { };
Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them.   Example 1: Input: root = [1,2,3,4,5] Output: 3 Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. Example 2: Input: root = [1,2] Output: 1   Constraints: The number of nodes in the tree is in the range [1, 104]. -100 <= Node.val <= 100
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 diameterOfBinaryTree = function (root) {\n if (root === null) return 0\n let longest = 0\n function dfs(node) {\n if (node === null) return 0\n let leftmax = dfs(node.left)\n let rightmax = dfs(node.right)\n longest = Math.max(longest, leftmax + 1 + rightmax)\n return Math.max(leftmax, rightmax) + 1\n }\n dfs(root)\n return longest - 1\n}", "const diameterOfBinaryTree = function(root) {\n let res = 0\n dfs(root)\n return res\n\n function dfs(node) {\n if(node == null) return 0\n const left = dfs(node.left), right = dfs(node.right)\n res = Math.max(res, left + right)\n return Math.max(left, right) + 1\n }\n};", "const diameterOfBinaryTree = function(root) {\n let res = -Infinity\n dfs(root)\n return res\n function dfs(node) {\n if(node == null) return -1\n const left = dfs(node.left)\n const right = dfs(node.right)\n res = Math.max(res, left + right + 2)\n return Math.max(left, right) + 1\n }\n};" ]
546
remove-boxes
[]
/** * @param {number[]} boxes * @return {number} */ var removeBoxes = function(boxes) { };
You are given several boxes with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), remove them and get k * k points. Return the maximum points you can get.   Example 1: Input: boxes = [1,3,2,2,2,3,4,3,1] Output: 23 Explanation: [1, 3, 2, 2, 2, 3, 4, 3, 1] ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) ----> [1, 3, 3, 3, 1] (1*1=1 points) ----> [1, 1] (3*3=9 points) ----> [] (2*2=4 points) Example 2: Input: boxes = [1,1,1] Output: 9 Example 3: Input: boxes = [1] Output: 1   Constraints: 1 <= boxes.length <= 100 1 <= boxes[i] <= 100
Hard
[ "array", "dynamic-programming", "memoization" ]
[ "const removeBoxes = function(boxes) {\n const n = boxes.length\n const dp = Array.from(new Array(n), () => {\n return Array.from(new Array(n), () => {\n return new Array(n).fill(0)\n })\n })\n return removeBoxesSub(boxes, 0, n - 1, 0, dp)\n};\n\nfunction removeBoxesSub(boxes, i, j, k, dp) {\n if(i > j) return 0;\n if(dp[i][j][k] > 0) return dp[i][j][k]\n for(; i + 1 <= j && boxes[i+1] === boxes[i] ; i++, k++) {\n // optimization: all boxes of the same color counted continuously from the first box should be grouped together\n }\n let res = (k+1) * (k+1) + removeBoxesSub(boxes, i + 1, j, 0, dp)\n for(let m = i + 1; m <= j; m++) {\n if(boxes[i] === boxes[m]) {\n res = Math.max(res, removeBoxesSub(boxes, i + 1, m - 1, 0, dp) + removeBoxesSub(boxes, m, j, k + 1, dp) )\n }\n }\n dp[i][j][k] = res\n return res\n}" ]
547
number-of-provinces
[]
/** * @param {number[][]} isConnected * @return {number} */ var findCircleNum = function(isConnected) { };
There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. A province is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise. Return the total number of provinces.   Example 1: Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]] Output: 2 Example 2: Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]] Output: 3   Constraints: 1 <= n <= 200 n == isConnected.length n == isConnected[i].length isConnected[i][j] is 1 or 0. isConnected[i][i] == 1 isConnected[i][j] == isConnected[j][i]
Medium
[ "depth-first-search", "breadth-first-search", "union-find", "graph" ]
[ "const findCircleNum = function(M) {\n let count = 0\n const visited = {}\n const dfs = function(M, i) {\n for (let j = 0; j < M[i].length; j++) {\n if (M[i][j] == 1 && !visited[j]) {\n visited[j] = true\n dfs(M, j)\n }\n }\n }\n for (let i = 0; i < M.length; i++) {\n if (!visited[i]) {\n dfs(M, i)\n count++\n }\n }\n return count\n}" ]
551
student-attendance-record-i
[]
/** * @param {string} s * @return {boolean} */ var checkRecord = function(s) { };
You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: 'A': Absent. 'L': Late. 'P': Present. The student is eligible for an attendance award if they meet both of the following criteria: The student was absent ('A') for strictly fewer than 2 days total. The student was never late ('L') for 3 or more consecutive days. Return true if the student is eligible for an attendance award, or false otherwise.   Example 1: Input: s = "PPALLP" Output: true Explanation: The student has fewer than 2 absences and was never late 3 or more consecutive days. Example 2: Input: s = "PPALLL" Output: false Explanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.   Constraints: 1 <= s.length <= 1000 s[i] is either 'A', 'L', or 'P'.
Easy
[ "string" ]
[ "const checkRecord = function(s) {\n let anum = 0\n let plidx = -1\n for(let i = 0, len = s.length; i < len; i++) {\n if(s[i] === 'A') anum++\n if(anum > 1) return false\n if(s[i] === 'L') {\n if(i === 0) plidx = 0\n else if(s[i - 1] === 'L') {\n if(i - plidx + 1 > 2) return false\n } else {\n plidx = i\n }\n }\n }\n return true\n};" ]
552
student-attendance-record-ii
[]
/** * @param {number} n * @return {number} */ var checkRecord = function(n) { };
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: 'A': Absent. 'L': Late. 'P': Present. Any student is eligible for an attendance award if they meet both of the following criteria: The student was absent ('A') for strictly fewer than 2 days total. The student was never late ('L') for 3 or more consecutive days. Given an integer n, return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 109 + 7.   Example 1: Input: n = 2 Output: 8 Explanation: There are 8 records with length 2 that are eligible for an award: "PP", "AP", "PA", "LP", "PL", "AL", "LA", "LL" Only "AA" is not eligible because there are 2 absences (there need to be fewer than 2). Example 2: Input: n = 1 Output: 3 Example 3: Input: n = 10101 Output: 183236316   Constraints: 1 <= n <= 105
Hard
[ "dynamic-programming" ]
[ "const checkRecord = function(n) {\n let P = 1\n let L1 = 1\n let L2 = 0\n let A = 1\n let pureP = 1\n let pureL1 = 1\n let pureL2 = 0\n const mod = 10 ** 9 + 7\n\n for (let i = 2; i < n + 1; i++) {\n const newP = (P + L1 + L2 + A) % mod\n const newL1 = (P + A) % mod\n const newL2 = L1\n const newA = (pureP + pureL1 + pureL2) % mod\n P = newP\n L1 = newL1\n L2 = newL2\n A = newA\n const newPureP = (pureP + pureL1 + pureL2) % mod\n const newPureL1 = pureP\n const newPureL2 = pureL1\n pureP = newPureP\n pureL1 = newPureL1\n pureL2 = newPureL2\n }\n return (P + L1 + L2 + A) % (10 ** 9 + 7)\n}" ]
553
optimal-division
[]
/** * @param {number[]} nums * @return {string} */ var optimalDivision = function(nums) { };
You are given an integer array nums. The adjacent integers in nums will perform the float division. For example, for nums = [2,3,4], we will evaluate the expression "2/3/4". However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. Return the corresponding expression that has the maximum value in string format. Note: your expression should not contain redundant parenthesis.   Example 1: Input: nums = [1000,100,10,2] Output: "1000/(100/10/2)" Explanation: 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in "1000/((100/10)/2)" are redundant since they do not influence the operation priority. So you should return "1000/(100/10/2)". Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 Example 2: Input: nums = [2,3,4] Output: "2/(3/4)" Explanation: (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667   Constraints: 1 <= nums.length <= 10 2 <= nums[i] <= 1000 There is only one optimal division for the given input.
Medium
[ "array", "math", "dynamic-programming" ]
[ "const optimalDivision = function(nums) {\n const len = nums.length\n if(len <= 2) return len === 2 ? `${nums[0]}/${nums[1]}` : nums.join('')\n let res = `${nums[0]}/(${nums[1]}`\n for(let i = 2; i < len; i++) {\n res += `/${nums[i]}`\n }\n return res + ')'\n};" ]
554
brick-wall
[]
/** * @param {number[][]} wall * @return {number} */ var leastBricks = function(wall) { };
There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same. Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line.   Example 1: Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] Output: 2 Example 2: Input: wall = [[1],[1],[1]] Output: 3   Constraints: n == wall.length 1 <= n <= 104 1 <= wall[i].length <= 104 1 <= sum(wall[i].length) <= 2 * 104 sum(wall[i]) is the same for each row i. 1 <= wall[i][j] <= 231 - 1
Medium
[ "array", "hash-table" ]
[ "const leastBricks = function(wall) {\n const hash = {};\n let row;\n let rowSum = 0;\n for (let i = 0; i < wall.length; i++) {\n rowSum = 0;\n row = wall[i];\n for (let j = 0; j < row.length - 1; j++) {\n rowSum += row[j];\n hash[rowSum] = hash.hasOwnProperty(rowSum) ? hash[rowSum] + 1 : 1;\n }\n }\n return (\n wall.length -\n (Object.keys(hash).length > 0\n ? Math.max(...Object.keys(hash).map(key => hash[key]))\n : 0)\n );\n};\n\nconsole.log(leastBricks([[1], [1], [1]]));" ]
556
next-greater-element-iii
[]
/** * @param {number} n * @return {number} */ var nextGreaterElement = function(n) { };
Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1. Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.   Example 1: Input: n = 12 Output: 21 Example 2: Input: n = 21 Output: -1   Constraints: 1 <= n <= 231 - 1
Medium
[ "math", "two-pointers", "string" ]
[ "const nextGreaterElement = function(n) {\n let i, j;\n const arr = (n + \"\").split(\"\").map(el => +el);\n for (i = arr.length - 2; i >= 0; i--) {\n if (arr[i] < arr[i + 1]) {\n break;\n }\n }\n if (i < 0) return -1;\n j = arr.length - 1;\n while (arr[j] <= arr[i]) {\n j--;\n }\n swap(arr, i, j);\n reverse(arr, i + 1, arr.length - 1);\n\n const res = arr.reduce((ac, el) => ac + el, \"\");\n return res > Math.pow(2, 31) - 1 ? -1 : +res\n};\n\nfunction swap(arr, i, j) {\n arr[i] ^= arr[j];\n arr[j] ^= arr[i];\n arr[i] ^= arr[j];\n}\n\nfunction reverse(arr, start, end) {\n let l = start;\n let h = end;\n while (l < h) {\n swap(arr, l++, h--);\n }\n}" ]
557
reverse-words-in-a-string-iii
[]
/** * @param {string} s * @return {string} */ var reverseWords = function(s) { };
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.   Example 1: Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Example 2: Input: s = "God Ding" Output: "doG gniD"   Constraints: 1 <= s.length <= 5 * 104 s contains printable ASCII characters. s does not contain any leading or trailing spaces. There is at least one word in s. All the words in s are separated by a single space.
Easy
[ "two-pointers", "string" ]
null
[]
558
logical-or-of-two-binary-grids-represented-as-quad-trees
[]
/** * // Definition for a QuadTree node. * function Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) { * this.val = val; * this.isLeaf = isLeaf; * this.topLeft = topLeft; * this.topRight = topRight; * this.bottomLeft = bottomLeft; * this.bottomRight = bottomRight; * }; */ /** * @param {Node} quadTree1 * @param {Node} quadTree2 * @return {Node} */ var intersect = function(quadTree1, quadTree2) { };
A Binary Matrix is a matrix in which all the elements are either 0 or 1. Given quadTree1 and quadTree2. quadTree1 represents a n * n binary matrix and quadTree2 represents another n * n binary matrix. Return a Quad-Tree representing the n * n binary matrix which is the result of logical bitwise OR of the two binary matrixes represented by quadTree1 and quadTree2. Notice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: val: True if the node represents a grid of 1's or False if the node represents a grid of 0's. isLeaf: True if the node is leaf node on the tree or False if the node has the four children. class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; } We can construct a Quad-Tree from a two-dimensional area using the following steps: If the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop. If the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo. Recurse for each of the children with the proper sub-grid. If you want to know more about the Quad-Tree, you can refer to the wiki. Quad-Tree format: The input/output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val]. If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.   Example 1: Input: quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,0]] , quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]] Output: [[0,0],[1,1],[1,1],[1,1],[1,0]] Explanation: quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree. If we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree. Notice that the binary matrices shown are only for illustration, you don't have to construct the binary matrix to get the result tree. Example 2: Input: quadTree1 = [[1,0]], quadTree2 = [[1,0]] Output: [[1,0]] Explanation: Each tree represents a binary matrix of size 1*1. Each matrix contains only zero. The resulting matrix is of size 1*1 with also zero.   Constraints: quadTree1 and quadTree2 are both valid Quad-Trees each representing a n * n grid. n == 2x where 0 <= x <= 9.
Medium
[ "divide-and-conquer", "tree" ]
/** * // Definition for a QuadTree node. * function Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) { * this.val = val; * this.isLeaf = isLeaf; * this.topLeft = topLeft; * this.topRight = topRight; * this.bottomLeft = bottomLeft; * this.bottomRight = bottomRight; * }; */
[ "const intersect = function (quadTree1, quadTree2) {\n if (quadTree1.isLeaf) {\n return quadTree1.val ? quadTree1 : quadTree2;\n }\n\n if (quadTree2.isLeaf) {\n return quadTree2.val ? quadTree2 : quadTree1;\n }\n\n const topLeft = intersect(quadTree1.topLeft, quadTree2.topLeft);\n const topRight = intersect(quadTree1.topRight, quadTree2.topRight);\n const bottomLeft = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft);\n const bottomRight = intersect(quadTree1.bottomRight, quadTree2.bottomRight);\n\n if (\n topLeft.isLeaf &&\n topRight.isLeaf &&\n bottomLeft.isLeaf &&\n bottomRight.isLeaf &&\n topLeft.val == topRight.val &&\n topRight.val == bottomLeft.val &&\n bottomLeft.val == bottomRight.val\n ) {\n return new Node(topLeft.val, true, null, null, null, null);\n } else {\n return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight);\n }\n};" ]
559
maximum-depth-of-n-ary-tree
[]
/** * // Definition for a Node. * function Node(val,children) { * this.val = val; * this.children = children; * }; */ /** * @param {Node|null} root * @return {number} */ var maxDepth = function(root) { };
Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).   Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: 3 Example 2: Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: 5   Constraints: The total number of nodes is in the range [0, 104]. The depth of the n-ary tree is less than or equal to 1000.
Easy
[ "tree", "depth-first-search", "breadth-first-search" ]
/** * // Definition for a Node. * function Node(val,children) { * this.val = val; * this.children = children; * }; */
[ "const maxDepth = function(root) {\n let max = 0\n if(root == null) return 0\n function dfs(node, depth) {\n if(node == null || node.children.length === 0) {\n depth++\n if(depth > max) max = depth\n return\n }\n depth++\n for(let n of node.children) {\n dfs(n, depth)\n }\n }\n dfs(root, 0)\n return max\n};" ]
560
subarray-sum-equals-k
[ "Will Brute force work here? Try to optimize it.", "Can we optimize it by using some extra space?", "What about storing sum frequencies in a hash table? Will it be useful?", "sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1.\r\n\r\nCan we use this property to optimize it." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var subarraySum = function(nums, k) { };
Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,1,1], k = 2 Output: 2 Example 2: Input: nums = [1,2,3], k = 3 Output: 2   Constraints: 1 <= nums.length <= 2 * 104 -1000 <= nums[i] <= 1000 -107 <= k <= 107
Medium
[ "array", "hash-table", "prefix-sum" ]
[ "const subarraySum = function(nums, k) {\n let totalNum = 0\n const map = new Map()\n let cumulativeSum = 0\n map.set(0, 1)\n for (let i = 0, len = nums.length; i < len; i++) {\n cumulativeSum += nums[i]\n if (map.get(cumulativeSum - k)) {\n totalNum += map.get(cumulativeSum - k)\n }\n if (map.get(cumulativeSum)) {\n map.set(cumulativeSum, map.get(cumulativeSum) + 1)\n } else {\n map.set(cumulativeSum, 1)\n }\n }\n return totalNum\n}", "const subarraySum = function (nums, k) {\n const n = nums.length, hash = { 0: 1 }\n let pre = 0\n let res = 0\n for (let i = 0; i < n; i++) {\n const cur = pre + nums[i]\n if (hash[cur - k] != null) res += hash[cur - k]\n hash[cur] = (hash[cur] || 0) + 1\n pre = cur\n }\n return res\n}" ]
561
array-partition
[ "Obviously, brute force won't help here. Think of something else, take some example like 1,2,3,4.", "How will you make pairs to get the result? There must be some pattern.", "Did you observe that- Minimum element gets add into the result in sacrifice of maximum element.", "Still won't able to find pairs? Sort the array and try to find the pattern." ]
/** * @param {number[]} nums * @return {number} */ var arrayPairSum = function(nums) { };
Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.   Example 1: Input: nums = [1,4,3,2] Output: 4 Explanation: All possible pairings (ignoring the ordering of elements) are: 1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3 2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3 3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4 So the maximum possible sum is 4. Example 2: Input: nums = [6,2,6,5,1,2] Output: 9 Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.   Constraints: 1 <= n <= 104 nums.length == 2 * n -104 <= nums[i] <= 104
Easy
[ "array", "greedy", "sorting", "counting-sort" ]
null
[]
563
binary-tree-tilt
[ "Don't think too much, this is an easy problem. Take some small tree as an example.", "Can a parent node use the values of its child nodes? How will you implement it?", "May be recursion and tree traversal can help you in implementing.", "What about postorder traversal, using values of left and right childs?" ]
/** * 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 findTilt = function(root) { };
Given the root of a binary tree, return the sum of every tree node's tilt. The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child.   Example 1: Input: root = [1,2,3] Output: 1 Explanation: Tilt of node 2 : |0-0| = 0 (no children) Tilt of node 3 : |0-0| = 0 (no children) Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3) Sum of every tilt : 0 + 0 + 1 = 1 Example 2: Input: root = [4,2,9,3,5,null,7] Output: 15 Explanation: Tilt of node 3 : |0-0| = 0 (no children) Tilt of node 5 : |0-0| = 0 (no children) Tilt of node 7 : |0-0| = 0 (no children) Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5) Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7) Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16) Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15 Example 3: Input: root = [21,7,14,1,1,2,2,3,3] Output: 9   Constraints: The number of nodes in the tree is in the range [0, 104]. -1000 <= Node.val <= 1000
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 findTilt = function(root) {\n const tilt = { val: 0 }\n dfs(root, tilt)\n function dfs(root, tilt) {\n if (!root) return 0\n let left = dfs(root.left, tilt)\n let right = dfs(root.right, tilt)\n tilt.val += Math.abs(left - right)\n return root.val + left + right\n }\n return tilt.val\n}" ]
564
find-the-closest-palindrome
[ "Will brute force work for this problem? Think of something else.", "Take some examples like 1234, 999,1000, etc and check their closest palindromes. How many different cases are possible?", "Do we have to consider only left half or right half of the string or both?", "Try to find the closest palindrome of these numbers- 12932, 99800, 12120. Did you observe something?" ]
/** * @param {string} n * @return {string} */ var nearestPalindromic = function(n) { };
Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one. The closest is defined as the absolute difference minimized between two integers.   Example 1: Input: n = "123" Output: "121" Example 2: Input: n = "1" Output: "0" Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.   Constraints: 1 <= n.length <= 18 n consists of only digits. n does not have leading zeros. n is representing an integer in the range [1, 1018 - 1].
Hard
[ "math", "string" ]
[ "const nearestPalindromic = function(n) {\n let bigInt = null\n\n if (typeof n === 'bigint') bigInt = n\n if (typeof n === 'string') bigInt = BigInt(n)\n if (typeof n == null) throw new Error('unknown input type')\n\n // take the number, keep adding 1 to it, then check if it's a palindrome\n const prevPalindrome = getPrevPalindrome(bigInt)\n const nextPalindrome = getNextPalindrome(bigInt)\n\n const scalarPrev = bigInt - prevPalindrome\n const scalarNext = nextPalindrome - bigInt\n\n if (scalarPrev <= scalarNext) return prevPalindrome.toString()\n else return nextPalindrome.toString()\n}\n\n\nfunction getPrevPalindrome(number) {\n const decrementedNumber =\n typeof number === 'bigint' ? number - BigInt(1) : BigInt(number) - BigInt(1)\n\n if (decrementedNumber.toString().length === 1) return decrementedNumber\n\n const leftSide = getLeftSideNumber(decrementedNumber)\n const palindromedLeft = getPalindromeAsString(leftSide)\n\n const rightSide = getRightSideNumberAsString(decrementedNumber)\n const comparison = compareTwoValues(BigInt(palindromedLeft), BigInt(rightSide))\n if (comparison === 0) {\n // the right side is already the palindromedLeft - return the incrementedNumber\n return decrementedNumber\n }\n if (comparison === 1) {\n // this means the right side is already too far advanced (going downwards) compared to the palindromedLeft,\n // you need to take the leftSideWithBorder, decrement by 1, then return this new number concatenated with\n // the leftSide's palindrome - this is the answer\n const leftWithBorder = getLeftSideNumberWithBorder(decrementedNumber)\n const decremented = leftWithBorder - BigInt(1)\n\n if (decremented === BigInt(0)) return BigInt(9)\n\n const newWhole = BigInt(decremented.toString() + getRightSideNumberAsString(decrementedNumber))\n\n const newLeft = getLeftSideNumber(newWhole)\n const palindromedNewLeft = getPalindromeAsString(newLeft)\n return BigInt(decremented.toString() + palindromedNewLeft.toString())\n }\n if (comparison === -1) {\n // this means the right side can naturally increment to the palindromedLeft,\n // so you can just return the leftSideWithBorder concatenated with the palindromedLeft\n const leftSideWithBorder = getLeftSideNumberWithBorder(decrementedNumber)\n return BigInt(leftSideWithBorder.toString() + palindromedLeft)\n }\n}\n\n\nfunction getNextPalindrome(number) {\n const incrementedNumber =\n typeof number === 'bigint' ? number + BigInt(1) : BigInt(number) + BigInt(1)\n\n if (incrementedNumber.toString().length === 1) return incrementedNumber\n\n const leftSide = getLeftSideNumber(incrementedNumber)\n const palindromedLeft = getPalindromeAsString(leftSide)\n\n const rightSide = getRightSideNumberAsString(incrementedNumber)\n const comparison = compareTwoValues(BigInt(palindromedLeft), BigInt(rightSide))\n if (comparison === 0) {\n // the right side is already the palindromedLeft - return the incrementedNumber\n return incrementedNumber\n }\n if (comparison === 1) {\n // this means the right side can naturally increment to the palindromedLeft,\n // so you can just return the leftSideWithBorder concatenated with the palindromedLeft\n const leftSideWithBorder = getLeftSideNumberWithBorder(incrementedNumber)\n const leftAsString = leftSideWithBorder.toString()\n const combined = leftAsString + palindromedLeft\n return BigInt(combined)\n }\n if (comparison === -1) {\n // this means the right side is already too far advanced compared to the palindromedLeft,\n // you need to take the leftSideWithBorder, increment by 1, then return this new number concatenated with\n // the leftSide's palindrome - this is the answer\n const leftWithBorder = getLeftSideNumberWithBorder(incrementedNumber)\n const incrementedLeftWithBorder = leftWithBorder + BigInt(1)\n const newWhole = BigInt(\n incrementedLeftWithBorder.toString() + getRightSideNumberAsString(incrementedNumber)\n )\n\n const newLeft = getLeftSideNumber(newWhole)\n const palindromedNewLeft = getPalindromeAsString(newLeft)\n return BigInt(incrementedLeftWithBorder.toString() + palindromedNewLeft.toString())\n }\n}\n\n\nfunction getLeftSideNumber(number) {\n const numberAsText = number.toString()\n const numCharsInLeftSide = Math.floor(numberAsText.length / 2)\n return BigInt(numberAsText.slice(0, numCharsInLeftSide))\n}\n\n\nfunction getLeftSideNumberWithBorder(number) {\n const numberAsText = number.toString()\n const hasOddNumChars = numberAsText.length % 2 === 1\n\n const left = getLeftSideNumber(number)\n\n // should return the left side only, if it's an even-digited number\n // else, return the left side together with the border number (since it's an odd-digited number)\n if (hasOddNumChars) {\n const middleChar = numberAsText.charAt(Math.floor(numberAsText.length / 2))\n return BigInt(left.toString() + middleChar)\n } else {\n return BigInt(left.toString())\n }\n}\n\n\nfunction getRightSideNumberAsString(number) {\n const numberAsText = number.toString()\n const numCharsInRightSide = Math.floor(numberAsText.length / 2)\n return numberAsText.slice(numberAsText.length - numCharsInRightSide)\n}\n\n\nfunction getPalindromeAsString(number) {\n const numberAsText = number.toString()\n return numberAsText\n .split('')\n .reverse()\n .join('')\n}\n\n\nfunction compareTwoValues(number1, number2) {\n if (number1 < number2) return -1\n if (number1 === number2) return 0\n if (number1 > number2) return 1\n}" ]
565
array-nesting
[]
/** * @param {number[]} nums * @return {number} */ var arrayNesting = function(nums) { };
You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1]. You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: The first element in s[k] starts with the selection of the element nums[k] of index = k. The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on. We stop adding right before a duplicate element occurs in s[k]. Return the longest length of a set s[k].   Example 1: Input: nums = [5,4,0,3,1,6,2] Output: 4 Explanation: nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2. One of the longest sets s[k]: s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0} Example 2: Input: nums = [0,1,2] Output: 1   Constraints: 1 <= nums.length <= 105 0 <= nums[i] < nums.length All the values of nums are unique.
Medium
[ "array", "depth-first-search" ]
[ "const arrayNesting = function(nums) {\n let res = 0;\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] !== Number.MAX_SAFE_INTEGER) {\n let start = nums[i],\n count = 0;\n while (nums[start] !== Number.MAX_SAFE_INTEGER) {\n let temp = start;\n start = nums[start];\n count++;\n nums[temp] = Number.MAX_SAFE_INTEGER;\n }\n res = Math.max(res, count);\n }\n }\n return res;\n};" ]
566
reshape-the-matrix
[ "Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one.", "M[i][j]=M[n*i+j] , where n is the number of cols. \r\nThis is the one way of converting 2-d indices into one 1-d index. \r\nNow, how will you convert 1-d index into 2-d indices?", "Try to use division and modulus to convert 1-d index into 2-d indices.", "M[i] => M[i/n][i%n] Will it result in right mapping? Take some example and check this formula." ]
/** * @param {number[][]} mat * @param {number} r * @param {number} c * @return {number[][]} */ var matrixReshape = function(mat, r, c) { };
In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data. You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix. The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.   Example 1: Input: mat = [[1,2],[3,4]], r = 1, c = 4 Output: [[1,2,3,4]] Example 2: Input: mat = [[1,2],[3,4]], r = 2, c = 4 Output: [[1,2],[3,4]]   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 100 -1000 <= mat[i][j] <= 1000 1 <= r, c <= 300
Easy
[ "array", "matrix", "simulation" ]
[ "const matrixReshape = function(nums, r, c) {\n if (isValid(nums, r, c) === false) {\n return nums;\n }\n const arr = [];\n nums.forEach(el => arr.push(...el));\n const res = [];\n for (let start = 0; start < arr.length; start = start + c) {\n res.push(arr.slice(start, start + c));\n }\n return res;\n};\n\nfunction isValid(matrix, r, c) {\n if (matrix.length * matrix[0].length !== r * c) {\n return false;\n } else {\n return true;\n }\n}\n\nconsole.log(matrixReshape([[1, 2], [3, 4]], 1, 4));\nconsole.log(matrixReshape([[1, 2], [3, 4]], 2, 4));" ]
567
permutation-in-string
[ "Obviously, brute force will result in TLE. Think of something else.", "How will you check whether one string is a permutation of another string?", "One way is to sort the string and then compare. But, Is there a better way?", "If one string is a permutation of another string then they must one common metric. What is that?", "Both strings must have same character frequencies, if one is permutation of another. Which data structure should be used to store frequencies?", "What about hash table? An array of size 26?" ]
/** * @param {string} s1 * @param {string} s2 * @return {boolean} */ var checkInclusion = function(s1, s2) { };
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is the substring of s2.   Example 1: Input: s1 = "ab", s2 = "eidbaooo" Output: true Explanation: s2 contains one permutation of s1 ("ba"). Example 2: Input: s1 = "ab", s2 = "eidboaoo" Output: false   Constraints: 1 <= s1.length, s2.length <= 104 s1 and s2 consist of lowercase English letters.
Medium
[ "hash-table", "two-pointers", "string", "sliding-window" ]
[ "const checkInclusion = function(s1, s2) {\n if(s1.length > s2.length) return false\n const s1map = new Array(26).fill(0)\n const s2map = new Array(26).fill(0)\n const aCode = ('a').charCodeAt(0)\n const zCode = ('z').charCodeAt(0)\n \n for(let i = 0; i < s1.length; i++) {\n s1map[s1.charCodeAt(i) - aCode]++\n s2map[s2.charCodeAt(i) - aCode]++\n }\n \n for(let i = 0; i < s2.length - s1.length; i++) {\n if(matches(s1map, s2map)) return true\n s2map[s2.charCodeAt(i + s1.length) - aCode]++\n s2map[s2.charCodeAt(i) - aCode]--\n }\n \n return matches(s1map, s2map)\n \n};\n\nfunction matches(s1map, s2map) {\n for(let i = 0; i < 26; i++) {\n if(s1map[i] !== s2map[i]) return false\n }\n return true\n}", "const checkInclusion = function(s1, s2) {\n const arr = Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n const s1l = s1.length\n for(let c of s1) arr[c.charCodeAt(0) - a] += 1\n for(let i = 0, len = s2.length; i < len; i++) {\n const tmp = s2[i]\n arr[tmp.charCodeAt(0) - a]--\n if(i >= s1l - 1) {\n if(allZeros(arr)) return true\n arr[s2.charCodeAt(i - s1l + 1) - a]++\n }\n \n }\n \n return false\n};\n\nfunction allZeros(arr) {\n for(let e of arr) {\n if(e !== 0) return false\n }\n return true\n}" ]
572
subtree-of-another-tree
[ "Which approach is better here- recursive or iterative?", "If recursive approach is better, can you write recursive function with its parameters?", "Two trees <b>s</b> and <b>t</b> are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae?", "Recursive formulae can be: \r\nisIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)" ]
/** * 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 {TreeNode} subRoot * @return {boolean} */ var isSubtree = function(root, subRoot) { };
Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.   Example 1: Input: root = [3,4,5,1,2], subRoot = [4,1,2] Output: true Example 2: Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] Output: false   Constraints: The number of nodes in the root tree is in the range [1, 2000]. The number of nodes in the subRoot tree is in the range [1, 1000]. -104 <= root.val <= 104 -104 <= subRoot.val <= 104
Easy
[ "tree", "depth-first-search", "string-matching", "binary-tree", "hash-function" ]
/** * 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 isSubtree = function(s, t) {\n if (s == null) return false \n if (isSame(s, t)) return true\n return isSubtree(s.left, t) || isSubtree(s.right, t) \n};\n\nfunction isSame(s, t) {\n if (s == null && t == null) return true\n if (s == null || t == null) return false\n if (s.val !== t.val) return false\n return isSame(s.left, t.left) && isSame(s.right, t.right)\n}" ]
575
distribute-candies
[ "To maximize the number of kinds of candies, we should try to distribute candies such that sister will gain all kinds.", "What is the upper limit of the number of kinds of candies sister will gain? Remember candies are to distributed equally.", "Which data structure is the most suitable for finding the number of kinds of candies?", "Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit." ]
/** * @param {number[]} candyType * @return {number} */ var distributeCandies = function(candyType) { };
Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them.   Example 1: Input: candyType = [1,1,2,2,3,3] Output: 3 Explanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type. Example 2: Input: candyType = [1,1,2,3] Output: 2 Explanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types. Example 3: Input: candyType = [6,6,6,6] Output: 1 Explanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.   Constraints: n == candyType.length 2 <= n <= 104 n is even. -105 <= candyType[i] <= 105
Easy
[ "array", "hash-table" ]
[ "const distributeCandies = function(candies) {\n const uniqNum = candies.filter((el, idx, arr) => arr.indexOf(el) === idx)\n .length;\n const halfNum = candies.length / 2;\n return halfNum > uniqNum ? uniqNum : halfNum;\n};\n\nconsole.log(distributeCandies([1, 1, 2, 2, 3, 3]));\nconsole.log(distributeCandies([1, 1, 2, 3]));" ]
576
out-of-boundary-paths
[ "Is traversing every path feasible? There are many possible paths for a small matrix. Try to optimize it.", "Can we use some space to store the number of paths and update them after every move?", "One obvious thing: the ball will go out of the boundary only by crossing it. Also, there is only one possible way the ball can go out of the boundary from the boundary cell except for corner cells. From the corner cell, the ball can go out in two different ways.\r\n\r\nCan you use this thing to solve the problem?" ]
/** * @param {number} m * @param {number} n * @param {number} maxMove * @param {number} startRow * @param {number} startColumn * @return {number} */ var findPaths = function(m, n, maxMove, startRow, startColumn) { };
There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball. Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.   Example 1: Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 Output: 6 Example 2: Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 Output: 12   Constraints: 1 <= m, n <= 50 0 <= maxMove <= 50 0 <= startRow < m 0 <= startColumn < n
Medium
[ "dynamic-programming" ]
[ "const findPaths = function (m, n, N, i, j) {\n const dp = [...Array(2)].map((_) =>\n [...Array(50)].map((_) => Array(50).fill(0))\n )\n while (N-- > 0) {\n for (let i = 0; i < m; i++) {\n for (let j = 0, nc = (N + 1) % 2, np = N % 2; j < n; j++) {\n dp[nc][i][j] =\n ((i === 0 ? 1 : dp[np][i - 1][j]) +\n (i === m - 1 ? 1 : dp[np][i + 1][j]) +\n (j === 0 ? 1 : dp[np][i][j - 1]) +\n (j === n - 1 ? 1 : dp[np][i][j + 1])) %\n 1000000007\n }\n }\n }\n return dp[1][i][j]\n}", "const findPaths = function (m, n, N, i, j) {\n if (N <= 0) return 0;\n const MOD = 1000000007;\n let count = Array.from({ length: m }, () => new Array(n).fill(0));\n count[i][j] = 1;\n let result = 0;\n const dirs = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ];\n for (let step = 0; step < N; step++) {\n const temp = Array.from({ length: m }, () => new Array(n).fill(0));\n for (let r = 0; r < m; r++) {\n for (let c = 0; c < n; c++) {\n for (let d of dirs) {\n const nr = r + d[0];\n const nc = c + d[1];\n if (nr < 0 || nr >= m || nc < 0 || nc >= n) {\n result = (result + count[r][c]) % MOD;\n } else {\n temp[nr][nc] = (temp[nr][nc] + count[r][c]) % MOD;\n }\n }\n }\n }\n count = temp;\n }\n return result;\n};", "const findPaths = function (m, n, N, i, j, memo = new Map()) {\n const key = N + ',' + i + ',' + j;\n if (memo.has(key)) return memo.get(key);\n const isOutside = i === -1 || i === m || j === -1 || j === n;\n if (N === 0 || isOutside) return +isOutside;\n memo.set(key, (\n findPaths(m, n, N - 1, i - 1, j, memo)\n + findPaths(m, n, N - 1, i + 1, j, memo)\n + findPaths(m, n, N - 1, i, j + 1, memo)\n + findPaths(m, n, N - 1, i, j - 1, memo)\n ) % 1000000007);\n return memo.get(key);\n}" ]
581
shortest-unsorted-continuous-subarray
[]
/** * @param {number[]} nums * @return {number} */ var findUnsortedSubarray = function(nums) { };
Given an integer array nums, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order. Return the shortest such subarray and output its length.   Example 1: Input: nums = [2,6,4,8,10,9,15] Output: 5 Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. Example 2: Input: nums = [1,2,3,4] Output: 0 Example 3: Input: nums = [1] Output: 0   Constraints: 1 <= nums.length <= 104 -105 <= nums[i] <= 105   Follow up: Can you solve it in O(n) time complexity?
Medium
[ "array", "two-pointers", "stack", "greedy", "sorting", "monotonic-stack" ]
[ "const findUnsortedSubarray = function(nums) {\n let stack = []\n let left = nums.length\n let right = 0\n for(let i = 0; i < nums.length; i++) {\n while(stack.length > 0 && nums[stack[stack.length - 1]] > nums[i]) {\n left = Math.min(left, stack.pop())\n }\n stack.push(i)\n }\n stack = []\n for(let i = nums.length - 1; i >= 0; i--) {\n while(stack.length > 0 && nums[stack[stack.length - 1]] < nums[i] ) {\n right = Math.max(right, stack.pop())\n }\n stack.push(i)\n }\n \n \n return right > left ? right - left + 1: 0\n};" ]
583
delete-operation-for-two-strings
[]
/** * @param {string} word1 * @param {string} word2 * @return {number} */ var minDistance = function(word1, word2) { };
Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. In one step, you can delete exactly one character in either string.   Example 1: Input: word1 = "sea", word2 = "eat" Output: 2 Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea". Example 2: Input: word1 = "leetcode", word2 = "etco" Output: 4   Constraints: 1 <= word1.length, word2.length <= 500 word1 and word2 consist of only lowercase English letters.
Medium
[ "string", "dynamic-programming" ]
[ "const minDistance = function (word1, word2, memo = new Map()) {\n if (word1 === word2) return 0\n if (word1 === '' || word2 === '') return Math.max(word1.length, word2.length)\n const len1 = word1.length\n const len2 = word2.length\n if (memo.has(`${word1}-${word2}`)) return memo.get(`${word1}-${word2}`)\n let res\n if (word1[len1 - 1] === word2[len2 - 1]) {\n res = minDistance(word1.slice(0, len1 - 1), word2.slice(0, len2 - 1), memo)\n } else {\n res =\n 1 +\n Math.min(\n minDistance(word1.slice(0, len1 - 1), word2, memo),\n minDistance(word1, word2.slice(0, len2 - 1), memo)\n )\n }\n memo.set(`${word1}-${word2}`, res)\n return res\n}", "const minDistance = function (word1, word2) {\n const len1 = word1.length\n const len2 = word2.length\n const dp = Array.from({ length: len1 + 1 }, () => new Array(len2 + 1).fill(0))\n for(let i = 1; i <= len1; i++) {\n for(let j = 1; j<= len2; j++) {\n if(word1[i - 1] === word2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1\n else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])\n }\n }\n return len1 + len2 - dp[len1][len2] * 2\n}", "const minDistance = function (word1, word2) {\n const len1 = word1.length\n const len2 = word2.length\n const dp = Array.from({ length: len1 + 1 }, () => new Array(len2 + 1).fill(0))\n for(let i = 1; i <= len2; i++) {\n dp[0][i] = i\n }\n for(let j = 1; j <= len1; j++) {\n dp[j][0] = j\n }\n for(let i = 1; i <= len1; i++) {\n for(let j = 1; j<= len2; j++) {\n if(word1[i - 1] === word2[j - 1]) dp[i][j] = dp[i - 1][j - 1]\n else dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1\n }\n }\n return dp[len1][len2]\n}" ]
587
erect-the-fence
[]
/** * @param {number[][]} trees * @return {number[][]} */ var outerTrees = function(trees) { };
You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden. Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if all the trees are enclosed. Return the coordinates of trees that are exactly located on the fence perimeter. You may return the answer in any order.   Example 1: Input: trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] Output: [[1,1],[2,0],[4,2],[3,3],[2,4]] Explanation: All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence. Example 2: Input: trees = [[1,2],[2,2],[4,2]] Output: [[4,2],[2,2],[1,2]] Explanation: The fence forms a line that passes through all the trees.   Constraints: 1 <= trees.length <= 3000 trees[i].length == 2 0 <= xi, yi <= 100 All the given positions are unique.
Hard
[ "array", "math", "geometry" ]
[ "const outerTrees = function (points) {\n const orientation = (p1, p2, p3) => {\n return (p2[1] - p1[1]) * (p3[0] - p2[0]) - (p2[0] - p1[0]) * (p3[1] - p2[1])\n }\n points.sort((a, b) => {\n return a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]\n })\n const stack = []\n for (let i = 0; i < points.length; i++) {\n while (\n stack.length >= 2 &&\n orientation(stack[stack.length - 2], stack[stack.length - 1], points[i]) >\n 0\n )\n stack.pop()\n stack.push(points[i])\n }\n stack.pop()\n for (let i = points.length - 1; i >= 0; i--) {\n while (\n stack.length >= 2 &&\n orientation(stack[stack.length - 2], stack[stack.length - 1], points[i]) >\n 0\n )\n stack.pop()\n stack.push(points[i])\n }\n return [...new Set(stack)]\n}" ]
589
n-ary-tree-preorder-traversal
[]
/** * // Definition for a Node. * function Node(val, children) { * this.val = val; * this.children = children; * }; */ /** * @param {Node|null} root * @return {number[]} */ var preorder = function(root) { };
Given the root of an n-ary tree, return the preorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)   Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [1,3,5,6,2,4] Example 2: Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]   Constraints: The number of nodes in the tree is in the range [0, 104]. 0 <= Node.val <= 104 The height of the n-ary tree is less than or equal to 1000.   Follow up: Recursive solution is trivial, could you do it iteratively?
Easy
[ "stack", "tree", "depth-first-search" ]
/** * // Definition for a Node. * function Node(val, children) { * this.val = val; * this.children = children; * }; */
[ "const preorder = function(root) {\n const arr = []\n traverse(root, arr)\n return arr\n};\n\nfunction traverse(node, arr) {\n if(node === null) return\n arr.push(node.val)\n for(let i = 0; i < node.children.length; i++) {\n traverse(node.children[i], arr)\n }\n}" ]
590
n-ary-tree-postorder-traversal
[]
/** * // Definition for a Node. * function Node(val,children) { * this.val = val; * this.children = children; * }; */ /** * @param {Node|null} root * @return {number[]} */ var postorder = function(root) { };
Given the root of an n-ary tree, return the postorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)   Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [5,6,3,2,4,1] Example 2: Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]   Constraints: The number of nodes in the tree is in the range [0, 104]. 0 <= Node.val <= 104 The height of the n-ary tree is less than or equal to 1000.   Follow up: Recursive solution is trivial, could you do it iteratively?
Easy
[ "stack", "tree", "depth-first-search" ]
/** * // Definition for a Node. * function Node(val,children) { * this.val = val; * this.children = children; * }; */
[ "const postorder = function(root) {\n const res = []\n traverse(root, res)\n return res\n};\n\nfunction traverse(node, res) {\n if(node == null) return\n for(let i = 0; i < node.children.length; i++) {\n traverse(node.children[i], res)\n }\n res.push(node.val)\n}" ]
591
tag-validator
[]
/** * @param {string} code * @return {boolean} */ var isValid = function(code) { };
Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: The code must be wrapped in a valid closed tag. Otherwise, the code is invalid. A closed tag (not necessarily valid) has exactly the following format : <TAG_NAME>TAG_CONTENT</TAG_NAME>. Among them, <TAG_NAME> is the start tag, and </TAG_NAME> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid. A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid. A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid. A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. A < is unmatched if you cannot find a subsequent >. And when you find a < or </, all the subsequent characters until the next > should be parsed as TAG_NAME (not necessarily valid). The cdata has the following format : <![CDATA[CDATA_CONTENT]]>. The range of CDATA_CONTENT is defined as the characters between <![CDATA[ and the first subsequent ]]>. CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.   Example 1: Input: code = "<DIV>This is the first line <![CDATA[<div>]]></DIV>" Output: true Explanation: The code is wrapped in a closed tag : <DIV> and </DIV>. The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. Example 2: Input: code = "<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>" Output: true Explanation: We first separate the code into : start_tag|tag_content|end_tag. start_tag -> "<DIV>" end_tag -> "</DIV>" tag_content could also be separated into : text1|cdata|text2. text1 -> ">> ![cdata[]] " cdata -> "<![CDATA[<div>]>]]>", where the CDATA_CONTENT is "<div>]>" text2 -> "]]>>]" The reason why start_tag is NOT "<DIV>>>" is because of the rule 6. The reason why cdata is NOT "<![CDATA[<div>]>]]>]]>" is because of the rule 7. Example 3: Input: code = "<A> <B> </A> </B>" Output: false Explanation: Unbalanced. If "<A>" is closed, then "<B>" must be unmatched, and vice versa.   Constraints: 1 <= code.length <= 500 code consists of English letters, digits, '<', '>', '/', '!', '[', ']', '.', and ' '.
Hard
[ "string", "stack" ]
[ "const isValid = function (code) {\n const stack = []\n const [A, Z] = ['A', 'Z'].map((e) => e.charCodeAt(0))\n for (let i = 0; i < code.length; ) {\n if (i > 0 && stack.length === 0) return false\n if (code.startsWith('<![CDATA[', i)) {\n let j = i + 9\n i = code.indexOf(']]>', j)\n if (i < 0) return false\n i += 3\n } else if (code.startsWith('</', i)) {\n let j = i + 2\n i = code.indexOf('>', j)\n if (i < 0 || i === j || i - j > 9) return false\n for (let k = j; k < i; k++) {\n if (\n code.charAt(k) !== code[k].toUpperCase() ||\n !(code.charCodeAt(k) >= A && code.charCodeAt(k) <= Z)\n )\n return false\n }\n let s = code.slice(j, i++)\n if (stack.length === 0 || stack.pop() !== s) return false\n } else if (code.startsWith('<', i)) {\n let j = i + 1\n i = code.indexOf('>', j)\n if (i < 0 || i === j || i - j > 9) return false\n for (let k = j; k < i; k++) {\n if (\n code.charAt(k) !== code[k].toUpperCase() ||\n !(code.charCodeAt(k) >= A && code.charCodeAt(k) <= Z)\n )\n return false\n }\n let s = code.slice(j, i++)\n stack.push(s)\n } else {\n i++\n }\n }\n return stack.length === 0\n}", "const isValid = function (code) {\n code = code.replace(/<!\\[CDATA\\[.*?\\]\\]>|t/g, '-')\n let prev\n while (code !== prev) {\n prev = code\n code = code.replace(/<([A-Z]{1,9})>[^<]*<\\/\\1>/g, 't')\n }\n return code === 't'\n}", "const isValid = function (code) {\n const STATES = {\n lt: 1, // <\n tagOrData: 2, // uppercase=tag, '!'=data\n tagName: 3, // uppercase, '>'=end\n dataContent: 4, // any, ']'=wait-for-end\n dataEnd: 5, // any, ']'=end\n tagContent: 6, // any, '<'=tag-or-data\n }\n class Validator {\n constructor(str) {\n this.state = STATES.lt\n this.str = str\n this.stack = []\n this.i = 0\n // this ensure it doesnt start with cdata\n this.isValid = this.isUpperCase(this.str[1])\n // check through code\n while (this.isValid && this.i < this.str.length) {\n this.isValid = this.validate()\n }\n // check if there is unclosed tags\n this.isValid = this.isValid && !this.stack.length\n }\n\n \n validate() {\n let char = this.str[this.i]\n switch (this.state) {\n // expect '<', only used at start\n case STATES.lt:\n this.i++\n if (char == '<') {\n this.state = STATES.tagOrData\n return true\n }\n return false\n // expect (end-)tag-name or cdata\n case STATES.tagOrData:\n // data\n if (char == '!') {\n this.i = this.findStrEnd(this.i + 1, '[CDATA[')\n if (this.i == -1) {\n return false\n }\n this.state = STATES.dataContent\n return true\n }\n // end tag\n if (char == '/') {\n let name = this.stack.pop()\n if (!name) {\n return false\n }\n this.i = this.findStrEnd(this.i + 1, name + '>')\n if (this.i == -1) {\n return false\n }\n if (!this.stack.length & (this.i < this.str.length)) {\n // more than one top level tags\n return false\n }\n this.state = STATES.tagContent\n return true\n }\n // tag name\n {\n let name = this.findTagName(this.i)\n if (!name) {\n return false\n }\n if (name.length > 9) {\n return false\n }\n this.i += name.length + 1\n this.stack.push(name)\n this.state = STATES.tagContent\n return true\n }\n case STATES.dataContent: // you can try replace these code with indexOf\n {\n let end = this.findStrEnd(this.i, ']]>')\n if (end != -1) {\n // found end\n this.i = end\n this.state = STATES.tagContent\n return true\n }\n // not yet\n this.i++\n return true\n }\n case STATES.tagContent:\n if (char == '<') {\n this.state = STATES.tagOrData\n this.i++\n return true\n }\n this.i++\n return true\n }\n }\n\n isUpperCase(char) {\n return /[A-Z]/.test(char)\n }\n\n findStrEnd(from, toFind = '') {\n let end = from + toFind.length\n for (let i = 0; i < toFind.length; i++) {\n if (toFind[i] != this.str[i + from]) return -1\n }\n return end\n }\n\n findTagName(from) {\n let tagName = ''\n for (let i = from; i < this.str.length; i++) {\n if (this.isUpperCase(this.str[i])) {\n tagName += this.str[i]\n continue\n }\n if (this.str[i] == '>') {\n return tagName\n }\n return ''\n }\n return ''\n }\n }\n let v = new Validator(code)\n return v.isValid\n}" ]
592
fraction-addition-and-subtraction
[]
/** * @param {string} expression * @return {string} */ var fractionAddition = function(expression) { };
Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.   Example 1: Input: expression = "-1/2+1/2" Output: "0/1" Example 2: Input: expression = "-1/2+1/2+1/3" Output: "1/3" Example 3: Input: expression = "1/3-1/2" Output: "-1/6"   Constraints: The input string only contains '0' to '9', '/', '+' and '-'. So does the output. Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted. The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above. The number of given fractions will be in the range [1, 10]. The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
Medium
[ "math", "string", "simulation" ]
[ "const fractionAddition = function (expression) {\n if (expression[0] === '-') expression = '0/1' + expression\n const terms = expression.split(/[+-]/g)\n const ops = '+' + expression.replace(/[^+-]/g, '')\n const nums = [],\n dens = []\n for (let term of terms) {\n let t = term.split('/')\n nums.push(parseInt(t[0]))\n dens.push(parseInt(t[1]))\n }\n const lcm = LCM(dens)\n const numSum = nums.reduce(\n (sum, num, i) => sum + ((+(ops[i] === '+') || -1) * num * lcm) / dens[i],\n 0\n )\n const gcd = Math.abs(GCD(numSum, lcm))\n return numSum / gcd + '/' + lcm / gcd\n}\n\nfunction LCM(arr) {\n let res = arr[0]\n for (let i = 1; i < arr.length; i++) {\n res = (arr[i] * res) / GCD(arr[i], res)\n }\n return res\n}\n\nfunction GCD(a, b) {\n if (b === 0) return a\n return GCD(b, a % b)\n}" ]
593
valid-square
[]
/** * @param {number[]} p1 * @param {number[]} p2 * @param {number[]} p3 * @param {number[]} p4 * @return {boolean} */ var validSquare = function(p1, p2, p3, p4) { };
Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square. The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order. A valid square has four equal sides with positive length and four equal angles (90-degree angles).   Example 1: Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] Output: true Example 2: Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12] Output: false Example 3: Input: p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1] Output: true   Constraints: p1.length == p2.length == p3.length == p4.length == 2 -104 <= xi, yi <= 104
Medium
[ "math", "geometry" ]
[ "const validSquare = function(p1, p2, p3, p4) {\n const lenArr = [\n distance(p1, p2),\n distance(p1, p3),\n distance(p1, p4),\n distance(p2, p3),\n distance(p2, p4),\n distance(p3, p4)\n ]\n const obj = {}\n for (let el of lenArr) {\n if (obj[el] != null) obj[el] += 1\n else obj[el] = 1\n }\n const keys = Object.keys(obj)\n\n return keys.length === 2 && (obj[keys[0]] === 2 || obj[keys[1]] === 2)\n}\n\nfunction distance(p1, p2) {\n return Math.sqrt(Math.pow(p1[1] - p2[1], 2) + Math.pow(p1[0] - p2[0], 2))\n}" ]
594
longest-harmonious-subsequence
[]
/** * @param {number[]} nums * @return {number} */ var findLHS = function(nums) { };
We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1. Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences. A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.   Example 1: Input: nums = [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3]. Example 2: Input: nums = [1,2,3,4] Output: 2 Example 3: Input: nums = [1,1,1,1] Output: 0   Constraints: 1 <= nums.length <= 2 * 104 -109 <= nums[i] <= 109
Easy
[ "array", "hash-table", "sorting" ]
[ "const findLHS = function(nums) {\n if(nums == null) return 0\n if(Object.prototype.toString.call(nums) === '[object Array]' && nums.length === 0) return 0\n let res = 0\n const map = {}\n for (let el of nums) {\n if(map.hasOwnProperty(el)) {\n map[el] += 1\n } else {\n map[el] = 1\n }\n }\n Object.keys(map).forEach(el => {\n if(map.hasOwnProperty(+el + 1)) {\n res = Math.max(res, map[el] + map[+el + 1])\n }\n })\n console.log(res)\n return res\n};" ]
598
range-addition-ii
[]
/** * @param {number} m * @param {number} n * @param {number[][]} ops * @return {number} */ var maxCount = function(m, n, ops) { };
You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi. Count and return the number of maximum integers in the matrix after performing all the operations.   Example 1: Input: m = 3, n = 3, ops = [[2,2],[3,3]] Output: 4 Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4. Example 2: Input: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] Output: 4 Example 3: Input: m = 3, n = 3, ops = [] Output: 9   Constraints: 1 <= m, n <= 4 * 104 0 <= ops.length <= 104 ops[i].length == 2 1 <= ai <= m 1 <= bi <= n
Easy
[ "array", "math" ]
[ "const maxCount = function (m, n, ops) {\n for (let i = 0, len = ops.length; i < len; i++) {\n if (ops[i][0] < m) m = ops[i][0]\n if (ops[i][1] < n) n = ops[i][1]\n }\n return m * n\n}" ]
599
minimum-index-sum-of-two-lists
[]
/** * @param {string[]} list1 * @param {string[]} list2 * @return {string[]} */ var findRestaurant = function(list1, list2) { };
Given two arrays of strings list1 and list2, find the common strings with the least index sum. A common string is a string that appeared in both list1 and list2. A common string with the least index sum is a common string such that if it appeared at list1[i] and list2[j] then i + j should be the minimum value among all the other common strings. Return all the common strings with the least index sum. Return the answer in any order.   Example 1: Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"] Output: ["Shogun"] Explanation: The only common string is "Shogun". Example 2: Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"] Output: ["Shogun"] Explanation: The common string with the least index sum is "Shogun" with index sum = (0 + 1) = 1. Example 3: Input: list1 = ["happy","sad","good"], list2 = ["sad","happy","good"] Output: ["sad","happy"] Explanation: There are three common strings: "happy" with index sum = (0 + 1) = 1. "sad" with index sum = (1 + 0) = 1. "good" with index sum = (2 + 2) = 4. The strings with the least index sum are "sad" and "happy".   Constraints: 1 <= list1.length, list2.length <= 1000 1 <= list1[i].length, list2[i].length <= 30 list1[i] and list2[i] consist of spaces ' ' and English letters. All the strings of list1 are unique. All the strings of list2 are unique. There is at least a common string between list1 and list2.
Easy
[ "array", "hash-table", "string" ]
[ "const findRestaurant = function(list1, list2) {\n const hash = {};\n for (let i = 0; i < list1.length; i++) {\n if (!hash.hasOwnProperty(list1[i])) {\n hash[list1[i]] = i;\n }\n }\n const resArr = [];\n for (let j = 0; j < list2.length; j++) {\n if (hash.hasOwnProperty(list2[j])) {\n resArr.push([list2[j], hash[list2[j]] + j]);\n }\n }\n const resHash = {};\n resArr.forEach(el => {\n if (resHash.hasOwnProperty(el[1])) {\n resHash[el[1]].push(el[0]);\n } else {\n resHash[el[1]] = [el[0]];\n }\n });\n resArr.sort((a, b) => a[1] - b[1]);\n return resHash[resArr[0][1]];\n};\n\nconsole.log(\n findRestaurant(\n [\"Shogun\", \"Tapioca Express\", \"Burger King\", \"KFC\"],\n [\"KFC\", \"Burger King\", \"Tapioca Express\", \"Shogun\"]\n )\n);" ]
600
non-negative-integers-without-consecutive-ones
[]
/** * @param {number} n * @return {number} */ var findIntegers = function(n) { };
Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.   Example 1: Input: n = 5 Output: 5 Explanation: Here are the non-negative integers <= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101 Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. Example 2: Input: n = 1 Output: 2 Example 3: Input: n = 2 Output: 3   Constraints: 1 <= n <= 109
Hard
[ "dynamic-programming" ]
[ "const findIntegers = function (num) {\n const binary = num.toString(2)\n const fibonacci = [1, 2]\n for (let i = 2; i < binary.length; ++i) {\n fibonacci.push(fibonacci[i - 2] + fibonacci[i - 1])\n }\n let answer = binary.indexOf('11') === -1 ? 1 : 0\n for (let i = 0; i < binary.length; ++i) {\n if (binary[i] === '1') {\n answer += fibonacci[binary.length - 1 - i]\n if (binary[i - 1] === '1') {\n break\n }\n }\n }\n return answer\n}" ]
605
can-place-flowers
[]
/** * @param {number[]} flowerbed * @param {number} n * @return {boolean} */ var canPlaceFlowers = function(flowerbed, n) { };
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.   Example 1: Input: flowerbed = [1,0,0,0,1], n = 1 Output: true Example 2: Input: flowerbed = [1,0,0,0,1], n = 2 Output: false   Constraints: 1 <= flowerbed.length <= 2 * 104 flowerbed[i] is 0 or 1. There are no two adjacent flowers in flowerbed. 0 <= n <= flowerbed.length
Easy
[ "array", "greedy" ]
[ "const canPlaceFlowers = function(flowerbed, n) {\n let count = 0\n const clone = flowerbed\n for(let i = 0; i < clone.length; i++) {\n if(clone[i] === 0) {\n if(i === 0 && (clone[i + 1] === 0 || clone[i+1] == null)){\n count++\n clone[i] = 1\n }\n if(i > 0 && i < clone.length - 1 && clone[i - 1] === 0 && clone[i + 1] === 0) {\n count++\n clone[i] = 1\n }\n if(i === clone.length - 1 && clone[i - 1] === 0 && clone[i] === 0) {\n count++\n clone[i] = 1\n }\n }\n }\n \n return count >= n ? true : false\n};" ]
606
construct-string-from-binary-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {string} */ var tree2str = function(root) { };
Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.   Example 1: Input: root = [1,2,3,4] Output: "1(2(4))(3)" Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)" Example 2: Input: root = [1,2,3,null,4] Output: "1(2()(4))(3)" Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.   Constraints: The number of nodes in the tree is in the range [1, 104]. -1000 <= Node.val <= 1000
Easy
[ "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 tree2str = function(t) {\n if (!t) return ''\n const left = tree2str(t.left)\n const right = tree2str(t.right)\n if (right) return `${t.val}(${left})(${right})`\n else if (left) return `${t.val}(${left})`\n else return `${t.val}`\n};" ]
609
find-duplicate-file-in-system
[]
/** * @param {string[]} paths * @return {string[][]} */ var findDuplicate = function(paths) { };
Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order. A group of duplicate files consists of at least two files that have the same content. A single directory info string in the input list has the following format: "root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)" It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory "root/d1/d2/.../dm". Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory. The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format: "directory_path/file_name.txt"   Example 1: Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"] Output: [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]] Example 2: Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"] Output: [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]]   Constraints: 1 <= paths.length <= 2 * 104 1 <= paths[i].length <= 3000 1 <= sum(paths[i].length) <= 5 * 105 paths[i] consist of English letters, digits, '/', '.', '(', ')', and ' '. You may assume no files or directories share the same name in the same directory. You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.   Follow up: Imagine you are given a real file system, how will you search files? DFS or BFS? If the file content is very large (GB level), how will you modify your solution? If you can only read the file by 1kb each time, how will you modify your solution? What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize? How to make sure the duplicated files you find are not false positive?
Medium
[ "array", "hash-table", "string" ]
[ "const findDuplicate = function (paths) {\n const map = {}\n for (let text of paths) {\n for (let i = 1, files = text.split(' '); i < files.length; i++) {\n const paren = files[i].indexOf('(')\n const content = files[i].substring(paren + 1, files[i].length - 1)\n map[content] = map[content] || []\n map[content].push(files[0] + '/' + files[i].substr(0, paren))\n }\n }\n return Object.values(map).filter((dups) => dups.length > 1)\n}" ]
611
valid-triangle-number
[]
/** * @param {number[]} nums * @return {number} */ var triangleNumber = function(nums) { };
Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.   Example 1: Input: nums = [2,2,3,4] Output: 3 Explanation: Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 Example 2: Input: nums = [4,2,3,4] Output: 4   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 1000
Medium
[ "array", "two-pointers", "binary-search", "greedy", "sorting" ]
[ "const triangleNumber = function(nums) {\n nums.sort((a, b) => a - b);\n let count = 0;\n let n = nums.length;\n for (let i = n - 1; i >= 2; i--) {\n let lo = 0;\n let mid = i - 1;\n while (lo < mid) {\n if (nums[lo] + nums[mid] > nums[i]) {\n count += mid - lo;\n mid -= 1;\n } else {\n lo += 1;\n }\n }\n }\n return count;\n};\n\nconsole.log(triangleNumber([2, 2, 3, 4]));" ]
617
merge-two-binary-trees
[]
/** * 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} root1 * @param {TreeNode} root2 * @return {TreeNode} */ var mergeTrees = function(root1, root2) { };
You are given two binary trees root1 and root2. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree. Return the merged tree. Note: The merging process must start from the root nodes of both trees.   Example 1: Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7] Output: [3,4,5,5,4,null,7] Example 2: Input: root1 = [1], root2 = [1,2] Output: [2,2]   Constraints: The number of nodes in both trees is in the range [0, 2000]. -104 <= Node.val <= 104
Easy
[ "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
null
[]
621
task-scheduler
[]
/** * @param {character[]} tasks * @param {number} n * @return {number} */ var leastInterval = function(tasks, n) { };
Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks. Return the least number of units of times that the CPU will take to finish all the given tasks.   Example 1: Input: tasks = ["A","A","A","B","B","B"], n = 2 Output: 8 Explanation: A -> B -> idle -> A -> B -> idle -> A -> B There is at least 2 units of time between any two same tasks. Example 2: Input: tasks = ["A","A","A","B","B","B"], n = 0 Output: 6 Explanation: On this case any permutation of size 6 would work since n = 0. ["A","A","A","B","B","B"] ["A","B","A","B","A","B"] ["B","B","B","A","A","A"] ... And so on. Example 3: Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2 Output: 16 Explanation: One possible solution is A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A   Constraints: 1 <= task.length <= 104 tasks[i] is upper-case English letter. The integer n is in the range [0, 100].
Medium
[ "array", "hash-table", "greedy", "sorting", "heap-priority-queue", "counting" ]
[ "const leastInterval = function (tasks, n) {\n const len = tasks.length\n const cnt = Array(26).fill(0)\n\n const A = 'A'.charCodeAt(0)\n let maxFreq = 0,\n maxFreqCnt = 0\n for (const ch of tasks) {\n const idx = ch.charCodeAt(0) - A\n cnt[idx]++\n if (maxFreq === cnt[idx]) {\n maxFreqCnt++\n } else if (maxFreq < cnt[idx]) {\n maxFreqCnt = 1\n maxFreq = cnt[idx]\n }\n }\n\n const slot = maxFreq - 1\n const numOfPerSlot = n - (maxFreqCnt - 1)\n const available = len - maxFreq * maxFreqCnt\n const idles = Math.max(0, slot * numOfPerSlot - available)\n return len + idles\n}", "const leastInterval = function(tasks, n) {\n const map = Array(26).fill(0);\n const ca = \"A\".charCodeAt(0);\n for (let c of tasks) map[c.charCodeAt(0) - ca]++;\n map.sort((a, b) => a - b);\n let max_val = map[25] - 1,\n idle_slots = max_val * n;\n for (let i = 24; i >= 0 && map[i] > 0; i--) {\n idle_slots -= Math.min(map[i], max_val);\n }\n return idle_slots > 0 ? idle_slots + tasks.length : tasks.length;\n};", "const leastInterval = function(tasks, n) {\n const hash = {};\n for(let task of tasks) {\n hash[task] = hash[task] + 1 || 1\n }\n let max = 0, count = 0;\n for(let el in hash) {\n if(hash[el] > max) {\n max = hash[el];\n count = 1\n } else if(hash[el] === max) {\n count++;\n }\n }\n return Math.max((max - 1) * (n + 1) + count, tasks.length)\n};", "const leastInterval = function(tasks, n) {\n let max = 0, maxCnt = 0\n const len = tasks.length, cnt = Array(26).fill(0), A = 'A'.charCodeAt(0)\n \n for(let ch of tasks) {\n const idx = ch.charCodeAt(0) - A\n cnt[idx]++\n if(max === cnt[idx]) maxCnt++\n else if(max < cnt[idx]) {\n max = cnt[idx]\n maxCnt = 1\n }\n }\n \n const maxSlots = max * maxCnt\n const avaiSlots = (max - 1) * (n - (maxCnt - 1))\n const rem = len - maxSlots\n const emptySlots = Math.max(0, avaiSlots - rem)\n \n return len + emptySlots\n};" ]
622
design-circular-queue
[]
/** * @param {number} k */ var MyCircularQueue = function(k) { }; /** * @param {number} value * @return {boolean} */ MyCircularQueue.prototype.enQueue = function(value) { }; /** * @return {boolean} */ MyCircularQueue.prototype.deQueue = function() { }; /** * @return {number} */ MyCircularQueue.prototype.Front = function() { }; /** * @return {number} */ MyCircularQueue.prototype.Rear = function() { }; /** * @return {boolean} */ MyCircularQueue.prototype.isEmpty = function() { }; /** * @return {boolean} */ MyCircularQueue.prototype.isFull = function() { }; /** * Your MyCircularQueue object will be instantiated and called as such: * var obj = new MyCircularQueue(k) * var param_1 = obj.enQueue(value) * var param_2 = obj.deQueue() * var param_3 = obj.Front() * var param_4 = obj.Rear() * var param_5 = obj.isEmpty() * var param_6 = obj.isFull() */
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer". One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. Implement the MyCircularQueue class: MyCircularQueue(k) Initializes the object with the size of the queue to be k. int Front() Gets the front item from the queue. If the queue is empty, return -1. int Rear() Gets the last item from the queue. If the queue is empty, return -1. boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful. boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful. boolean isEmpty() Checks whether the circular queue is empty or not. boolean isFull() Checks whether the circular queue is full or not. You must solve the problem without using the built-in queue data structure in your programming language.    Example 1: Input ["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"] [[3], [1], [2], [3], [4], [], [], [], [4], []] Output [null, true, true, true, false, 3, true, true, true, 4] Explanation MyCircularQueue myCircularQueue = new MyCircularQueue(3); myCircularQueue.enQueue(1); // return True myCircularQueue.enQueue(2); // return True myCircularQueue.enQueue(3); // return True myCircularQueue.enQueue(4); // return False myCircularQueue.Rear(); // return 3 myCircularQueue.isFull(); // return True myCircularQueue.deQueue(); // return True myCircularQueue.enQueue(4); // return True myCircularQueue.Rear(); // return 4   Constraints: 1 <= k <= 1000 0 <= value <= 1000 At most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull.
Medium
[ "array", "linked-list", "design", "queue" ]
[ "const MyCircularQueue = function (k) {\n this.a = new Array(k).fill(0)\n this.front = 0\n this.rear = -1\n this.len = 0\n}\n\n\nMyCircularQueue.prototype.enQueue = function (value) {\n if (!this.isFull()) {\n this.rear = (this.rear + 1) % this.a.length\n this.a[this.rear] = value\n this.len++\n return true\n } else return false\n}\n\n\nMyCircularQueue.prototype.deQueue = function () {\n if (!this.isEmpty()) {\n this.front = (this.front + 1) % this.a.length\n this.len--\n return true\n } else return false\n}\n\n\nMyCircularQueue.prototype.Front = function () {\n return this.isEmpty() ? -1 : this.a[this.front]\n}\n\n\nMyCircularQueue.prototype.Rear = function () {\n return this.isEmpty() ? -1 : this.a[this.rear]\n}\n\n\nMyCircularQueue.prototype.isEmpty = function () {\n return this.len === 0\n}\n\n\nMyCircularQueue.prototype.isFull = function () {\n return this.len == this.a.length\n}" ]
623
add-one-row-to-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} val * @param {number} depth * @return {TreeNode} */ var addOneRow = function(root, val, depth) { };
Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth. Note that the root node is at depth 1. The adding rule is: Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root. cur's original left subtree should be the left subtree of the new left subtree root. cur's original right subtree should be the right subtree of the new right subtree root. If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.   Example 1: Input: root = [4,2,6,3,1,5], val = 1, depth = 2 Output: [4,1,1,2,null,null,6,3,1,5] Example 2: Input: root = [4,2,null,3,1], val = 1, depth = 3 Output: [4,2,null,1,1,3,null,null,1]   Constraints: The number of nodes in the tree is in the range [1, 104]. The depth of the tree is in the range [1, 104]. -100 <= Node.val <= 100 -105 <= val <= 105 1 <= depth <= the depth of tree + 1
Medium
[ "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const addOneRow = function (root, v, d, level = 1) {\n if (d === 1) {\n const node = new TreeNode(v)\n node.left = root\n return node\n }\n const queue = []\n queue.push(root)\n let depth = 1\n while (queue.length) {\n const size = queue.length\n for (let i = 0; i < size; i++) {\n const cur = queue.shift()\n if (depth === d - 1) {\n let left = new TreeNode(v)\n let right = new TreeNode(v)\n left.left = cur.left\n right.right = cur.right\n cur.left = left\n cur.right = right\n } else {\n if (cur.left !== null) {\n queue.push(cur.left)\n }\n if (cur.right !== null) {\n queue.push(cur.right)\n }\n }\n }\n depth++\n }\n return root\n}", "const addOneRow = function (root, v, d, level = 1) {\n if (!root) return\n if (d === 1) {\n const newRoot = new TreeNode(v)\n newRoot.left = root\n return newRoot\n } else if (d === level + 1) {\n const oldLeft = root.left\n const oldRight = root.right\n root.left = new TreeNode(v)\n root.right = new TreeNode(v)\n root.left.left = oldLeft\n root.right.right = oldRight\n } else {\n addOneRow(root.left, v, d, level + 1)\n addOneRow(root.right, v, d, level + 1)\n }\n return root\n}" ]
628
maximum-product-of-three-numbers
[]
/** * @param {number[]} nums * @return {number} */ var maximumProduct = function(nums) { };
Given an integer array nums, find three numbers whose product is maximum and return the maximum product.   Example 1: Input: nums = [1,2,3] Output: 6 Example 2: Input: nums = [1,2,3,4] Output: 24 Example 3: Input: nums = [-1,-2,-3] Output: -6   Constraints: 3 <= nums.length <= 104 -1000 <= nums[i] <= 1000
Easy
[ "array", "math", "sorting" ]
[ "const maximumProduct = function (nums) {\n nums.sort((a, b) => a - b)\n return Math.max(\n nums[0] * nums[1] * nums[nums.length - 1],\n nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]\n )\n}", "const maximumProduct = function (nums) {\n let max1 = -Infinity\n let max2 = -Infinity\n let max3 = -Infinity\n let min1 = Infinity\n let min2 = Infinity\n for (let num of nums) {\n if (num > max1) {\n max3 = max2\n max2 = max1\n max1 = num\n } else if (num > max2) {\n max3 = max2\n max2 = num\n } else if (num > max3) {\n max3 = num\n }\n\n if (num < min1) {\n min2 = min1\n min1 = num\n } else if (num < min2) {\n min2 = num\n }\n }\n return Math.max(max1 * max2 * max3, max1 * min1 * min2)\n}" ]
629
k-inverse-pairs-array
[]
/** * @param {number} n * @param {number} k * @return {number} */ var kInversePairs = function(n, k) { };
For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j]. Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7.   Example 1: Input: n = 3, k = 0 Output: 1 Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. Example 2: Input: n = 3, k = 1 Output: 2 Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.   Constraints: 1 <= n <= 1000 0 <= k <= 1000
Hard
[ "dynamic-programming" ]
[ "const kInversePairs = function(n, k) {\n const dp = Array.from({ length: n + 1 }, () => new Array(k + 1).fill(0))\n for (let i = 1; i < n + 1; i++) {\n dp[i][0] = 1\n }\n const MOD = 1e9 + 7\n for (let i = 1; i < n + 1; i++) {\n for (let j = 1; j < k + 1; j++) {\n let val = (dp[i - 1][j] - (j >= i ? dp[i - 1][j - i] : 0) + MOD) % MOD\n dp[i][j] = (dp[i][j - 1] + val) % MOD\n }\n }\n return (dp[n][k] - (dp[n][k - 1] || 0) + MOD) % MOD\n}" ]
630
course-schedule-iii
[ "During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn’t.</br></br>\r\n\r\n1. If it doesn’t, then I have added one new course. Increment the currentTotalTime with duration of current course.", "2. If it exceeds deadline, I can swap current course with current courses that has biggest duration.</br>\r\n* No harm done and I might have just reduced the currentTotalTime, right? </br>\r\n* What preprocessing do I need to do on my course processing order so that this swap is always legal?" ]
/** * @param {number[][]} courses * @return {number} */ var scheduleCourse = function(courses) { };
There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi. You will start on the 1st day and you cannot take two or more courses simultaneously. Return the maximum number of courses that you can take.   Example 1: Input: courses = [[100,200],[200,1300],[1000,1250],[2000,3200]] Output: 3 Explanation: There are totally 4 courses, but you can take 3 courses at most: First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day. Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date. Example 2: Input: courses = [[1,2]] Output: 1 Example 3: Input: courses = [[3,2],[4,3]] Output: 0   Constraints: 1 <= courses.length <= 104 1 <= durationi, lastDayi <= 104
Hard
[ "array", "greedy", "sorting", "heap-priority-queue" ]
[ "const scheduleCourse = function (courses) {\n const compare = (a, b) => a[0] === b[0] ? 0 : (a[0] > b[0] ? -1 : 1)\n const queue = new PriorityQueue({ compare })\n courses.sort((a, b) => a[1] - b[1])\n let time = 0\n for(let e of courses) {\n time += e[0]\n queue.enqueue(e)\n if(time > e[1]) {\n const tmp = queue.dequeue()\n time -= tmp[0]\n }\n }\n return queue.size()\n}", "const scheduleCourse = function(courses) {\n const pq = new PQ((a, b) => a[0] === b[0] ? a[1] < b[1] : a[0] > b[0])\n const n = courses.length\n courses.sort((a, b) => a[1] === b[1] ? a[0] - b[0] : a[1] - b[1])\n \n let time = 0\n for(const e of courses) {\n const [dur, end] = e\n time += dur\n pq.push(e)\n if(time > end) {\n const tmp = pq.pop()\n time -= tmp[0]\n }\n }\n \n return pq.size()\n};\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}", "const scheduleCourse = function (courses) {\n const queue = new MaxPriorityQueue({\n priority: e => e[0]\n })\n courses.sort((a, b) => a[1] - b[1])\n let time = 0\n for(let e of courses) {\n time += e[0]\n queue.enqueue(e)\n if(time > e[1]) {\n const tmp = queue.dequeue().element\n time -= tmp[0]\n }\n }\n return queue.size()\n}", "const scheduleCourse = function (courses) {\n courses.sort((c1, c2) => c1[1] - c2[1])\n let count = 0\n let time = 0\n const queue = []\n const inQueue = (val) => {\n let i = 0\n while (i < queue.length && queue[i] > val) i += 1\n queue.splice(i, 0, val)\n }\n for (let i = 0; i < courses.length; i += 1) {\n const [dur, end] = courses[i]\n if (time <= end - dur) {\n count += 1\n time += dur\n inQueue(dur)\n } else if (queue.length && queue[0] > dur) {\n time = time - queue.shift() + dur\n inQueue(dur)\n }\n }\n return count\n}", "const scheduleCourse = function (courses) {\n courses.sort((a, b) => +a[1] - +b[1])\n let queue = new Heap()\n let time = 0\n for (let c of courses) {\n if (c[0] + time <= c[1]) {\n time += c[0]\n queue.push(c[0])\n } else if (queue.size() > 0) {\n let top = queue.peek()\n if (top > c[0]) {\n queue.pop()\n queue.push(c[0])\n time += c[0] - top\n }\n }\n }\n return queue.size()\n}\n\nconst parent = (i) => Math.floor((i - 1) / 2)\nconst left = (i) => 2 * i + 1\nconst right = (i) => 2 * i + 2\nclass Heap {\n constructor() {\n this.compare = (a, b) => +b - +a\n this._heap = []\n }\n size() {\n return this._heap.length\n }\n _upper(i, j) {\n return this.compare(this._heap[i], this._heap[j]) < 0\n }\n _swap(i, j) {\n let tmp = this._heap[i]\n this._heap[i] = this._heap[j]\n this._heap[j] = tmp\n }\n push(item) {\n this._heap.push(item)\n this._siftUp()\n return this.size()\n }\n _siftUp() {\n let node = this._heap.length - 1\n while (node > 0 && this._upper(node, parent(node))) {\n this._swap(node, parent(node))\n node = parent(node)\n }\n }\n peek() {\n return this._heap[0]\n }\n pop() {\n let ret = this._heap[0]\n if (this.size() > 1) {\n this._swap(0, this._heap.length - 1)\n }\n this._heap.pop()\n this._siftDown()\n return ret\n }\n _siftDown() {\n let node = 0\n while (\n (right(node) < this.size() && this._upper(right(node), node)) ||\n (left(node) < this.size() && this._upper(left(node), node))\n ) {\n let upperChild =\n right(node) < this.size() && this._upper(right(node), left(node))\n ? right(node)\n : left(node)\n this._swap(upperChild, node)\n node = upperChild\n }\n }\n}" ]
632
smallest-range-covering-elements-from-k-lists
[]
/** * @param {number[][]} nums * @return {number[]} */ var smallestRange = function(nums) { };
You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.   Example 1: Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] Output: [20,24] Explanation: List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. List 2: [0, 9, 12, 20], 20 is in range [20,24]. List 3: [5, 18, 22, 30], 22 is in range [20,24]. Example 2: Input: nums = [[1,2,3],[1,2,3],[1,2,3]] Output: [1,1]   Constraints: nums.length == k 1 <= k <= 3500 1 <= nums[i].length <= 50 -105 <= nums[i][j] <= 105 nums[i] is sorted in non-decreasing order.
Hard
[ "array", "hash-table", "greedy", "sliding-window", "sorting", "heap-priority-queue" ]
[ "const smallestRange = function(nums) {\n if (nums.length === 1) return [nums[0], nums[0]]\n const pq = new PQ((a, b) => a.v < b.v)\n let min = Number.MAX_SAFE_INTEGER\n let max = Number.MIN_SAFE_INTEGER\n for (let i = 0; i < nums.length; i++) {\n if (nums[i].length > 0) {\n const top = nums[i].shift()\n pq.push({ v: top, i })\n min = Math.min(min, top)\n max = Math.max(max, top)\n }\n }\n let bestRange = [min, max]\n while (pq.size() > 0) {\n const { v, i } = pq.pop()\n if (nums[i].length === 0) return bestRange\n const newVal = nums[i].shift()\n pq.push({ v: newVal, i })\n min = pq.peek().v\n max = Math.max(max, newVal)\n if (max - min < bestRange[1] - bestRange[0]) {\n bestRange = [min, max]\n }\n }\n return bestRange\n}\n\nfunction PQ(f) {\n this.q = []\n this.f = f\n}\n\nPQ.prototype.size = function() {\n return this.q.length\n}\n\nPQ.prototype.peek = function() {\n return this.q[0]\n}\n\nPQ.prototype.push = function(v) {\n const q = this.q\n let i = q.length\n q.push(v)\n let parent = Math.floor((i - 1) / 2)\n while (parent >= 0 && this.f(q[i], q[parent])) {\n this.swap(i, parent)\n i = parent\n parent = Math.floor((i - 1) / 2)\n }\n}\n\nPQ.prototype.pop = function() {\n const q = this.q\n if (q.length === 0) return null\n this.swap(0, q.length - 1)\n let i = 0\n let lc = 1\n let rc = 2\n while (lc < q.length - 1) {\n let r = i\n if (this.f(q[lc], q[r])) {\n r = lc\n }\n if (rc < q.length - 1 && this.f(q[rc], q[r])) {\n r = rc\n }\n if (r === i) break\n this.swap(i, r)\n i = r\n lc = i * 2 + 1\n rc = i * 2 + 2\n }\n return q.pop()\n}\n\nPQ.prototype.swap = function(i, j) {\n const q = this.q\n const t = q[i]\n q[i] = q[j]\n q[j] = t\n}", "function Queue() {\n this.data = []\n}\n\nQueue.prototype.pop = function() {\n return this.data.shift()\n}\n\nQueue.prototype.getMax = function() {\n let n = this.data.length - 1\n let max = this.data[n]\n if (max === undefined) {\n return 100000000\n }\n return max.val\n}\n\nQueue.prototype.getMin = function() {\n let min = this.data[0]\n if (min === undefined) {\n return -100000000\n }\n return min.val\n}\n\nQueue.prototype.add = function(node) {\n if (!this.data.length) {\n this.data.push(node)\n return\n }\n\n let index = findIndex(this.data, node)\n this.data.splice(index, 0, node)\n return true\n\n function findIndex(arr, node) {\n let left = 0\n let right = arr.length - 1\n while (left <= right) {\n let mid = Math.floor((left + right) / 2)\n if (arr[mid].val === node.val) {\n return mid\n }\n\n if (arr[mid].val > node.val) {\n right = mid - 1\n } else {\n left = mid + 1\n }\n }\n return left\n }\n}\n\nfunction Node(list, val, index) {\n this.list = list\n this.val = val\n this.index = index\n}\n\nvar smallestRange = function(nums) {\n let queue = new Queue()\n for (let i = 0; i < nums.length; i++) {\n let node = new Node(i, nums[i][0], 0)\n queue.add(node)\n }\n\n let a = Math.min(queue.getMin(), queue.getMax())\n let b = Math.max(queue.getMin(), queue.getMax())\n let ans = [a, b]\n let min = ans[1] - ans[0]\n for (;;) {\n let a = Math.min(queue.getMin(), queue.getMax())\n let b = Math.max(queue.getMin(), queue.getMax())\n if (b - a < min) {\n min = b - a\n ans = [a, b]\n }\n\n let m = queue.pop()\n let list = nums[m.list]\n let index = m.index\n if (index + 1 < list.length) {\n m.index++\n m.val = list[m.index]\n queue.add(m)\n } else {\n break\n }\n }\n\n return ans\n}", "class PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\nconst smallestRange = function (nums) {\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n const limit = 10 ** 5,\n n = nums.length,\n { max } = Math\n let right = -1e5,\n res = [-limit, limit]\n for (let i = 0; i < n; i++) {\n pq.push([nums[i][0], i, 0])\n right = max(right, nums[i][0])\n }\n while (pq.size()) {\n const cur = pq.pop()\n const [left, list, indice] = cur\n if (right - left < res[1] - res[0]) res = [left, right]\n if (indice + 1 === nums[list].length) return res\n right = max(right, nums[list][indice + 1])\n pq.push([nums[list][indice + 1], list, indice + 1])\n }\n return []\n}" ]
633
sum-of-square-numbers
[]
/** * @param {number} c * @return {boolean} */ var judgeSquareSum = function(c) { };
Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.   Example 1: Input: c = 5 Output: true Explanation: 1 * 1 + 2 * 2 = 5 Example 2: Input: c = 3 Output: false   Constraints: 0 <= c <= 231 - 1
Medium
[ "math", "two-pointers", "binary-search" ]
[ "const judgeSquareSum = function(c) {\n if (c < 0) return false;\n const max = Math.floor(Math.sqrt(c));\n for (let i = 0; i < max + 1; i++) {\n if (Number.isInteger(Math.sqrt(c - i * i))) {\n return true;\n }\n }\n return false;\n};" ]
636
exclusive-time-of-functions
[]
/** * @param {number} n * @param {string[]} logs * @return {number[]} */ var exclusiveTime = function(n, logs) { };
On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1. Function calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp. You are given a list logs, where logs[i] represents the ith log message formatted as a string "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means a function call with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times, possibly recursively. A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3. Return the exclusive time of each function in an array, where the value at the ith index represents the exclusive time for the function with ID i.   Example 1: Input: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"] Output: [3,4] Explanation: Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1. Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5. Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing. Example 2: Input: n = 1, logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"] Output: [8] Explanation: Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls itself again. Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing. Example 3: Input: n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"] Output: [7,1] Explanation: Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls function 1. Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6. Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time. So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.   Constraints: 1 <= n <= 100 1 <= logs.length <= 500 0 <= function_id < n 0 <= timestamp <= 109 No two start events will happen at the same timestamp. No two end events will happen at the same timestamp. Each function has an "end" log for each "start" log.
Medium
[ "array", "stack" ]
[ "const exclusiveTime = function (n, logs) {\n const res = [...Array(n)].fill(0)\n const stack = []\n let pre = 0\n for (let i = 0; i < logs.length; i++) {\n const log = logs[i].split(':')\n if (log[1] === 'start') {\n if(stack.length !== 0) res[stack[stack.length - 1]] += +log[2] - pre\n stack.push(log[0])\n pre = log[2]\n } else {\n res[stack.pop()] += +log[2] - pre + 1\n pre = +log[2] + 1\n }\n }\n return res\n}" ]
637
average-of-levels-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 * @return {number[]} */ var averageOfLevels = function(root) { };
Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: root = [3,9,20,null,null,15,7] Output: [3.00000,14.50000,11.00000] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. Example 2: Input: root = [3,9,20,15,7] Output: [3.00000,14.50000,11.00000]   Constraints: The number of nodes in the tree is in the range [1, 104]. -231 <= Node.val <= 231 - 1
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 averageOfLevels = function(root) {\n const res = [];\n layer(res, [root]);\n return res.map(el => el.val / el.num);\n};\n\nfunction layer(arr, args) {\n const item = {\n val: args.reduce((ac, el) => ac + el.val, 0),\n num: args.length\n };\n arr.push(item);\n const children = [];\n args.forEach(el => {\n el.left === null ? null : children.push(el.left);\n el.right === null ? null : children.push(el.right);\n });\n if (children.length) {\n layer(arr, children);\n }\n}" ]
638
shopping-offers
[]
/** * @param {number[]} price * @param {number[][]} special * @param {number[]} needs * @return {number} */ var shoppingOffers = function(price, special, needs) { };
In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy. You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer. Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.   Example 1: Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2] Output: 14 Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. In special offer 1, you can pay $5 for 3A and 0B In special offer 2, you can pay $10 for 1A and 2B. You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A. Example 2: Input: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1] Output: 11 Explanation: The price of A is $2, and $3 for B, $4 for C. You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. You cannot add more items, though only $9 for 2A ,2B and 1C.   Constraints: n == price.length == needs.length 1 <= n <= 6 0 <= price[i], needs[i] <= 10 1 <= special.length <= 100 special[i].length == n + 1 0 <= special[i][j] <= 50
Medium
[ "array", "dynamic-programming", "backtracking", "bit-manipulation", "memoization", "bitmask" ]
[ "const shoppingOffers = function (price, special, needs) {\n const directBuy = function (price, needs) {\n let res = 0\n for (let i = 0; i < price.length; i++) {\n res += price[i] * needs[i]\n }\n return res\n }\n const isValid = function (offer, needs) {\n for (let i = 0; i < offer.length; i++) {\n if (offer[i] > needs[i]) return false\n }\n return true\n }\n const help = (price, special, needs) => {\n let curMin = directBuy(price, needs)\n for (let i = 0; i < special.length; i++) {\n let curOf = special[i]\n if (isValid(curOf, needs)) {\n let tem = []\n for (let j = 0; j < needs.length; j++) {\n tem.push(needs[j] - curOf[j])\n }\n if (tem.length > 0) {\n curMin = Math.min(\n curMin,\n curOf[curOf.length - 1] + help(price, special, tem)\n )\n }\n }\n }\n return curMin\n }\n return help(price, special, needs)\n}" ]
639
decode-ways-ii
[]
/** * @param {string} s * @return {number} */ var numDecodings = function(s) { };
A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: "AAJF" with the grouping (1 1 10 6) "KJF" with the grouping (11 10 6) Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent. Given a string s consisting of digits and '*' characters, return the number of ways to decode it. Since the answer may be very large, return it modulo 109 + 7.   Example 1: Input: s = "*" Output: 9 Explanation: The encoded message can represent any of the encoded messages "1", "2", "3", "4", "5", "6", "7", "8", or "9". Each of these can be decoded to the strings "A", "B", "C", "D", "E", "F", "G", "H", and "I" respectively. Hence, there are a total of 9 ways to decode "*". Example 2: Input: s = "1*" Output: 18 Explanation: The encoded message can represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Each of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K"). Hence, there are a total of 9 * 2 = 18 ways to decode "1*". Example 3: Input: s = "2*" Output: 15 Explanation: The encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "28", or "29". "21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have 1 way. Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2*".   Constraints: 1 <= s.length <= 105 s[i] is a digit or '*'.
Hard
[ "string", "dynamic-programming" ]
[ "const numDecodings = function(s) {\n const mod = Math.pow(10, 9) + 7\n const dp = [1, s.charAt(0) === '*' ? 9 : s.charAt(0) === '0' ? 0 : 1]\n for (let i = 0; i < s.length; i++) {\n if (s.charAt(i) === '*') {\n if (s.charAt(i - 1) === '*') {\n dp[i + 1] = 9 * dp[i] + 15 * dp[i - 1]\n } else if (s.charAt(i - 1) === '1') {\n dp[i + 1] = 9 * dp[i] + 9 * dp[i - 1]\n } else if (s.charAt(i - 1) === '2') {\n dp[i + 1] = 9 * dp[i] + 6 * dp[i - 1]\n } else {\n dp[i + 1] = dp[i] * 9\n }\n } else {\n let mul = s.charAt(i) === '0' ? 0 : 1\n if (s.charAt(i - 1) === '*') {\n dp[i + 1] = mul * dp[i] + (s.charAt(i) <= '6' ? 2 : 1) * dp[i - 1]\n } else if (\n s.charAt(i - 1) === '1' ||\n (s.charAt(i - 1) === '2' && s.charAt(i) <= '6')\n ) {\n dp[i + 1] = mul * dp[i] + dp[i - 1]\n } else {\n dp[i + 1] = mul * dp[i]\n }\n }\n dp[i + 1] = dp[i + 1] % mod\n }\n return dp[dp.length - 1]\n}" ]
640
solve-the-equation
[]
/** * @param {string} equation * @return {string} */ var solveEquation = function(equation) { };
Solve a given equation and return the value of 'x' in the form of a string "x=#value". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return "No solution" if there is no solution for the equation, or "Infinite solutions" if there are infinite solutions for the equation. If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.   Example 1: Input: equation = "x+5-3+x=6+x-2" Output: "x=2" Example 2: Input: equation = "x=x" Output: "Infinite solutions" Example 3: Input: equation = "2x=x" Output: "x=0"   Constraints: 3 <= equation.length <= 1000 equation has exactly one '='. equation consists of integers with an absolute value in the range [0, 100] without any leading zeros, and the variable 'x'.
Medium
[ "math", "string", "simulation" ]
[ "function solveEquation (equation) {\n const strArr = equation.split('=')\n const leftHash = build(strArr[0])\n const rightHash = build(strArr[1])\n const xnum = leftHash.x - rightHash.x\n const num = rightHash.num - leftHash.num\n if(xnum === 0 && num !== 0) {\n return \"No solution\"\n } else if(xnum === 0) {\n return \"Infinite solutions\"\n } else {\n return `x=${num / xnum}`\n }\n};\n\nfunction build(str) {\n let cur = ''\n const map = {\n num:0,\n x:0\n }\n for(let i = 0; i < str.length; i++) {\n if(str[i] === '-' || str[i] === '+') {\n chkCur(cur, map)\n cur = str[i]\n } else {\n cur += str[i]\n }\n }\n if(cur !== '') {\n chkCur(cur, map)\n }\n return map\n}\nfunction chkCur(cur, map) {\n let xIdx = cur.indexOf('x')\n if(xIdx === -1) {\n map.num += +cur\n } else {\n map.x += chkX(cur, xIdx)\n }\n}\nfunction chkX(str, xIdx) {\n let tmp = str.slice(0,xIdx)\n let num = 0\n if(tmp === '-') {\n num = -1\n } else if(tmp === '' || tmp === '+') {\n num = 1\n } else {\n num = +tmp\n }\n return num\n}" ]
641
design-circular-deque
[]
/** * @param {number} k */ var MyCircularDeque = function(k) { }; /** * @param {number} value * @return {boolean} */ MyCircularDeque.prototype.insertFront = function(value) { }; /** * @param {number} value * @return {boolean} */ MyCircularDeque.prototype.insertLast = function(value) { }; /** * @return {boolean} */ MyCircularDeque.prototype.deleteFront = function() { }; /** * @return {boolean} */ MyCircularDeque.prototype.deleteLast = function() { }; /** * @return {number} */ MyCircularDeque.prototype.getFront = function() { }; /** * @return {number} */ MyCircularDeque.prototype.getRear = function() { }; /** * @return {boolean} */ MyCircularDeque.prototype.isEmpty = function() { }; /** * @return {boolean} */ MyCircularDeque.prototype.isFull = function() { }; /** * Your MyCircularDeque object will be instantiated and called as such: * var obj = new MyCircularDeque(k) * var param_1 = obj.insertFront(value) * var param_2 = obj.insertLast(value) * var param_3 = obj.deleteFront() * var param_4 = obj.deleteLast() * var param_5 = obj.getFront() * var param_6 = obj.getRear() * var param_7 = obj.isEmpty() * var param_8 = obj.isFull() */
Design your implementation of the circular double-ended queue (deque). Implement the MyCircularDeque class: MyCircularDeque(int k) Initializes the deque with a maximum size of k. boolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise. boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise. boolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise. boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise. int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty. int getRear() Returns the last item from Deque. Returns -1 if the deque is empty. boolean isEmpty() Returns true if the deque is empty, or false otherwise. boolean isFull() Returns true if the deque is full, or false otherwise.   Example 1: Input ["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"] [[3], [1], [2], [3], [4], [], [], [], [4], []] Output [null, true, true, true, false, 2, true, true, true, 4] Explanation MyCircularDeque myCircularDeque = new MyCircularDeque(3); myCircularDeque.insertLast(1); // return True myCircularDeque.insertLast(2); // return True myCircularDeque.insertFront(3); // return True myCircularDeque.insertFront(4); // return False, the queue is full. myCircularDeque.getRear(); // return 2 myCircularDeque.isFull(); // return True myCircularDeque.deleteLast(); // return True myCircularDeque.insertFront(4); // return True myCircularDeque.getFront(); // return 4   Constraints: 1 <= k <= 1000 0 <= value <= 1000 At most 2000 calls will be made to insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty, isFull.
Medium
[ "array", "linked-list", "design", "queue" ]
[ "const MyCircularDeque = function(k) {\n this.q = []\n this.k = k\n};\n\n\nMyCircularDeque.prototype.insertFront = function(value) {\n if(this.q.length < this.k) {\n this.q.unshift(value)\n return true\n }\n return false\n};\n\n\nMyCircularDeque.prototype.insertLast = function(value) {\n if(this.q.length < this.k) {\n this.q.push(value)\n return true\n }\n return false\n};\n\n\nMyCircularDeque.prototype.deleteFront = function() {\n if(this.q.length) {\n this.q.shift()\n return true\n }\n return false\n};\n\n\nMyCircularDeque.prototype.deleteLast = function() {\n if(this.q.length) {\n this.q.pop()\n return true\n }\n return false \n};\n\n\nMyCircularDeque.prototype.getFront = function() {\n return this.q[0] === undefined ? -1 : this.q[0]\n};\n\n\nMyCircularDeque.prototype.getRear = function() {\n return this.q[this.q.length - 1] === undefined ? -1 : this.q[this.q.length - 1]\n};\n\n\nMyCircularDeque.prototype.isEmpty = function() {\n return this.q.length === 0\n};\n\n\nMyCircularDeque.prototype.isFull = function() {\n return this.q.length === this.k\n};" ]
643
maximum-average-subarray-i
[]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var findMaxAverage = function(nums, k) { };
You are given an integer array nums consisting of n elements, and an integer k. Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.   Example 1: Input: nums = [1,12,-5,-6,50,3], k = 4 Output: 12.75000 Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 Example 2: Input: nums = [5], k = 1 Output: 5.00000   Constraints: n == nums.length 1 <= k <= n <= 105 -104 <= nums[i] <= 104
Easy
[ "array", "sliding-window" ]
[ "const findMaxAverage = function(nums, k) {\n let max = 0;\n let temp = 0;\n for(let i = 0; i < k; i++) {\n max += nums[i];\n }\n temp = max;\n for(let i = k; i < nums.length ; i++) {\n temp = temp - nums[i - k] + nums[i];\n max = Math.max(max, temp);\n }\n \n return max/k;\n };" ]
645
set-mismatch
[]
/** * @param {number[]} nums * @return {number[]} */ var findErrorNums = function(nums) { };
You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. You are given an integer array nums representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return them in the form of an array.   Example 1: Input: nums = [1,2,2,4] Output: [2,3] Example 2: Input: nums = [1,1] Output: [1,2]   Constraints: 2 <= nums.length <= 104 1 <= nums[i] <= 104
Easy
[ "array", "hash-table", "bit-manipulation", "sorting" ]
[ "const findErrorNums = function(nums) {\n if(nums == null || nums.length === 0) return null\n const res = []\n const hash = {}\n for(let el of nums) {\n if(hash.hasOwnProperty(el)){\n res[0] = el\n } else hash[el] = 0\n hash[el]++\n }\n for(let i = 1, len = nums.length; i <= len; i++) {\n if(!hash.hasOwnProperty(i)) {\n res[1] = i\n break\n }\n }\n return res\n};", "const findErrorNums = function(nums) {\n const res = [];\n for (const i of nums) {\n if (nums[Math.abs(i) - 1] < 0) res[0] = Math.abs(i);\n\t else nums[Math.abs(i) - 1] *= -1;\n }\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] > 0) res[1] = i + 1;\n }\n return res; \n};" ]
646
maximum-length-of-pair-chain
[]
/** * @param {number[][]} pairs * @return {number} */ var findLongestChain = function(pairs) { };
You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti. A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion. Return the length longest chain which can be formed. You do not need to use up all the given intervals. You can select pairs in any order.   Example 1: Input: pairs = [[1,2],[2,3],[3,4]] Output: 2 Explanation: The longest chain is [1,2] -> [3,4]. Example 2: Input: pairs = [[1,2],[7,8],[4,5]] Output: 3 Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].   Constraints: n == pairs.length 1 <= n <= 1000 -1000 <= lefti < righti <= 1000
Medium
[ "array", "dynamic-programming", "greedy", "sorting" ]
[ "const findLongestChain = function(pairs) {\n pairs.sort((a, b) => a[1] - b[1])\n let end = pairs[0][1], res = 1\n for(let i = 1, len = pairs.length; i < len; i++) {\n if(pairs[i][0] > end) {\n res++\n end = pairs[i][1]\n } \n }\n return res\n};", "const findLongestChain = function(pairs) {\n pairs.sort((a, b) => a[1] - b[1]);\n let cur = Number.MIN_SAFE_INTEGER;\n let res = 0;\n for (let i = 0; i < pairs.length; i++) {\n if (cur < pairs[i][0]) {\n cur = pairs[i][1];\n res += 1;\n }\n }\n return res;\n};", "const findLongestChain = function (pairs) {\n pairs.sort((a, b) => a[0] - b[0])\n let out = 0\n let prevEnd = Number.MIN_SAFE_INTEGER\n for (let i = 0; i < pairs.length; i++) {\n const cur = pairs[i]\n if (prevEnd < cur[0]) {\n prevEnd = cur[1]\n out += 1\n } else {\n prevEnd = Math.min(cur[1], prevEnd)\n }\n }\n return out\n}" ]
647
palindromic-substrings
[ "How can we reuse a previously computed palindrome to compute a larger palindrome?", "If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome?", "Complexity based hint:</br>\r\nIf we use brute force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation?" ]
/** * @param {string} s * @return {number} */ var countSubstrings = function(s) { };
Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string.   Example 1: Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Example 2: Input: s = "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".   Constraints: 1 <= s.length <= 1000 s consists of lowercase English letters.
Medium
[ "string", "dynamic-programming" ]
[ "const countSubstrings = function(s) {\n let count = 0;\n\n if (s == null || s.length === 0) {\n return 0;\n }\n\n for (let i = 0; i < s.length; i++) {\n extendPalindrome(s, i, i);\n extendPalindrome(s, i, i + 1);\n }\n\n function extendPalindrome(str, left, right) {\n while (\n left >= 0 &&\n right < s.length &&\n s.charAt(left) === s.charAt(right)\n ) {\n count++;\n left--;\n right++;\n }\n }\n return count;\n};\n\nconsole.log(countSubstrings(\"abc\"));\nconsole.log(countSubstrings(\"aaa\"));", "const countSubstrings = function(s) {\n const arr = manachers(s)\n return arr.map(e => ~~((e + 1) / 2)).reduce((ac, e) => ac + e, 0)\n};\n\nfunction manachers(s) {\n const str = `@#${s.split('').join('#')}#$`\n const arr = Array(str.length).fill(0)\n \n let center = right = 0\n for(let i = 1, n = str.length; i < n - 1; i++) {\n if(i < right) {\n arr[i] = Math.min(right - i, arr[2 * center - i])\n }\n while(str[i + arr[i] + 1] === str[i - arr[i] - 1]) {\n arr[i] += 1\n }\n if(i + arr[i] > right) {\n center = i\n right = i + arr[i]\n }\n }\n \n return arr\n}" ]
648
replace-words
[]
/** * @param {string[]} dictionary * @param {string} sentence * @return {string} */ var replaceWords = function(dictionary, sentence) { };
In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root "an" is followed by the successor word "other", we can form a new word "another". Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length. Return the sentence after the replacement.   Example 1: Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery" Output: "the cat was rat by the bat" Example 2: Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs" Output: "a a b c"   Constraints: 1 <= dictionary.length <= 1000 1 <= dictionary[i].length <= 100 dictionary[i] consists of only lower-case letters. 1 <= sentence.length <= 106 sentence consists of only lower-case letters and spaces. The number of words in sentence is in the range [1, 1000] The length of each word in sentence is in the range [1, 1000] Every two consecutive words in sentence will be separated by exactly one space. sentence does not have leading or trailing spaces.
Medium
[ "array", "hash-table", "string", "trie" ]
[ "const replaceWords = function(dict, sentence) {\n dict.sort();\n const unsortedParts = sentence.split(\" \");\n const parts = unsortedParts.slice();\n parts.sort();\n\n let i = (j = 0);\n const rootMap = {};\n while (i < dict.length && j < parts.length) {\n let part = parts[j];\n let root = dict[i];\n // dict is ahead, increase part\n if (root > part) {\n j++;\n } else {\n if (part.startsWith(root)) {\n rootMap[part] = root;\n j++;\n } else {\n i++;\n }\n }\n }\n for (i = 0; i < unsortedParts.length; i++) {\n if (rootMap[unsortedParts[i]]) {\n unsortedParts[i] = rootMap[unsortedParts[i]];\n }\n }\n return unsortedParts.join(\" \");\n};\n\nconsole.log(\n replaceWords([\"cat\", \"bat\", \"rat\"], \"the cattle was rattled by the battery\")\n);" ]
649
dota2-senate
[]
/** * @param {string} senate * @return {string} */ var predictPartyVictory = function(senate) { };
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights: Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds. Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game. Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n. The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be "Radiant" or "Dire".   Example 1: Input: senate = "RD" Output: "Radiant" Explanation: The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. Example 2: Input: senate = "RDD" Output: "Dire" Explanation: The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.   Constraints: n == senate.length 1 <= n <= 104 senate[i] is either 'R' or 'D'.
Medium
[ "string", "greedy", "queue" ]
[ "const predictPartyVictory = function (senate) {\n const m = senate.length,\n radiant = [],\n dire = []\n for (let i = 0; i < m; i++) {\n if (senate[i] === 'R') {\n radiant.push(i)\n } else {\n dire.push(i)\n }\n }\n\n while (radiant.length && dire.length) {\n let r = radiant.shift(),\n d = dire.shift()\n if (r < d) {\n radiant.push(r + m)\n } else {\n dire.push(d + m)\n }\n }\n return radiant.length > dire.length ? 'Radiant' : 'Dire'\n}" ]
650
2-keys-keyboard
[ "How many characters may be there in the clipboard at the last step if n = 3? n = 7? n = 10? n = 24?" ]
/** * @param {number} n * @return {number} */ var minSteps = function(n) { };
There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step: Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). Paste: You can paste the characters which are copied last time. Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.   Example 1: Input: n = 3 Output: 3 Explanation: Initially, we have one character 'A'. In step 1, we use Copy All operation. In step 2, we use Paste operation to get 'AA'. In step 3, we use Paste operation to get 'AAA'. Example 2: Input: n = 1 Output: 0   Constraints: 1 <= n <= 1000
Medium
[ "math", "dynamic-programming" ]
[ "const minSteps = function(n) {\n let res = 0\n for (let i = 2; i <= n; i++) {\n while (n % i === 0) {\n res += i\n n /= i\n }\n }\n return res\n}" ]
652
find-duplicate-subtrees
[]
/** * 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 findDuplicateSubtrees = function(root) { };
Given the root of a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them. Two trees are duplicate if they have the same structure with the same node values.   Example 1: Input: root = [1,2,3,4,null,2,4,null,null,4] Output: [[2,4],[4]] Example 2: Input: root = [2,1,1] Output: [[1]] Example 3: Input: root = [2,2,2,3,null,3,null] Output: [[2,3],[3]]   Constraints: The number of the nodes in the tree will be in the range [1, 5000] -200 <= Node.val <= 200
Medium
[ "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 findDuplicateSubtrees = function(root) {\n const hash = {}, res = []\n pre(root, hash, res)\n return res\n};\n\nfunction pre(node, hash, res) {\n if(node == null) return '#'\n const str = `${node.val},${pre(node.left, hash, res)},${pre(node.right, hash, res)}`\n if(hash[str] == null) hash[str] = 0\n hash[str]++\n if(hash[str] === 2) res.push(node)\n return str\n}", "const findDuplicateSubtrees = function(root) {\n const serId = {}, cntId = {}, res = []\n let id = 1\n post(root)\n return res\n \n function post(node) {\n if(node == null) return 0\n const curId = `${post(node.left)},${node.val},${post(node.right)}`\n serId[curId] = serId[curId] || id\n if(serId[curId] === id) id++\n cntId[curId] = (cntId[curId] || 0) + 1\n if(cntId[curId] === 2) res.push(node)\n return serId[curId]\n }\n};" ]
653
two-sum-iv-input-is-a-bst
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} k * @return {boolean} */ var findTarget = function(root, k) { };
Given the root of a binary search tree and an integer k, return true if there exist two elements in the BST such that their sum is equal to k, or false otherwise.   Example 1: Input: root = [5,3,6,2,4,null,7], k = 9 Output: true Example 2: Input: root = [5,3,6,2,4,null,7], k = 28 Output: false   Constraints: The number of nodes in the tree is in the range [1, 104]. -104 <= Node.val <= 104 root is guaranteed to be a valid binary search tree. -105 <= k <= 105
Easy
[ "hash-table", "two-pointers", "tree", "depth-first-search", "breadth-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 findTarget = function(root, k) {\n const m = new Map()\n return traverse(root, k, m)\n};\n\nfunction traverse(node, k, m) {\n if(node == null) return false\n if(m.has(k - node.val)) return true\n m.set(node.val, node)\n return traverse(node.left,k,m) || traverse(node.right,k,m)\n}" ]
654
maximum-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 {number[]} nums * @return {TreeNode} */ var constructMaximumBinaryTree = function(nums) { };
You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm: Create a root node whose value is the maximum value in nums. Recursively build the left subtree on the subarray prefix to the left of the maximum value. Recursively build the right subtree on the subarray suffix to the right of the maximum value. Return the maximum binary tree built from nums.   Example 1: Input: nums = [3,2,1,6,0,5] Output: [6,3,5,null,2,0,null,null,1] Explanation: The recursive calls are as follow: - The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5]. - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1]. - Empty array, so no child. - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1]. - Empty array, so no child. - Only one element, so child is a node with value 1. - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is []. - Only one element, so child is a node with value 0. - Empty array, so no child. Example 2: Input: nums = [3,2,1] Output: [3,null,2,null,1]   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 1000 All integers in nums are unique.
Medium
[ "array", "divide-and-conquer", "stack", "tree", "monotonic-stack", "binary-tree" ]
null
[]
655
print-binary-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {string[][]} */ var printTree = function(root) { };
Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules: The height of the tree is height and the number of rows m should be equal to height + 1. The number of columns n should be equal to 2height+1 - 1. Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]). For each node that has been placed in the matrix at position res[r][c], place its left child at res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1]. Continue this process until all the nodes in the tree have been placed. Any empty cells should contain the empty string "". Return the constructed matrix res.   Example 1: Input: root = [1,2] Output: [["","1",""],  ["2","",""]] Example 2: Input: root = [1,2,3,null,4] Output: [["","","","1","","",""],  ["","2","","","","3",""],  ["","","4","","","",""]]   Constraints: The number of nodes in the tree is in the range [1, 210]. -99 <= Node.val <= 99 The depth of the tree will be in the range [1, 10].
Medium
[ "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const printTree = function (root) {\n const h = getH(root)\n const w = Math.pow(2, h) - 1\n const matrix = new Array(h).fill(0).map((_) => new Array(w).fill(''))\n fill(root, 0, 0, w - 1)\n return matrix\n function getH(root) {\n if (!root) return 0\n return Math.max(getH(root.left), getH(root.right)) + 1\n }\n function fill(root, level, start, end) {\n if (!root) return\n let mid = (start + end) / 2\n matrix[level][mid] = root.val + ''\n fill(root.left, level + 1, start, mid - 1)\n fill(root.right, level + 1, mid + 1, end)\n }\n}" ]
657
robot-return-to-origin
[]
/** * @param {string} moves * @return {boolean} */ var judgeCircle = function(moves) { };
There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. You are given a string moves that represents the move sequence of the robot where moves[i] represents its ith move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down). Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise. Note: The way that the robot is "facing" is irrelevant. 'R' will always make the robot move to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.   Example 1: Input: moves = "UD" Output: true Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true. Example 2: Input: moves = "LL" Output: false Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.   Constraints: 1 <= moves.length <= 2 * 104 moves only contains the characters 'U', 'D', 'L' and 'R'.
Easy
[ "string", "simulation" ]
null
[]
658
find-k-closest-elements
[]
/** * @param {number[]} arr * @param {number} k * @param {number} x * @return {number[]} */ var findClosestElements = function(arr, k, x) { };
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: |a - x| < |b - x|, or |a - x| == |b - x| and a < b   Example 1: Input: arr = [1,2,3,4,5], k = 4, x = 3 Output: [1,2,3,4] Example 2: Input: arr = [1,2,3,4,5], k = 4, x = -1 Output: [1,2,3,4]   Constraints: 1 <= k <= arr.length 1 <= arr.length <= 104 arr is sorted in ascending order. -104 <= arr[i], x <= 104
Medium
[ "array", "two-pointers", "binary-search", "sliding-window", "sorting", "heap-priority-queue" ]
[ "const findClosestElements = function(arr, k, x) {\n let lo = 0, hi = arr.length - k - 1;\n while (lo <= hi) {\n let mid = Math.floor(lo + (hi - lo) / 2);\n if (Math.abs(x - arr[mid]) > Math.abs(x - arr[mid+k])) {\n lo = mid + 1; \n } else {\n hi = mid - 1; \n } \n } \n return arr.slice(lo, lo+k);\n};", "const findClosestElements = function(arr, k, x) {\n let lo=0,hi=arr.length-1\n while(hi-lo>=k){\n let left=Math.abs(x-arr[lo])\n let right=Math.abs(x-arr[hi])\n if(left<right){\n hi--\n }else if(left>right){\n lo++\n }else{\n hi--\n }\n }\n return arr.slice(lo,hi+1)\n};" ]
659
split-array-into-consecutive-subsequences
[]
/** * @param {number[]} nums * @return {boolean} */ var isPossible = function(nums) { };
You are given an integer array nums that is sorted in non-decreasing order. Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true: Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer). All subsequences have a length of 3 or more. Return true if you can split nums according to the above conditions, or false otherwise. A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).   Example 1: Input: nums = [1,2,3,3,4,5] Output: true Explanation: nums can be split into the following subsequences: [1,2,3,3,4,5] --> 1, 2, 3 [1,2,3,3,4,5] --> 3, 4, 5 Example 2: Input: nums = [1,2,3,3,4,4,5,5] Output: true Explanation: nums can be split into the following subsequences: [1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5 [1,2,3,3,4,4,5,5] --> 3, 4, 5 Example 3: Input: nums = [1,2,3,4,4,5] Output: false Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.   Constraints: 1 <= nums.length <= 104 -1000 <= nums[i] <= 1000 nums is sorted in non-decreasing order.
Medium
[ "array", "hash-table", "greedy", "heap-priority-queue" ]
[ "const isPossible = function(nums) {\n const freq = new Map()\n const build = new Map()\n for (let el of nums) {\n freq.has(el) ? freq.set(el, freq.get(el) + 1) : freq.set(el, 1)\n }\n for (let item of nums) {\n if (freq.get(item) === 0) continue\n else if (getOrDefault(build, item) > 0) {\n build.set(item, build.get(item) - 1)\n build.set(item + 1, getOrDefault(build, item + 1) + 1)\n } else if (getOrDefault(freq, item + 1) > 0 && getOrDefault(freq, item + 2) > 0) {\n freq.set(item + 1, freq.get(item + 1) - 1)\n freq.set(item + 2, freq.get(item + 2) - 1)\n build.set(item + 3, getOrDefault(build, item + 3) + 1)\n } else return false\n freq.set(item, freq.get(item) - 1)\n }\n return true\n}\n\nfunction getOrDefault(map, key) {\n return map.get(key) || 0\n}", "const isPossible = function(nums) {\n let prev = -Infinity, p1 = 0, p2 = 0, p3 = 0\n let i = 0\n const n = nums.length\n while (i < n) {\n let curr = nums[i], c1 = 0, c2 = 0, c3 = 0\n let cnt = 0\n while (i < n && nums[i] === curr) { cnt++; i++ }\n if (curr !== prev+1) {\n if (p1 > 0 || p2 > 0) { return false }\n c1 = cnt; c2 = 0; c3 = 0\n } else {\n if (cnt < p1 + p2) { return false }\n c2 = p1\n c3 = p2 + Math.min(p3, cnt - p1 - p2)\n c1 = Math.max(0, cnt - p1 - p2 - p3)\n }\n prev = curr; p1 = c1; p2 = c2; p3 = c3;\n }\n return p1 === 0 && p2 === 0\n};" ]
661
image-smoother
[]
/** * @param {number[][]} img * @return {number[][]} */ var imageSmoother = function(img) { };
An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.   Example 1: Input: img = [[1,1,1],[1,0,1],[1,1,1]] Output: [[0,0,0],[0,0,0],[0,0,0]] Explanation: For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 For the point (1,1): floor(8/9) = floor(0.88888889) = 0 Example 2: Input: img = [[100,200,100],[200,50,200],[100,200,100]] Output: [[137,141,137],[141,138,141],[137,141,137]] Explanation: For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137 For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141 For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138   Constraints: m == img.length n == img[i].length 1 <= m, n <= 200 0 <= img[i][j] <= 255
Easy
[ "array", "matrix" ]
[ "const imageSmoother = function (M) {\n const r = M.length\n if (r === 0) return 0\n const c = M[0].length\n if (c === 0) return 0\n const res = Array.from({ length: r }, () => Array(c).fill(0))\n for (let i = 0; i < r; i++) {\n for (let j = 0; j < c; j++) {\n res[i][j] = helper(M, i, j, res)\n }\n }\n return res\n}\n\nfunction helper(M, i, j, res) {\n let val = M[i][j]\n let num = 1\n const dirs = [\n [-1, -1],\n [-1, 0],\n [-1, 1],\n [0, -1],\n [0, 1],\n [1, -1],\n [1, 0],\n [1, 1],\n ]\n for (let [dr, dc] of dirs) {\n const ii = i + dr\n const jj = j + dc\n if (M[ii] != null && M[ii][jj] != null) {\n val += M[ii][jj]\n num++\n }\n }\n return (val / num) >> 0\n}" ]
662
maximum-width-of-binary-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var widthOfBinaryTree = function(root) { };
Given the root of a binary tree, return the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation. It is guaranteed that the answer will in the range of a 32-bit signed integer.   Example 1: Input: root = [1,3,2,5,3,null,9] Output: 4 Explanation: The maximum width exists in the third level with length 4 (5,3,null,9). Example 2: Input: root = [1,3,2,5,null,null,9,6,null,7] Output: 7 Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7). Example 3: Input: root = [1,3,2,5] Output: 2 Explanation: The maximum width exists in the second level with length 2 (3,2).   Constraints: The number of nodes in the tree is in the range [1, 3000]. -100 <= Node.val <= 100
Medium
[ "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const widthOfBinaryTree = function(root) {\n const mins = [0]\n let max = 0\n \n dfs(root, 0, 0)\n return max\n \n // depth first search\n function dfs(currentNode, depth, position) {\n if (!currentNode) return\n if (depth === mins.length) {\n mins[depth] = position\n }\n \n const delta = position - mins[depth]\n max = Math.max(max, delta + 1)\n dfs(currentNode.left, depth + 1, delta * 2)\n dfs(currentNode.right, depth + 1, delta * 2 + 1)\n }\n }" ]
664
strange-printer
[]
/** * @param {string} s * @return {number} */ var strangePrinter = function(s) { };
There is a strange printer with the following two special properties: The printer can only print a sequence of the same character each time. At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters. Given a string s, return the minimum number of turns the printer needed to print it.   Example 1: Input: s = "aaabbb" Output: 2 Explanation: Print "aaa" first and then print "bbb". Example 2: Input: s = "aba" Output: 2 Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.   Constraints: 1 <= s.length <= 100 s consists of lowercase English letters.
Hard
[ "string", "dynamic-programming" ]
[ "const strangePrinter = function(s) {\n // optimize\n const arr = s.split('')\n for(let i = 1; i < arr.length; i++) {\n if(arr[i] === arr[i - 1]) arr[i - 1] = ''\n }\n s = arr.join('')\n let n = s.length\n let dp = new Array(n).fill(0).map(() => new Array(n).fill(0))\n\n const help = (s, i, j) => {\n if (i > j) return 0\n if (dp[i][j] > 0) {\n return dp[i][j]\n }\n let res = help(s, i, j - 1) + 1\n for (let k = i; k < j; k++) {\n if (s[k] === s[j]) {\n res = Math.min(help(s, i, k) + help(s, k + 1, j - 1), res)\n }\n }\n dp[i][j] = res\n return res\n }\n\n return help(s, 0, n - 1)\n}", "const strangePrinter = function(s) {\n const n = s.length\n const dp = Array.from({ length: n }, () => Array(n).fill(n))\n for(let i = 0; i < n; i++) dp[i][i] = 1\n for(let len = 2; len <= n; len++) {\n for(let i = 0; i < n - len + 1; i++) {\n let j = i + len - 1\n dp[i][j] = 1 + dp[i + 1][j]\n for(let k = i + 1; k < j; k++) {\n if(s[i] === s[k]) dp[i][j] = Math.min(dp[i][j], dp[i][k - 1] + dp[k + 1][j])\n }\n if(s[i] === s[j]) dp[i][j] = Math.min(dp[i][j - 1], dp[i][j])\n }\n }\n return dp[0][n - 1]\n};" ]
665
non-decreasing-array
[]
/** * @param {number[]} nums * @return {boolean} */ var checkPossibility = function(nums) { };
Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element. We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).   Example 1: Input: nums = [4,2,3] Output: true Explanation: You could modify the first 4 to 1 to get a non-decreasing array. Example 2: Input: nums = [4,2,1] Output: false Explanation: You cannot get a non-decreasing array by modifying at most one element.   Constraints: n == nums.length 1 <= n <= 104 -105 <= nums[i] <= 105
Medium
[ "array" ]
[ "const checkPossibility = function(nums) {\n let count = 0;\n let idx;\n if (nums.length === 1) return true;\n for (let i = 1; i < nums.length; i++) {\n if (nums[i - 1] > nums[i]) {\n count++;\n idx = i;\n }\n }\n if (count > 1) return false;\n if (idx === nums.length - 1 || idx === 1) return true;\n return (\n Math.max(...nums.slice(0, idx - 1)) <= Math.min(...nums.slice(idx)) ||\n Math.max(...nums.slice(0, idx)) <= Math.min(...nums.slice(idx + 1))\n );\n};" ]
667
beautiful-arrangement-ii
[]
/** * @param {number} n * @param {number} k * @return {number[]} */ var constructArray = function(n, k) { };
Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement: Suppose this list is answer = [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers. Return the list answer. If there multiple valid answers, return any of them.   Example 1: Input: n = 3, k = 1 Output: [1,2,3] Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1 Example 2: Input: n = 3, k = 2 Output: [1,3,2] Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.   Constraints: 1 <= k < n <= 104
Medium
[ "array", "math" ]
[ "const constructArray = function (n, k) {\n const res = [1]\n while (k) {\n const index = res.length\n if (index % 2 === 1) {\n res.push(res[index - 1] + k)\n } else {\n res.push(res[index - 1] - k)\n }\n k -= 1\n }\n if (res.length < n) {\n for (let i = res.length + 1; i <= n; i += 1) {\n res.push(i)\n }\n }\n return res\n}" ]
668
kth-smallest-number-in-multiplication-table
[]
/** * @param {number} m * @param {number} n * @param {number} k * @return {number} */ var findKthNumber = function(m, n, k) { };
Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed). Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table.   Example 1: Input: m = 3, n = 3, k = 5 Output: 3 Explanation: The 5th smallest number is 3. Example 2: Input: m = 2, n = 3, k = 6 Output: 6 Explanation: The 6th smallest number is 6.   Constraints: 1 <= m, n <= 3 * 104 1 <= k <= m * n
Hard
[ "math", "binary-search" ]
[ "const findKthNumber = function(m, n, k) {\n let left = 1;\n let right = m * n;\n while (left < right) {\n const mid = Math.floor((left + right) / 2);\n const nSmaller = count(m, n, mid);\n if (nSmaller >= k) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n return left;\n};\n\nfunction count(m, n, target) {\n let nSmaller = 0;\n let j = n;\n for (let i = 1; i <= m; i++) {\n while (i * j > target) {\n j -= 1;\n }\n nSmaller += j;\n }\n return nSmaller;\n}", "const findKthNumber = function(m, n, k) {\n let left = 1;\n let right = m * n;\n while (left < right) {\n const mid = Math.floor((left + right) / 2);\n const num = count(m, n, mid);\n if (num < k) left = mid + 1;\n else right = mid;\n }\n return left;\n};\n\nfunction count(m, n, target) {\n let res = 0;\n let j = n;\n for (let i = 1; i <= m; i++) {\n while (i * j > target) j--\n res += j;\n }\n return res;\n}" ]