Datasets:

QID
int64
1
2.85k
titleSlug
stringlengths
3
77
Hints
sequence
Code
stringlengths
80
1.34k
Body
stringlengths
190
4.55k
Difficulty
stringclasses
3 values
Topics
sequence
Definitions
stringclasses
14 values
Solutions
sequence
891
sum-of-subsequence-widths
[]
/** * @param {number[]} nums * @return {number} */ var sumSubseqWidths = function(nums) { };
The width of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].   Example 1: Input: nums = [2,1,3] Output: 6 Explanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6. Example 2: Input: nums = [2] Output: 0   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105
Hard
[ "array", "math", "sorting" ]
[ "const sumSubseqWidths = function(A) {\n A.sort((a, b) => a - b)\n let c = 1, res = 0, mod = 10 ** 9 + 7\n for (let i = 0, n = A.length; i < n; i++, c = c * 2 % mod) {\n res = (res + A[i] * c - A[n - i - 1] * c) % mod;\n }\n return (res + mod) % mod;\n};" ]
892
surface-area-of-3d-shapes
[]
/** * @param {number[][]} grid * @return {number} */ var surfaceArea = function(grid) { };
You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j). After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return the total surface area of the resulting shapes. Note: The bottom face of each shape counts toward its surface area.   Example 1: Input: grid = [[1,2],[3,4]] Output: 34 Example 2: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 32 Example 3: Input: grid = [[2,2,2],[2,1,2],[2,2,2]] Output: 46   Constraints: n == grid.length == grid[i].length 1 <= n <= 50 0 <= grid[i][j] <= 50
Easy
[ "array", "math", "geometry", "matrix" ]
[ "const surfaceArea = function(grid) {\n if(grid == null || grid.length === 0) return 0\n const m = grid.length, n = grid[0].length\n let res = 0, adj = 0\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n const h = grid[i][j]\n if(h) res += h * 4 + 2\n if(j > 0) {\n if(grid[i][j - 1]) adj += Math.min(h, grid[i][j - 1])\n }\n if(i > 0) {\n if(grid[i - 1][j]) adj += Math.min(h, grid[i - 1][j])\n }\n // console.log(adj)\n }\n }\n \n return res - adj * 2\n};\n\n// 2 * 4 + 2\n// 6 + 10 + 14 + 18 - (1 + 2 + 3 + 1) * 2" ]
893
groups-of-special-equivalent-strings
[]
/** * @param {string[]} words * @return {number} */ var numSpecialEquivGroups = function(words) { };
You are given an array of strings of the same length words. In one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i]. Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j]. For example, words[i] = "zzxy" and words[j] = "xyzz" are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz". A group of special-equivalent strings from words is a non-empty subset of words such that: Every pair of strings in the group are special equivalent, and The group is the largest size possible (i.e., there is not a string words[i] not in the group such that words[i] is special-equivalent to every string in the group). Return the number of groups of special-equivalent strings from words.   Example 1: Input: words = ["abcd","cdab","cbad","xyzz","zzxy","zzyx"] Output: 3 Explanation: One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are ["xyzz", "zzxy"] and ["zzyx"]. Note that in particular, "zzxy" is not special equivalent to "zzyx". Example 2: Input: words = ["abc","acb","bac","bca","cab","cba"] Output: 3   Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 20 words[i] consist of lowercase English letters. All the strings are of the same length.
Medium
[ "array", "hash-table", "string" ]
[ "const numSpecialEquivGroups = function(A) {\n return new Set(\n A.map(word =>\n [...word]\n .reduce((counter, c, i) => {\n counter[c.charCodeAt(0) - \"a\".charCodeAt(0) + 26 * (i % 2)]++;\n return counter;\n }, new Array(52).fill(0))\n .join(\"-\")\n )\n ).size;\n};", "const numSpecialEquivGroups = function(A) {\n const result = new Set();\n for (let i of A) {\n let arr = i.split(\"\");\n let res = [[], []];\n for (let j = 0; j < arr.length; j++) {\n res[j & 1].push(arr[j]);\n }\n result.add(res[0].sort().join(\"\") + res[1].sort().join(\"\"));\n }\n return result.size;\n};" ]
894
all-possible-full-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 {number} n * @return {TreeNode[]} */ var allPossibleFBT = function(n) { };
Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0. Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order. A full binary tree is a binary tree where each node has exactly 0 or 2 children.   Example 1: Input: n = 7 Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]] Example 2: Input: n = 3 Output: [[0,0,0]]   Constraints: 1 <= n <= 20
Medium
[ "dynamic-programming", "tree", "recursion", "memoization", "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 allPossibleFBT = function(N) {\n if (N <= 0) return []\n const dp = Array.from({ length: N + 1 }, () => [])\n dp[1].push(new TreeNode(0))\n\n for (let numNode = 1; numNode <= N; numNode += 2) {\n for (let leftNode = 1; leftNode < numNode; leftNode += 2) {\n for (let left of dp[leftNode]) {\n for (let right of dp[numNode - 1 - leftNode]) {\n let root = new TreeNode(0)\n root.left = left\n root.right = right\n dp[numNode].push(root)\n }\n }\n }\n }\n return dp[N]\n};" ]
895
maximum-frequency-stack
[]
var FreqStack = function() { }; /** * @param {number} val * @return {void} */ FreqStack.prototype.push = function(val) { }; /** * @return {number} */ FreqStack.prototype.pop = function() { }; /** * Your FreqStack object will be instantiated and called as such: * var obj = new FreqStack() * obj.push(val) * var param_2 = obj.pop() */
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class: FreqStack() constructs an empty frequency stack. void push(int val) pushes an integer val onto the top of the stack. int pop() removes and returns the most frequent element in the stack. If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.   Example 1: Input ["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"] [[], [5], [7], [5], [7], [4], [5], [], [], [], []] Output [null, null, null, null, null, null, null, 5, 7, 5, 4] Explanation FreqStack freqStack = new FreqStack(); freqStack.push(5); // The stack is [5] freqStack.push(7); // The stack is [5,7] freqStack.push(5); // The stack is [5,7,5] freqStack.push(7); // The stack is [5,7,5,7] freqStack.push(4); // The stack is [5,7,5,7,4] freqStack.push(5); // The stack is [5,7,5,7,4,5] freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4]. freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4]. freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4]. freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].   Constraints: 0 <= val <= 109 At most 2 * 104 calls will be made to push and pop. It is guaranteed that there will be at least one element in the stack before calling pop.
Hard
[ "hash-table", "stack", "design", "ordered-set" ]
[ "const FreqStack = function() {\n this.stack = Array.from({length: 10001}, () => [])\n this.maxf = 0\n this.freq = {}\n};\n\n\nFreqStack.prototype.push = function(x) {\n if(!this.freq[x]) this.freq[x] = 0\n this.freq[x]++\n if(this.freq[x] > this.maxf) this.maxf = this.freq[x]\n this.stack[this.freq[x]].push(x)\n};\n\n\nFreqStack.prototype.pop = function() {\n let res = this.stack[this.maxf].pop()\n if(this.stack[this.maxf].length === 0) this.maxf--\n this.freq[res]--\n return res\n};" ]
896
monotonic-array
[]
/** * @param {number[]} nums * @return {boolean} */ var isMonotonic = function(nums) { };
An array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j]. Given an integer array nums, return true if the given array is monotonic, or false otherwise.   Example 1: Input: nums = [1,2,2,3] Output: true Example 2: Input: nums = [6,5,4,4] Output: true Example 3: Input: nums = [1,3,2] Output: false   Constraints: 1 <= nums.length <= 105 -105 <= nums[i] <= 105
Easy
[ "array" ]
[ "const isMonotonic = function(nums) {\n return inc(nums) || dec(nums)\n};\n\nfunction inc(nums) {\n if(nums == null || nums.length <= 1) return true\n for(let i = 1, n = nums.length; i < n; i++) {\n if(nums[i] < nums[i - 1]) return false\n }\n return true \n}\nfunction dec(nums) {\n if(nums == null || nums.length <= 1) return true\n for(let i = 1, n = nums.length; i < n; i++) {\n if(nums[i] > nums[i - 1]) return false\n }\n return true \n}", "const isMonotonic = function(nums) {\n let inc = true, dec = true\n for(let i = 1, n = nums.length; i < n; i++) {\n inc &= nums[i] >= nums[i - 1]\n dec &= nums[i] <= nums[i - 1]\n }\n return inc || dec\n};" ]
897
increasing-order-search-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {TreeNode} */ var increasingBST = function(root) { };
Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.   Example 1: Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9] Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] Example 2: Input: root = [5,1,7] Output: [1,null,5,null,7]   Constraints: The number of nodes in the given tree will be in the range [1, 100]. 0 <= Node.val <= 1000
Easy
[ "stack", "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 increasingBST = function(root) {\n return helper(root, null)\n};\n\nfunction helper(node, tail) {\n if(node == null) return tail\n const res = helper(node.left, node)\n node.left = null\n node.right = helper(node.right, tail)\n return res\n}" ]
898
bitwise-ors-of-subarrays
[]
/** * @param {number[]} arr * @return {number} */ var subarrayBitwiseORs = function(arr) { };
Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: arr = [0] Output: 1 Explanation: There is only one possible result: 0. Example 2: Input: arr = [1,1,2] Output: 3 Explanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2]. These yield the results 1, 1, 2, 1, 3, 3. There are 3 unique values, so the answer is 3. Example 3: Input: arr = [1,2,4] Output: 6 Explanation: The possible results are 1, 2, 3, 4, 6, and 7.   Constraints: 1 <= arr.length <= 5 * 104 0 <= arr[i] <= 109
Medium
[ "array", "dynamic-programming", "bit-manipulation" ]
[ "const subarrayBitwiseORs = function(A) {\n let cur = new Set()\n const ans = new Set()\n \n for (let i = 0; i < A.length; i++) {\n const item = A[i]\n const x = new Set()\n for (let e of cur.values()) {\n x.add(e | item)\n }\n x.add(item)\n cur = x\n for (let sub of cur.values()) {\n ans.add(sub)\n }\n }\n return ans.size\n};" ]
899
orderly-queue
[]
/** * @param {string} s * @param {number} k * @return {string} */ var orderlyQueue = function(s, k) { };
You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string. Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.   Example 1: Input: s = "cba", k = 1 Output: "acb" Explanation: In the first move, we move the 1st character 'c' to the end, obtaining the string "bac". In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb". Example 2: Input: s = "baaca", k = 3 Output: "aaabc" Explanation: In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab". In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc".   Constraints: 1 <= k <= s.length <= 1000 s consist of lowercase English letters.
Hard
[ "math", "string", "sorting" ]
[ "const orderlyQueue = function (S, K) {\n if (K === 0) return S\n else if (K > 1) return S.split('').sort().join('')\n let result = 0,\n L = S.length\n for (let i = 1; i < L; i++) {\n for (let j = 0; j < L; j++) {\n let d = S.charCodeAt((result + j) % L) - S.charCodeAt((i + j) % L)\n if (d !== 0) {\n if (d > 0) result = i\n break\n }\n }\n }\n return S.slice(result) + S.slice(0, result)\n}" ]
900
rle-iterator
[]
/** * @param {number[]} encoding */ var RLEIterator = function(encoding) { }; /** * @param {number} n * @return {number} */ RLEIterator.prototype.next = function(n) { }; /** * Your RLEIterator object will be instantiated and called as such: * var obj = new RLEIterator(encoding) * var param_1 = obj.next(n) */
We can use run-length encoding (i.e., RLE) to encode a sequence of integers. In a run-length encoded array of even length encoding (0-indexed), for all even i, encoding[i] tells us the number of times that the non-negative integer value encoding[i + 1] is repeated in the sequence. For example, the sequence arr = [8,8,8,5,5] can be encoded to be encoding = [3,8,2,5]. encoding = [3,8,0,9,2,5] and encoding = [2,8,1,8,2,5] are also valid RLE of arr. Given a run-length encoded array, design an iterator that iterates through it. Implement the RLEIterator class: RLEIterator(int[] encoded) Initializes the object with the encoded array encoded. int next(int n) Exhausts the next n elements and returns the last element exhausted in this way. If there is no element left to exhaust, return -1 instead.   Example 1: Input ["RLEIterator", "next", "next", "next", "next"] [[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]] Output [null, 8, 8, 5, -1] Explanation RLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5]. rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5]. rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5]. rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5]. rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5, but the second term did not exist. Since the last term exhausted does not exist, we return -1.   Constraints: 2 <= encoding.length <= 1000 encoding.length is even. 0 <= encoding[i] <= 109 1 <= n <= 109 At most 1000 calls will be made to next.
Medium
[ "array", "design", "counting", "iterator" ]
null
[]
901
online-stock-span
[]
var StockSpanner = function() { }; /** * @param {number} price * @return {number} */ StockSpanner.prototype.next = function(price) { }; /** * Your StockSpanner object will be instantiated and called as such: * var obj = new StockSpanner() * var param_1 = obj.next(price) */
Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day. The span of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day. For example, if the prices of the stock in the last four days is [7,2,1,2] and the price of the stock today is 2, then the span of today is 4 because starting from today, the price of the stock was less than or equal 2 for 4 consecutive days. Also, if the prices of the stock in the last four days is [7,34,1,2] and the price of the stock today is 8, then the span of today is 3 because starting from today, the price of the stock was less than or equal 8 for 3 consecutive days. Implement the StockSpanner class: StockSpanner() Initializes the object of the class. int next(int price) Returns the span of the stock's price given that today's price is price.   Example 1: Input ["StockSpanner", "next", "next", "next", "next", "next", "next", "next"] [[], [100], [80], [60], [70], [60], [75], [85]] Output [null, 1, 1, 1, 2, 1, 4, 6] Explanation StockSpanner stockSpanner = new StockSpanner(); stockSpanner.next(100); // return 1 stockSpanner.next(80); // return 1 stockSpanner.next(60); // return 1 stockSpanner.next(70); // return 2 stockSpanner.next(60); // return 1 stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. stockSpanner.next(85); // return 6   Constraints: 1 <= price <= 105 At most 104 calls will be made to next.
Medium
[ "stack", "design", "monotonic-stack", "data-stream" ]
[ "const StockSpanner = function() {\n this.values = []\n}\n\n\nStockSpanner.prototype.next = function(price) {\n let count = 1\n while (\n this.values.length > 0 &&\n this.values[this.values.length - 1][0] <= price\n ) {\n count += this.values.pop()[1]\n }\n this.values.push([price, count])\n return count\n}" ]
902
numbers-at-most-n-given-digit-set
[]
/** * @param {string[]} digits * @param {number} n * @return {number} */ var atMostNGivenDigitSet = function(digits, n) { };
Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'. Return the number of positive integers that can be generated that are less than or equal to a given integer n.   Example 1: Input: digits = ["1","3","5","7"], n = 100 Output: 20 Explanation: The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. Example 2: Input: digits = ["1","4","9"], n = 1000000000 Output: 29523 Explanation: We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. Example 3: Input: digits = ["7"], n = 8 Output: 1   Constraints: 1 <= digits.length <= 9 digits[i].length == 1 digits[i] is a digit from '1' to '9'. All the values in digits are unique. digits is sorted in non-decreasing order. 1 <= n <= 109
Hard
[ "array", "math", "string", "binary-search", "dynamic-programming" ]
[ "const atMostNGivenDigitSet = function(digits, n) {\n const str = '' + n, { pow } = Math\n const len = str.length, dsize = digits.length\n let res = 0\n \n for(let i = 1; i < len; i++) {\n res += pow(dsize, i)\n }\n \n for(let i = 0; i < len; i++) {\n let sameNum = false\n for(const d of digits) {\n if(+d < +str[i]) {\n res += pow(dsize, len - i - 1)\n } else if(+d === +str[i]) sameNum = true\n }\n if(sameNum === false) return res\n }\n \n return res + 1\n};" ]
903
valid-permutations-for-di-sequence
[]
/** * @param {string} s * @return {number} */ var numPermsDISequence = function(s) { };
You are given a string s of length n where s[i] is either: 'D' means decreasing, or 'I' means increasing. A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i: If s[i] == 'D', then perm[i] > perm[i + 1], and If s[i] == 'I', then perm[i] < perm[i + 1]. Return the number of valid permutations perm. Since the answer may be large, return it modulo 109 + 7.   Example 1: Input: s = "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0) Example 2: Input: s = "D" Output: 1   Constraints: n == s.length 1 <= n <= 200 s[i] is either 'I' or 'D'.
Hard
[ "string", "dynamic-programming", "prefix-sum" ]
[ "const numPermsDISequence = function(s) {\n const mod = 1e9 + 7\n const n = s.length\n const dp = Array.from({ length: n + 1 }, () => Array(n + 1).fill(0))\n s = '#' + s\n dp[0][0] = 1\n for(let i = 1; i <= n; i++) {\n const ch = s[i]\n for(let j = 0; j <= i; j++) {\n if(ch === 'I') {\n for(let k = 0; k < j; k++) {\n dp[i][j] += dp[i - 1][k]\n dp[i][j] %= mod\n }\n } else {\n for(let k = j; k < i; k++) {\n dp[i][j] += dp[i - 1][k]\n dp[i][j] %= mod\n }\n }\n }\n }\n \n \n let res = 0\n \n for(let i = 0; i <= n; i++) {\n res = (res + dp[n][i]) % mod\n }\n \n return res\n};", "const numPermsDISequence = function(s) {\n const n = s.length, mod = 1e9 + 7\n const dp = Array.from({ length: n + 1}, () => Array(n + 1).fill(0))\n dp[0][0] = 1\n for(let i = 1; i <= n; i++) {\n for(let j = 0; j <= i; j++) {\n if(s[i - 1] === 'D') {\n for(let k = j; k <= i - 1; k++) {\n dp[i][j] = (dp[i][j] + dp[i - 1][k]) % mod\n }\n } else {\n for(let k = 0; k < j; k++) {\n dp[i][j] = (dp[i][j] + dp[i - 1][k]) % mod\n }\n }\n }\n }\n let res = 0\n for(let i = 0; i <= n; i++) {\n res = (res + dp[n][i]) % mod\n }\n \n return res\n};", "const numPermsDISequence = function(S) {\n let n = S.length,\n mod = 10 ** 9 + 7\n const dp = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(0))\n for (let j = 0; j <= n; j++) dp[0][j] = 1\n for (let i = 0; i < n; i++)\n if (S.charAt(i) === 'I')\n for (let j = 0, cur = 0; j < n - i; j++)\n dp[i + 1][j] = cur = (cur + dp[i][j]) % mod\n else\n for (let j = n - i - 1, cur = 0; j >= 0; j--)\n dp[i + 1][j] = cur = (cur + dp[i][j + 1]) % mod\n return dp[n][0]\n}" ]
904
fruit-into-baskets
[]
/** * @param {number[]} fruits * @return {number} */ var totalFruit = function(fruits) { };
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold. Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array fruits, return the maximum number of fruits you can pick.   Example 1: Input: fruits = [1,2,1] Output: 3 Explanation: We can pick from all 3 trees. Example 2: Input: fruits = [0,1,2,2] Output: 3 Explanation: We can pick from trees [1,2,2]. If we had started at the first tree, we would only pick from trees [0,1]. Example 3: Input: fruits = [1,2,3,2,2] Output: 4 Explanation: We can pick from trees [2,3,2,2]. If we had started at the first tree, we would only pick from trees [1,2].   Constraints: 1 <= fruits.length <= 105 0 <= fruits[i] < fruits.length
Medium
[ "array", "hash-table", "sliding-window" ]
[ "const totalFruit = function (fruits) {\n let n = fruits.length\n let i = 0, j = 0\n const map = new Map()\n let res = 0\n for(;j < n; j++) {\n const e = fruits[j]\n if(!map.has(e)) map.set(e, 1)\n else map.set(e, map.get(e) + 1)\n\n while(map.size > 2 && i < n) {\n const tmp = fruits[i++]\n map.set(tmp, map.get(tmp) - 1)\n if(map.get(tmp) === 0) {\n map.delete(tmp)\n }\n }\n res = Math.max(res, j - i + 1)\n }\n\n return res\n}" ]
905
sort-array-by-parity
[]
/** * @param {number[]} nums * @return {number[]} */ var sortArrayByParity = function(nums) { };
Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition.   Example 1: Input: nums = [3,1,2,4] Output: [2,4,3,1] Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. Example 2: Input: nums = [0] Output: [0]   Constraints: 1 <= nums.length <= 5000 0 <= nums[i] <= 5000
Easy
[ "array", "two-pointers", "sorting" ]
[ "const sortArrayByParity = function(A) {\n for(let i = 0, len = A.length; i < len;) {\n if(A[i] % 2 !== 0) {\n A.push(A[i])\n A.splice(i, 1)\n len--\n } else {\n i++\n }\n }\n return A\n}; " ]
906
super-palindromes
[]
/** * @param {string} left * @param {string} right * @return {number} */ var superpalindromesInRange = function(left, right) { };
Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].   Example 1: Input: left = "4", right = "1000" Output: 4 Explanation: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome. Example 2: Input: left = "1", right = "2" Output: 1   Constraints: 1 <= left.length, right.length <= 18 left and right consist of only digits. left and right cannot have leading zeros. left and right represent integers in the range [1, 1018 - 1]. left is less than or equal to right.
Hard
[ "math", "enumeration" ]
[ "const superpalindromesInRange = function (L, R) {\n // My idea was to take the root of L and R and then generate all palindromes between those numbers,\n // and then put those palindromes to power 2 and check if those are palindrome as well.\n\n // The generation of palindromes is done like this:\n // Lets say i want all palindromes of length 4, then i take all numbers of length 2.\n // I reverse the length 2 numbers and concatenate them with themselves.\n // So \"19\" becomes \"19\" + \"91\". For odd length I do the same,\n //\tbut put a for loop around them that puts nrs 0 - 9 inside them.\n // So \"19\" + \"0\" + \"91\", then \"19\" + \"1\" + \"91\", etc.\n\n // Next I loop through the generated palindromes and just check whether they are\n // inside sqrt(L) and sqrt(R). (sqrt(L) < palin < sqrt(R))\n // For every palin within sqrt(L) and sqrt(R), i put the palin to power 2\n // (with BigInt!) and then check if that is a palindrome. If so, then count++;\n\n const sqL = Math.sqrt(L)\n const sqR = Math.sqrt(R)\n const sqR_Length = parseInt(sqR).toString(10).length\n // counting the valid super-palindromes\n let palins = 0\n // L is a superpalindrome\n if (\n isPalindrome(L) &&\n sqL === parseInt(sqL) &&\n isPalindrome(sqL.toString(10))\n )\n palins++\n // R is a superpalindrome\n if (\n isPalindrome(R) &&\n sqR === parseInt(sqR) &&\n isPalindrome(sqR.toString(10))\n )\n palins++\n\n let end\n if (sqR === parseInt(sqR)) {\n // or else the loop will possibly add R as well\n end = parseInt(sqR) - 1\n } else {\n end = parseInt(Math.floor(sqR))\n }\n\n let begin\n if (sqL === parseInt(sqL)) {\n // or else the loop will possibly add R as well\n begin = parseInt(sqL) + 1\n } else {\n begin = parseInt(Math.ceil(sqL))\n }\n\n // account for superpalins with for single digit 'sub-palins'\n if (begin <= 1 && end >= 1) palins++ // 1\n if (begin <= 2 && end >= 2) palins++ // 4\n if (begin <= 3 && end >= 3) palins++ // 9\n const length = sqR_Length\n const even = length % 2 === 0\n const half = Math.floor(length / 2)\n const pow10Half = Math.pow(10, half) // 10 or 100 or 1000, etc\n const pow10HalfMinOne = Math.pow(10, half - 1)\n let pal = '' // init\n let palinStr = '' // init\n let palin = -1 // init\n for (let i = 1, leni = pow10Half; i < leni; i++) {\n pal = i.toString(10)\n pal.padStart(half - pal.length, '0')\n palReverse = reverseStr(pal)\n // generate even length palindrome\n palinStr = pal + palReverse\n palin = parseInt(palinStr)\n if (palin >= begin && palin <= end) {\n if (isPalindromeInt(BigInt(palin) * BigInt(palin))) {\n palins++\n }\n }\n // If I generate all palindromes up until some even length,\n // lets say 4, then last step is to do length 2 + length 2 (19 + 91),\n // and not the 19 + 0 + 91 step that generates odd length palindromes.\n if (even && i >= pow10HalfMinOne) {\n continue\n }\n for (let j = 0, lenj = 10; j < lenj; j++) {\n // generate odd length palindrome\n palinStr = pal + j + palReverse\n palin = parseInt(palinStr)\n if (palin >= begin && palin <= end) {\n if (isPalindromeInt(BigInt(palin) * BigInt(palin))) {\n palins++\n }\n }\n }\n }\n return palins\n}\n\nconst reverseStr = function (str) {\n return str.split('').reverse().join('')\n}\n\nconst isPalindromeInt = function (nr) {\n nr = nr.toString(10)\n return nr === nr.split('').reverse().join('')\n}\nconst isPalindrome = function (nr) {\n return nr === nr.split('').reverse().join('')\n}", " const superpalindromesInRange = function(left, right) {\n const palindromes = []\n let res = 0\n for(let i = 1; i < 10; i++) {\n palindromes.push(`${i}`)\n }\n for(let i = 1; i < 1e4; i++) {\n let l = `${i}`, r = l.split('').reverse().join('')\n palindromes.push(`${l}${r}`)\n for(let j = 0; j < 10; j++) {\n palindromes.push(`${l}${j}${r}`)\n }\n }\n\n for(let p of palindromes) {\n const square = BigInt(p) * BigInt(p)\n if(!isPalindrome(`${square}`)) continue\n if(BigInt(left) <= square && square <= BigInt(right)) res++ \n }\n\n return res\n\n function isPalindrome(str) {\n let i = 0;\n let j = str.length - 1;\n while (i < j) {\n if (str.charAt(i) !== str.charAt(j)) {\n return false;\n }\n i++;\n j--;\n }\n return true;\n }\n};", "const superpalindromesInRange = function (left, right) {\n let ans = 9 >= left && 9 <= right ? 1 : 0\n\n const isPal = (str) => {\n for (let i = 0, j = str.length - 1; i < j; i++, j--)\n if (str.charAt(i) !== str.charAt(j)) return false\n return true\n }\n\n for (let dig = 1; dig < 10; dig++) {\n let isOdd = dig % 2 && dig !== 1,\n innerLen = (dig >> 1) - 1,\n innerLim = Math.max(1, 2 ** innerLen),\n midPos = dig >> 1,\n midLim = isOdd ? 3 : 1\n for (let edge = 1; edge < 3; edge++) {\n let pal = new Uint8Array(dig)\n ;(pal[0] = edge), (pal[dig - 1] = edge)\n if (edge === 2) (innerLim = 1), (midLim = Math.min(midLim, 2))\n for (let inner = 0; inner < innerLim; inner++) {\n if (inner > 0) {\n let innerStr = inner.toString(2).padStart(innerLen, '0')\n for (let i = 0; i < innerLen; i++)\n (pal[1 + i] = innerStr[i]), (pal[dig - 2 - i] = innerStr[i])\n }\n for (let mid = 0; mid < midLim; mid++) {\n if (isOdd) pal[midPos] = mid\n let palin = ~~pal.join(''),\n square = BigInt(palin) * BigInt(palin)\n if (square > right) return ans\n if (square >= left && isPal(square.toString())) ans++\n }\n }\n }\n }\n return ans\n}" ]
907
sum-of-subarray-minimums
[]
/** * @param {number[]} arr * @return {number} */ var sumSubarrayMins = function(arr) { };
Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.   Example 1: Input: arr = [3,1,2,4] Output: 17 Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17. Example 2: Input: arr = [11,81,94,43,3] Output: 444   Constraints: 1 <= arr.length <= 3 * 104 1 <= arr[i] <= 3 * 104
Medium
[ "array", "dynamic-programming", "stack", "monotonic-stack" ]
[ " const sumSubarrayMins = function (arr) {\n const n = arr.length\n const mod = 1e9 + 7, stk = []\n const left = Array(n), right = Array(n)\n for(let i = 0; i< n; i++) {\n left[i] = i + 1\n right[i] = n - i\n }\n let res = 0\n for(let i = 0; i < n; i++) {\n while(stk.length && arr[stk[stk.length - 1]] > arr[i]) {\n const idx = stk.pop()\n right[idx] = i - idx\n }\n if (stk.length) left[i] = i - stk[stk.length - 1]\n stk.push(i)\n \n }\n for(let i = 0; i < n; i++) {\n res = (res + arr[i] * left[i] * right[i]) % mod\n }\n \n return res\n}\n ", "const sumSubarrayMins = function (arr) {\n const n = arr.length,\n s1 = [],\n s2 = [],\n left = Array(n),\n right = Array(n)\n for (let i = 0; i < n; i++) {\n let cnt = 1\n while (s1.length && s1[s1.length - 1][0] > arr[i]) {\n cnt += s1.pop()[1]\n }\n left[i] = cnt\n s1.push([arr[i], cnt])\n }\n\n for (let i = n - 1; i >= 0; i--) {\n let cnt = 1\n while (s2.length && s2[s2.length - 1][0] >= arr[i]) {\n cnt += s2.pop()[1]\n }\n right[i] = cnt\n s2.push([arr[i], cnt])\n }\n let res = 0\n const mod = 1e9 + 7\n for (let i = 0; i < n; i++) {\n // left[i] number of starting positions\n // right[i] number of ending positions\n res = (res + arr[i] * left[i] * right[i]) % mod\n }\n\n return res\n}" ]
908
smallest-range-i
[]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var smallestRangeI = function(nums, k) { };
You are given an integer array nums and an integer k. In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i. The score of nums is the difference between the maximum and minimum elements in nums. Return the minimum score of nums after applying the mentioned operation at most once for each index in it.   Example 1: Input: nums = [1], k = 0 Output: 0 Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0. Example 2: Input: nums = [0,10], k = 2 Output: 6 Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. Example 3: Input: nums = [1,3,6], k = 3 Output: 0 Explanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.   Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 104 0 <= k <= 104
Easy
[ "array", "math" ]
[ "const smallestRangeI = function(nums, k) {\n let min = Infinity, max = -Infinity\n for(let e of nums) {\n min = Math.min(min, e)\n max = Math.max(max, e)\n }\n return max - k >= min + k ? max - k - (min + k) : 0\n};" ]
909
snakes-and-ladders
[]
/** * @param {number[][]} board * @return {number} */ var snakesAndLadders = function(board) { };
You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row. You start on square 1 of the board. In each move, starting from square curr, do the following: Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)]. This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board. If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next. The game ends when you reach the square n2. A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 do not have a snake or ladder. Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder. For example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4. Return the least number of moves required to reach the square n2. If it is not possible to reach the square, return -1.   Example 1: Input: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]] Output: 4 Explanation: In the beginning, you start at square 1 (at row 5, column 0). You decide to move to square 2 and must take the ladder to square 15. You then decide to move to square 17 and must take the snake to square 13. You then decide to move to square 14 and must take the ladder to square 35. You then decide to move to square 36, ending the game. This is the lowest possible number of moves to reach the last square, so return 4. Example 2: Input: board = [[-1,-1],[-1,3]] Output: 1   Constraints: n == board.length == board[i].length 2 <= n <= 20 board[i][j] is either -1 or in the range [1, n2]. The squares labeled 1 and n2 do not have any ladders or snakes.
Medium
[ "array", "breadth-first-search", "matrix" ]
null
[]
910
smallest-range-ii
[]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var smallestRangeII = function(nums, k) { };
You are given an integer array nums and an integer k. For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k. The score of nums is the difference between the maximum and minimum elements in nums. Return the minimum score of nums after changing the values at each index.   Example 1: Input: nums = [1], k = 0 Output: 0 Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0. Example 2: Input: nums = [0,10], k = 2 Output: 6 Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. Example 3: Input: nums = [1,3,6], k = 3 Output: 3 Explanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.   Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 104 0 <= k <= 104
Medium
[ "array", "math", "greedy", "sorting" ]
[ "const smallestRangeII = function (nums, k) {\n let n = nums.length\n nums.sort((a, b) => a - b)\n // all elements plus k or minus k\n let res = nums[n - 1] - nums[0]\n\n // left side elements plus k, right side elements minus k\n let left = nums[0] + k, right = nums[n - 1] - k\n for(let i = 0; i < n - 1; i++) {\n const tmax = Math.max(right, nums[i] + k)\n const tmin = Math.min(left, nums[i + 1] - k)\n res = Math.min(res, tmax - tmin)\n }\n\n return res\n}" ]
911
online-election
[]
/** * @param {number[]} persons * @param {number[]} times */ var TopVotedCandidate = function(persons, times) { }; /** * @param {number} t * @return {number} */ TopVotedCandidate.prototype.q = function(t) { }; /** * Your TopVotedCandidate object will be instantiated and called as such: * var obj = new TopVotedCandidate(persons, times) * var param_1 = obj.q(t) */
You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i]. For each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the TopVotedCandidate class: TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays. int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules.   Example 1: Input ["TopVotedCandidate", "q", "q", "q", "q", "q", "q"] [[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]] Output [null, 0, 1, 1, 0, 0, 1] Explanation TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]); topVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1   Constraints: 1 <= persons.length <= 5000 times.length == persons.length 0 <= persons[i] < persons.length 0 <= times[i] <= 109 times is sorted in a strictly increasing order. times[0] <= t <= 109 At most 104 calls will be made to q.
Medium
[ "array", "hash-table", "binary-search", "design" ]
null
[]
912
sort-an-array
[]
/** * @param {number[]} nums * @return {number[]} */ var sortArray = function(nums) { };
Given an array of integers nums, sort the array in ascending order and return it. You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.   Example 1: Input: nums = [5,2,3,1] Output: [1,2,3,5] Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5). Example 2: Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5] Explanation: Note that the values of nums are not necessairly unique.   Constraints: 1 <= nums.length <= 5 * 104 -5 * 104 <= nums[i] <= 5 * 104
Medium
[ "array", "divide-and-conquer", "sorting", "heap-priority-queue", "merge-sort", "bucket-sort", "radix-sort", "counting-sort" ]
[ "function swap(items, l, r) {\n const temp = items[l];\n items[l] = items[r];\n items[r] = temp;\n}\nfunction partition(items, start, end) {\n let pivot = items[end], s = start\n for(let i = start; i < end; i++) {\n if(items[i] <= pivot) {\n swap(items, s, i)\n s++\n }\n }\n swap(items, s, end)\n return s\n}\n\nfunction quickSort(items, left, right) {\n if(left < right) {\n const pIdx = partition(items, left, right)\n quickSort(items, left, pIdx - 1)\n quickSort(items, pIdx + 1, right)\n }\n return items;\n}\nconst sortArray = function(nums) {\n return quickSort(nums, 0, nums.length - 1);\n};" ]
913
cat-and-mouse
[]
/** * @param {number[][]} graph * @return {number} */ var catMouseGame = function(graph) { };
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph. The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0. During each player's turn, they must travel along one edge of the graph that meets where they are.  For example, if the Mouse is at node 1, it must travel to any node in graph[1]. Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three ways: If ever the Cat occupies the same node as the Mouse, the Cat wins. If ever the Mouse reaches the Hole, the Mouse wins. If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. Given a graph, and assuming both players play optimally, return 1 if the mouse wins the game, 2 if the cat wins the game, or 0 if the game is a draw.   Example 1: Input: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]] Output: 0 Example 2: Input: graph = [[1,3],[0],[3],[0,2]] Output: 1   Constraints: 3 <= graph.length <= 50 1 <= graph[i].length < graph.length 0 <= graph[i][j] < graph.length graph[i][j] != i graph[i] is unique. The mouse and the cat can always move. 
Hard
[ "math", "dynamic-programming", "graph", "topological-sort", "memoization", "game-theory" ]
[ "const catMouseGame = function (g) {\n const n = g.length\n const win = Array(2)\n .fill(0)\n .map(() => Array(n * n).fill(0))\n for (let i = 0; i < n; i++) {\n win[0][i] = 1\n win[1][i] = 1\n }\n for (let i = 1; i < n; i++) {\n win[0][i * n + i] = 2\n win[1][i * n + i] = 2\n }\n\n while (true) {\n let anew = false\n for (let m = 0; m < n; m++) {\n inner: for (let c = 1; c < n; c++) {\n if (win[0][m * n + c] == 0) {\n let und = false\n for (let e of g[m]) {\n if (win[1][e * n + c] == 1) {\n win[0][m * n + c] = 1\n anew = true\n continue inner\n }\n if (win[1][e * n + c] == 0) {\n und = true\n }\n }\n if (!und) {\n win[0][m * n + c] = 2\n anew = true\n }\n }\n }\n }\n for (let c = 1; c < n; c++) {\n inner: for (let m = 0; m < n; m++) {\n if (win[1][m * n + c] == 0) {\n let und = false\n for (e of g[c]) {\n if (e == 0) continue\n if (win[0][m * n + e] == 2) {\n win[1][m * n + c] = 2\n anew = true\n continue inner\n }\n if (win[0][m * n + e] == 0) {\n und = true\n }\n }\n if (!und) {\n win[1][m * n + c] = 1\n anew = true\n }\n }\n }\n }\n if (!anew) break\n }\n\n return win[0][1 * n + 2]\n}" ]
914
x-of-a-kind-in-a-deck-of-cards
[]
/** * @param {number[]} deck * @return {boolean} */ var hasGroupsSizeX = function(deck) { };
You are given an integer array deck where deck[i] represents the number written on the ith card. Partition the cards into one or more groups such that: Each group has exactly x cards where x > 1, and All the cards in one group have the same integer written on them. Return true if such partition is possible, or false otherwise.   Example 1: Input: deck = [1,2,3,4,4,3,2,1] Output: true Explanation: Possible partition [1,1],[2,2],[3,3],[4,4]. Example 2: Input: deck = [1,1,1,2,2,2,3,3] Output: false Explanation: No possible partition.   Constraints: 1 <= deck.length <= 104 0 <= deck[i] < 104
Easy
[ "array", "hash-table", "math", "counting", "number-theory" ]
[ "const hasGroupsSizeX = function(deck) {\n if(deck == null || deck.length <= 1) return false\n const hash = {}\n for(let e of deck) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n let res = 0\n for(let k in hash) res = gcd(hash[k], res)\n return res > 1\n};\n\nfunction gcd(a, b) {\n return b ? gcd(b, a % b) : a\n}" ]
915
partition-array-into-disjoint-intervals
[]
/** * @param {number[]} nums * @return {number} */ var partitionDisjoint = function(nums) { };
Given an integer array nums, partition it into two (contiguous) subarrays left and right so that: Every element in left is less than or equal to every element in right. left and right are non-empty. left has the smallest possible size. Return the length of left after such a partitioning. Test cases are generated such that partitioning exists.   Example 1: Input: nums = [5,0,3,8,6] Output: 3 Explanation: left = [5,0,3], right = [8,6] Example 2: Input: nums = [1,1,1,0,6,12] Output: 4 Explanation: left = [1,1,1,0], right = [6,12]   Constraints: 2 <= nums.length <= 105 0 <= nums[i] <= 106 There is at least one valid answer for the given input.
Medium
[ "array" ]
[ "const partitionDisjoint = function(A) {\n let n = A.length;\n let maxLeft = A[0];\n let minRight = new Int32Array(n);\n let min = Infinity;\n for (let i = n - 1; i >= 1; i--) {\n min = Math.min(min, A[i]);\n minRight[i] = min;\n }\n \n for(let i = 1; i < n; i++){\n if (maxLeft <= minRight[i]){\n return i;\n }\n\n maxLeft = Math.max(maxLeft, A[i]); \n }\n};" ]
916
word-subsets
[]
/** * @param {string[]} words1 * @param {string[]} words2 * @return {string[]} */ var wordSubsets = function(words1, words2) { };
You are given two string arrays words1 and words2. A string b is a subset of string a if every letter in b occurs in a including multiplicity. For example, "wrr" is a subset of "warrior" but is not a subset of "world". A string a from words1 is universal if for every string b in words2, b is a subset of a. Return an array of all the universal strings in words1. You may return the answer in any order.   Example 1: Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"] Output: ["facebook","google","leetcode"] Example 2: Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"] Output: ["apple","google","leetcode"]   Constraints: 1 <= words1.length, words2.length <= 104 1 <= words1[i].length, words2[i].length <= 10 words1[i] and words2[i] consist only of lowercase English letters. All the strings of words1 are unique.
Medium
[ "array", "hash-table", "string" ]
[ "const wordSubsets = function(A, B) {\n function counter(s) {\n let count = Array(26).fill(0);\n for (let i = 0; i < s.length; i++) count[s.charCodeAt(i) - 97]++;\n return count;\n }\n let aux = Array(26).fill(0);\n let result = [];\n for (let i = 0; i < B.length; i++) {\n let count = counter(B[i]);\n for (let i = 0; i < 26; i++) {\n aux[i] = Math.max(aux[i], count[i]);\n }\n }\n for (let i = 0; i < A.length; i++) {\n let count = counter(A[i]);\n let flag = true;\n for (let j = 0; j < 26; j++) {\n if (aux[j] > 0 && count[j] - aux[j] < 0) {\n flag = false;\n break;\n }\n }\n if (flag) result.push(A[i]);\n }\n return result;\n};" ]
917
reverse-only-letters
[ "This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach." ]
/** * @param {string} s * @return {string} */ var reverseOnlyLetters = function(s) { };
Given a string s, reverse the string according to the following rules: All the characters that are not English letters remain in the same position. All the English letters (lowercase or uppercase) should be reversed. Return s after reversing it.   Example 1: Input: s = "ab-cd" Output: "dc-ba" Example 2: Input: s = "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba" Example 3: Input: s = "Test1ng-Leet=code-Q!" Output: "Qedo1ct-eeLg=ntse-T!"   Constraints: 1 <= s.length <= 100 s consists of characters with ASCII values in the range [33, 122]. s does not contain '\"' or '\\'.
Easy
[ "two-pointers", "string" ]
[ "const reverseOnlyLetters = function(S) {\n let start = 0\n let end = S.length - 1\n const arr = S.split(\"\")\n while (start < end) {\n while (start < end && !chk(S.charCodeAt(start))) {\n start++\n }\n while (start < end && !chk(S.charCodeAt(end))) {\n end--\n }\n\n let tmp = S[end]\n arr[end] = S[start]\n arr[start] = tmp\n start++\n end--\n }\n return arr.join(\"\")\n}\n\nfunction chk(num) {\n const aCode = \"a\".charCodeAt(0)\n const zCode = \"z\".charCodeAt(0)\n const ACode = \"A\".charCodeAt(0)\n const ZCode = \"Z\".charCodeAt(0)\n\n if ((num >= aCode && num <= zCode) || (num >= ACode && num <= ZCode)) {\n return true\n } else {\n return false\n }\n}" ]
918
maximum-sum-circular-subarray
[ "For those of you who are familiar with the <b>Kadane's algorithm</b>, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you already have a great algorithm brewing up in your mind in which case, go right ahead!", "What is an alternate way of representing a circular array so that it appears to be a straight array?\r\nEssentially, there are two cases of this problem that we need to take care of. Let's look at the figure below to understand those two cases:\r\n\r\n<br>\r\n<img src=\"https://assets.leetcode.com/uploads/2019/10/20/circular_subarray_hint_1.png\" width=\"700\"/>", "The first case can be handled by the good old Kadane's algorithm. However, is there a smarter way of going about handling the second case as well?" ]
/** * @param {number[]} nums * @return {number} */ var maxSubarraySumCircular = function(nums) { };
Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums. A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n]. A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n.   Example 1: Input: nums = [1,-2,3,-2] Output: 3 Explanation: Subarray [3] has maximum sum 3. Example 2: Input: nums = [5,-3,5] Output: 10 Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10. Example 3: Input: nums = [-3,-2,-3] Output: -2 Explanation: Subarray [-2] has maximum sum -2.   Constraints: n == nums.length 1 <= n <= 3 * 104 -3 * 104 <= nums[i] <= 3 * 104
Medium
[ "array", "divide-and-conquer", "dynamic-programming", "queue", "monotonic-queue" ]
[ "const maxSubarraySumCircular = function(A) {\n let minSum = Infinity, sum = 0, maxSum = -Infinity, curMax = 0, curMin = 0\n for(let a of A) {\n sum += a\n curMax = Math.max(curMax + a, a);\n maxSum = Math.max(maxSum, curMax);\n curMin = Math.min(curMin + a, a);\n minSum = Math.min(minSum, curMin);\n }\n return maxSum > 0 ? Math.max(maxSum, sum - minSum) : maxSum;\n};" ]
919
complete-binary-tree-inserter
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root */ var CBTInserter = function(root) { }; /** * @param {number} val * @return {number} */ CBTInserter.prototype.insert = function(val) { }; /** * @return {TreeNode} */ CBTInserter.prototype.get_root = function() { }; /** * Your CBTInserter object will be instantiated and called as such: * var obj = new CBTInserter(root) * var param_1 = obj.insert(val) * var param_2 = obj.get_root() */
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. Implement the CBTInserter class: CBTInserter(TreeNode root) Initializes the data structure with the root of the complete binary tree. int insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that the tree remains complete, and returns the value of the parent of the inserted TreeNode. TreeNode get_root() Returns the root node of the tree.   Example 1: Input ["CBTInserter", "insert", "insert", "get_root"] [[[1, 2]], [3], [4], []] Output [null, 1, 2, [1, 2, 3, 4]] Explanation CBTInserter cBTInserter = new CBTInserter([1, 2]); cBTInserter.insert(3); // return 1 cBTInserter.insert(4); // return 2 cBTInserter.get_root(); // return [1, 2, 3, 4]   Constraints: The number of nodes in the tree will be in the range [1, 1000]. 0 <= Node.val <= 5000 root is a complete binary tree. 0 <= val <= 5000 At most 104 calls will be made to insert and get_root.
Medium
[ "tree", "breadth-first-search", "design", "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) * } */
[ "var CBTInserter = function(root) {\n this.r = root\n};\n\n\nCBTInserter.prototype.insert = function(val) {\n let q = [this.r]\n \n while(q.length) {\n const tmp = []\n for(let i = 0; i < q.length; i++) {\n const cur = q[i]\n if(cur.left == null) {\n cur.left = new TreeNode(val)\n return cur.val\n } else tmp.push(cur.left)\n if(cur.right == null) {\n cur.right = new TreeNode(val)\n return cur.val\n } else tmp.push(cur.right)\n }\n \n q = tmp\n }\n};\n\n\nCBTInserter.prototype.get_root = function() {\n return this.r\n};" ]
920
number-of-music-playlists
[]
/** * @param {number} n * @param {number} goal * @param {number} k * @return {number} */ var numMusicPlaylists = function(n, goal, k) { };
Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: Every song is played at least once. A song can only be played again only if k other songs have been played. Given n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 109 + 7.   Example 1: Input: n = 3, goal = 3, k = 1 Output: 6 Explanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1]. Example 2: Input: n = 2, goal = 3, k = 0 Output: 6 Explanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2]. Example 3: Input: n = 2, goal = 3, k = 1 Output: 2 Explanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].   Constraints: 0 <= k < n <= goal <= 100
Hard
[ "math", "dynamic-programming", "combinatorics" ]
[ "const numMusicPlaylists = function (N, L, K) {\n const mod = 10 ** 9 + 7\n const dp = Array.from({ length: L + 1 }, () => Array(N + 1).fill(0))\n dp[0][0] = 1\n for (let i = 1; i <= L; i++) {\n for (let j = 1; j <= N; j++) {\n dp[i][j] = (dp[i - 1][j - 1] * (N - (j - 1))) % mod\n if (j > K) {\n dp[i][j] = (dp[i][j] + ((dp[i - 1][j] * (j - K)) % mod)) % mod\n }\n }\n }\n return dp[L][N]\n}" ]
921
minimum-add-to-make-parentheses-valid
[]
/** * @param {string} s * @return {number} */ var minAddToMakeValid = function(s) { };
A parentheses string is valid if and only if: It is the empty string, It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string. For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))". Return the minimum number of moves required to make s valid.   Example 1: Input: s = "())" Output: 1 Example 2: Input: s = "(((" Output: 3   Constraints: 1 <= s.length <= 1000 s[i] is either '(' or ')'.
Medium
[ "string", "stack", "greedy" ]
[ "const minAddToMakeValid = function(S) {\n if(S === '' || S == null) return 0\n const len = S.length\n const h = {\n o: 0,\n c: 0\n }\n for(let i = 0; i < len; i++) {\n if(S[i] === '(') {\n h.o++\n } else {\n if(h.o > 0) {\n h.o--\n } else {\n h.c++\n }\n }\n }\n \n return h.o + h.c\n};" ]
922
sort-array-by-parity-ii
[]
/** * @param {number[]} nums * @return {number[]} */ var sortArrayByParityII = function(nums) { };
Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition.   Example 1: Input: nums = [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Example 2: Input: nums = [2,3] Output: [2,3]   Constraints: 2 <= nums.length <= 2 * 104 nums.length is even. Half of the integers in nums are even. 0 <= nums[i] <= 1000   Follow Up: Could you solve it in-place?
Easy
[ "array", "two-pointers", "sorting" ]
[ "const sortArrayByParityII = function(A) {\n const res = []\n const odd = []\n const even = []\n for(let i = 0, len = A.length; i < len; i++) {\n if(A[i] % 2 === 0) even.push(A[i])\n else odd.push(A[i])\n }\n for(let i = 0, len = odd.length; i < len; i++) {\n res.push(even[i], odd[i])\n }\n return res\n};" ]
923
3sum-with-multiplicity
[]
/** * @param {number[]} arr * @param {number} target * @return {number} */ var threeSumMulti = function(arr, target) { };
Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target. As the answer can be very large, return it modulo 109 + 7.   Example 1: Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8 Output: 20 Explanation: Enumerating by the values (arr[i], arr[j], arr[k]): (1, 2, 5) occurs 8 times; (1, 3, 4) occurs 8 times; (2, 2, 4) occurs 2 times; (2, 3, 3) occurs 2 times. Example 2: Input: arr = [1,1,2,2,2,2], target = 5 Output: 12 Explanation: arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times: We choose one 1 from [1,1] in 2 ways, and two 2s from [2,2,2,2] in 6 ways. Example 3: Input: arr = [2,1,3], target = 6 Output: 1 Explanation: (1, 2, 3) occured one time in the array so we return 1.   Constraints: 3 <= arr.length <= 3000 0 <= arr[i] <= 100 0 <= target <= 300
Medium
[ "array", "hash-table", "two-pointers", "sorting", "counting" ]
[ "const threeSumMulti = function(A, target) {\n const d = {};\n let res = 0;\n const mod = Math.pow(10, 9) + 7;\n for (let i = 0; i < A.length; i++) {\n res += d[target - A[i]] >= 0 ? d[target - A[i]] : 0;\n res %= mod;\n for (let j = 0; j < i; j++) {\n d[A[i] + A[j]] = (d[A[i] + A[j]] || 0) + 1;\n }\n }\n return res % mod;\n};" ]
924
minimize-malware-spread
[]
/** * @param {number[][]} graph * @param {number[]} initial * @return {number} */ var minMalwareSpread = function(graph, initial) { };
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial. Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index. Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.   Example 1: Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1] Output: 0 Example 2: Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2] Output: 0 Example 3: Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2] Output: 1   Constraints: n == graph.length n == graph[i].length 2 <= n <= 300 graph[i][j] is 0 or 1. graph[i][j] == graph[j][i] graph[i][i] == 1 1 <= initial.length <= n 0 <= initial[i] <= n - 1 All the integers in initial are unique.
Hard
[ "hash-table", "depth-first-search", "breadth-first-search", "union-find", "graph" ]
[ "const minMalwareSpread = function (graph, initial) {\n const l = graph.length\n const p = []\n const children = []\n for (let i = 0; i < l; i++) {\n p[i] = i\n children[i] = [i]\n }\n\n for (let i = 0; i < l; i++) {\n for (let j = i + 1; j < l; j++) {\n if (graph[i][j] === 1) {\n const pi = find(i)\n const pj = find(j)\n if (pi !== pj) {\n union(pi, pj)\n }\n }\n }\n }\n\n initial.sort((a, b) => (a > b ? 1 : -1))\n\n const count = {}\n\n let index = initial[0]\n let max = 0\n // find the index that not unioned with other indexes and with the most number of children\n initial.forEach((e) => {\n const pe = find(e)\n if (!count[pe]) count[pe] = 0\n count[pe] += 1\n })\n initial.forEach((e, i) => {\n const pe = find(e)\n if (count[pe] === 1 && children[pe].length > max) {\n max = children[pe].length\n index = e\n }\n })\n\n return index\n\n function find(x) {\n while (p[x] !== x) {\n p[x] = p[p[x]]\n x = p[x]\n }\n return x\n }\n\n function union(pi, pj) {\n p[pj] = pi\n //also move the children to the new parent\n children[pi] = children[pi].concat(children[pj])\n children[pj] = []\n }\n}" ]
925
long-pressed-name
[]
/** * @param {string} name * @param {string} typed * @return {boolean} */ var isLongPressedName = function(name, typed) { };
Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times. You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.   Example 1: Input: name = "alex", typed = "aaleex" Output: true Explanation: 'a' and 'e' in 'alex' were long pressed. Example 2: Input: name = "saeed", typed = "ssaaedd" Output: false Explanation: 'e' must have been pressed twice, but it was not in the typed output.   Constraints: 1 <= name.length, typed.length <= 1000 name and typed consist of only lowercase English letters.
Easy
[ "two-pointers", "string" ]
[ "const isLongPressedName = function(name, typed) {\n let i = 0, m = name.length, n = typed.length\n for(let j = 0; j < n; j++) {\n if(i < m && name[i] === typed[j]) i++\n else if(j === 0 || typed[j] !== typed[j - 1]) return false\n }\n return i === m\n};" ]
926
flip-string-to-monotone-increasing
[]
/** * @param {string} s * @return {number} */ var minFlipsMonoIncr = function(s) { };
A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none). You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0. Return the minimum number of flips to make s monotone increasing.   Example 1: Input: s = "00110" Output: 1 Explanation: We flip the last digit to get 00111. Example 2: Input: s = "010110" Output: 2 Explanation: We flip to get 011111, or alternatively 000111. Example 3: Input: s = "00011000" Output: 2 Explanation: We flip to get 00000000.   Constraints: 1 <= s.length <= 105 s[i] is either '0' or '1'.
Medium
[ "string", "dynamic-programming" ]
[ "const minFlipsMonoIncr = function(s) {\n const n = s.length\n let res = 0, oneCnt = 0\n for(const e of s) {\n if(e === '1') oneCnt++\n else {\n const stayZero = oneCnt\n const flipToOne = res + 1\n res = Math.min(stayZero, flipToOne)\n }\n }\n \n return res\n};", "const minFlipsMonoIncr = function(s) {\n const n = s.length\n const arr = Array(n).fill(0)\n let oneCnt = 0\n for(let i = 0; i < n; i++) {\n if(s[i] === '1') oneCnt++\n arr[i] = oneCnt\n }\n const zeroCnt = n - oneCnt\n let res = Infinity\n \n for(let i = 0; i < n; i++) {\n const cnt = arr[i]\n const tmp = cnt + (zeroCnt - (i + 1 - cnt))\n res = Math.min(res, tmp)\n }\n res = Math.min(res, oneCnt, zeroCnt)\n return res\n};" ]
927
three-equal-parts
[]
/** * @param {number[]} arr * @return {number[]} */ var threeEqualParts = function(arr) { };
You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any [i, j] with i + 1 < j, such that: arr[0], arr[1], ..., arr[i] is the first part, arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part. All three parts have equal binary values. If it is not possible, return [-1, -1]. Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.   Example 1: Input: arr = [1,0,1,0,1] Output: [0,3] Example 2: Input: arr = [1,1,0,1,1] Output: [-1,-1] Example 3: Input: arr = [1,1,0,0,1] Output: [0,2]   Constraints: 3 <= arr.length <= 3 * 104 arr[i] is 0 or 1
Hard
[ "array", "math" ]
[ "const threeEqualParts = function (A) {\n let countNumberOfOnes = 0\n for (let c of A) if (c === 1) countNumberOfOnes++\n if (countNumberOfOnes === 0) return [0, A.length - 1]\n if (countNumberOfOnes % 3 != 0) return [-1, -1]\n const k = countNumberOfOnes / 3\n let i\n // find the first 1 in the array\n for (i = 0; i < A.length; i++) if (A[i] == 1) break\n let start = i\n // find (k+1)th 1 in the array\n let count1 = 0\n for (i = 0; i < A.length; i++) {\n if (A[i] == 1) count1++\n if (count1 == k + 1) break\n }\n let mid = i\n //find (2*k +1)th 1 in the array\n count1 = 0\n for (i = 0; i < A.length; i++) {\n if (A[i] === 1) count1++\n if (count1 === 2 * k + 1) break\n }\n let end = i\n // Match all values till the end of the array\n while (end < A.length && A[start] === A[mid] && A[mid] === A[end]) {\n start++\n mid++\n end++\n }\n // Return appropriate values if all the values have matched till the end\n if (end == A.length) return [start - 1, mid]\n // otherwise, no such indices found\n return [-1, -1]\n}" ]
928
minimize-malware-spread-ii
[]
/** * @param {number[][]} graph * @param {number[]} initial * @return {number} */ var minMalwareSpread = function(graph, initial) { };
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial, completely removing it and any connections from this node to any other node. Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.   Example 1: Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1] Output: 0 Example 2: Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1] Output: 1 Example 3: Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1] Output: 1   Constraints: n == graph.length n == graph[i].length 2 <= n <= 300 graph[i][j] is 0 or 1. graph[i][j] == graph[j][i] graph[i][i] == 1 1 <= initial.length < n 0 <= initial[i] <= n - 1 All the integers in initial are unique.
Hard
[ "hash-table", "depth-first-search", "breadth-first-search", "union-find", "graph" ]
[ "var minMalwareSpread = function (graph, initial) {\n const map = new Map() // node -> initial nodes infect this node\n for (let i of initial) {\n const visited = new Set(initial)\n const q = []\n q.push(i)\n while (q.length) {\n let cur = q.shift()\n for (let j = 0; j < graph[cur].length; j++) {\n if (graph[cur][j] == 1) {\n if (!visited.has(j)) {\n visited.add(j)\n q.push(j)\n\n if (map.get(j) == null) map.set(j, [])\n map.get(j).push(i)\n }\n }\n }\n }\n }\n\n const res = Array(graph.length).fill(0) // node -> safe nodes it infects\n for (let node of map.keys()) {\n if (map.get(node).length == 1) {\n let i = map.get(node)[0]\n res[i]++\n }\n }\n let max = 0\n let removed = -1\n for (let i = 0; i < res.length; i++) {\n if (res[i] > max) {\n max = res[i]\n removed = i\n }\n }\n initial.sort((a, b) => a - b)\n return removed == -1 ? initial[0] : removed\n}", "const minMalwareSpread = function (graph, initial) {\n const map = new Map(), n = graph.length\n for(let init of initial) {\n const visited = new Set(initial)\n const q = [init]\n while(q.length) {\n const cur = q.pop()\n for(let i = 0; i < n; i++) {\n if(graph[cur][i] === 1 && !visited.has(i)) {\n visited.add(i)\n q.push(i)\n if(map.get(i) == null) map.set(i, [])\n map.get(i).push(init)\n }\n } \n }\n }\n \n let res = 0, max = -1\n const arr = Array(n)\n for(let [k,v] of map) {\n if(v.length === 1) {\n if(arr[v[0]] == null) arr[v[0]] = 0\n arr[v[0]]++\n }\n }\n \n for(let k = 0; k < n; k++) {\n const v = arr[k]\n if(v > max) {\n max = v\n res = +k\n }\n }\n \n let min = Infinity\n for(let e of initial) {\n if(e < min) min = e\n }\n return max === -1 ? min: res\n \n}" ]
929
unique-email-addresses
[]
/** * @param {string[]} emails * @return {number} */ var numUniqueEmails = function(emails) { };
Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'. For example, in "alice@leetcode.com", "alice" is the local name, and "leetcode.com" is the domain name. If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names. For example, "m.y+name@email.com" will be forwarded to "my@email.com". It is possible to use both of these rules at the same time. Given an array of strings emails where we send one email to each emails[i], return the number of different addresses that actually receive mails.   Example 1: Input: emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"] Output: 2 Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails. Example 2: Input: emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"] Output: 3   Constraints: 1 <= emails.length <= 100 1 <= emails[i].length <= 100 emails[i] consist of lowercase English letters, '+', '.' and '@'. Each emails[i] contains exactly one '@' character. All local and domain names are non-empty. Local names do not start with a '+' character. Domain names end with the ".com" suffix.
Easy
[ "array", "hash-table", "string" ]
[ "const numUniqueEmails = function(emails) {\n const res = new Set()\n emails.forEach(el => helper(el, res))\n return res.size\n};\n\nfunction helper(str, s) {\n const arr = str.split('@')\n const p = arr[0]\n const d = arr[1]\n let res = ''\n for(let i = 0, len = p.length; i < len; i++) {\n if(p[i] === '.') {\n continue\n } else if(p[i] === '+') {\n break\n } else {\n res += p[i]\n }\n }\n s.add(`${res}@${d}`)\n}" ]
930
binary-subarrays-with-sum
[]
/** * @param {number[]} nums * @param {number} goal * @return {number} */ var numSubarraysWithSum = function(nums, goal) { };
Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal. A subarray is a contiguous part of the array.   Example 1: Input: nums = [1,0,1,0,1], goal = 2 Output: 4 Explanation: The 4 subarrays are bolded and underlined below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] Example 2: Input: nums = [0,0,0,0,0], goal = 0 Output: 15   Constraints: 1 <= nums.length <= 3 * 104 nums[i] is either 0 or 1. 0 <= goal <= nums.length
Medium
[ "array", "hash-table", "sliding-window", "prefix-sum" ]
[ "const numSubarraysWithSum = function(A, S) {\n if(A === null || A.length == 0) return 0;\n const freq = new Array(A.length + 1).fill(0)\n let ans = 0;\n let sum = 0;\n for(let i = 0; i < A.length; i++) {\n sum += A[i];\n let index = sum - S;\n if(index >= 0) ans += freq[index];\n if(sum == S) ans++;\n freq[sum]++;\n }\n return ans;\n};", "const numSubarraysWithSum = function(nums, goal) {\n const hash = {}\n const n = nums.length\n let res = 0, sum = 0\n for(let i = 0; i < n; i++) {\n const cur = nums[i]\n sum += cur\n const pre = sum - goal\n if(hash[sum] == null) hash[sum] = 0\n if(hash[pre] != null) res += hash[pre]\n if(sum === goal) res++\n hash[sum]++ \n }\n \n return res\n};" ]
931
minimum-falling-path-sum
[]
/** * @param {number[][]} matrix * @return {number} */ var minFallingPathSum = function(matrix) { };
Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix. A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).   Example 1: Input: matrix = [[2,1,3],[6,5,4],[7,8,9]] Output: 13 Explanation: There are two falling paths with a minimum sum as shown. Example 2: Input: matrix = [[-19,57],[-40,-5]] Output: -59 Explanation: The falling path with a minimum sum is shown.   Constraints: n == matrix.length == matrix[i].length 1 <= n <= 100 -100 <= matrix[i][j] <= 100
Medium
[ "array", "dynamic-programming", "matrix" ]
[ "const minFallingPathSum = function(A) {\n for (let i = 1, rows = A.length; i < rows; i++) {\n for (let j = 0, cols = A[0].length; j < cols; j++) {\n A[i][j] += Math.min(\n getValueOrMax(A, i - 1, j - 1),\n getValueOrMax(A, i - 1, j),\n getValueOrMax(A, i - 1, j + 1)\n );\n }\n }\n return Math.min(...A[A.length - 1]);\n};\n\nfunction getValueOrMax(A, i, j) {\n return A[i][j] !== undefined ? A[i][j] : Number.MAX_VALUE;\n}", "const minFallingPathSum = function(A) {\n for (let i = A.length - 2; i >= 0; i -= 1) {\n for (let j = 0; j < A[i].length; j += 1) {\n A[i][j] += Math.min(\n getValueOrMax(A, i + 1, j - 1),\n getValueOrMax(A, i + 1, j),\n getValueOrMax(A, i + 1, j + 1)\n )\n }\n }\n return Math.min(...A[0])\n }\n \n function getValueOrMax(A, i, j) {\n return A[i][j] !== undefined ? A[i][j] : Number.MAX_VALUE\n }\n " ]
932
beautiful-array
[]
/** * @param {number} n * @return {number[]} */ var beautifulArray = function(n) { };
An array nums of length n is beautiful if: nums is a permutation of the integers in the range [1, n]. For every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j]. Given the integer n, return any beautiful array nums of length n. There will be at least one valid answer for the given n.   Example 1: Input: n = 4 Output: [2,1,4,3] Example 2: Input: n = 5 Output: [3,1,2,5,4]   Constraints: 1 <= n <= 1000
Medium
[ "array", "math", "divide-and-conquer" ]
[ "const beautifulArray = function(N) {\n let res = [];\n res.push(1);\n while (res.length < N) {\n const tmp = [];\n for (let i of res) if (i * 2 - 1 <= N) tmp.push(i * 2 - 1);\n for (let i of res) if (i * 2 <= N) tmp.push(i * 2);\n res = tmp;\n }\n return res;\n};" ]
933
number-of-recent-calls
[]
var RecentCounter = function() { }; /** * @param {number} t * @return {number} */ RecentCounter.prototype.ping = function(t) { }; /** * Your RecentCounter object will be instantiated and called as such: * var obj = new RecentCounter() * var param_1 = obj.ping(t) */
You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: RecentCounter() Initializes the counter with zero recent requests. int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t]. It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.   Example 1: Input ["RecentCounter", "ping", "ping", "ping", "ping"] [[], [1], [100], [3001], [3002]] Output [null, 1, 2, 3, 3] Explanation RecentCounter recentCounter = new RecentCounter(); recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1 recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2 recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3 recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3   Constraints: 1 <= t <= 109 Each test case will call ping with strictly increasing values of t. At most 104 calls will be made to ping.
Easy
[ "design", "queue", "data-stream" ]
[ "const RecentCounter = function() {\n this.pings = [];\n};\n\n\nRecentCounter.prototype.ping = function(t) {\n if (t === null) return null;\n if (t > 3000) {\n let delta = t - 3000;\n while (this.pings.length > 0 && this.pings[0] < delta) {\n this.pings.shift();\n } \n }\n \n this.pings.push(t);\n return this.pings.length;\n};" ]
934
shortest-bridge
[]
/** * @param {number[][]} grid * @return {number} */ var shortestBridge = function(grid) { };
You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid. You may change 0's to 1's to connect the two islands to form one island. Return the smallest number of 0's you must flip to connect the two islands.   Example 1: Input: grid = [[0,1],[1,0]] Output: 1 Example 2: Input: grid = [[0,1,0],[0,0,0],[0,0,1]] Output: 2 Example 3: Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] Output: 1   Constraints: n == grid.length == grid[i].length 2 <= n <= 100 grid[i][j] is either 0 or 1. There are exactly two islands in grid.
Medium
[ "array", "depth-first-search", "breadth-first-search", "matrix" ]
[ "const shortestBridge = function(A) {\n let r = A.length;\n let c = A[0].length;\n let found = false;\n let queue = [];\n for (let i = 0; i < r; i++) {\n for (let j = 0; j < c; j++) {\n if (A[i][j]) {\n dfs(A, i, j, queue);\n found = true;\n break;\n }\n }\n if (found) break;\n }\n \n let replace = [];\n let count = 0;\n let cells = [[1, 0], [-1, 0], [0, 1], [0, -1]];\n while (queue.length) {\n let pos = queue.shift();\n \n for (let i = 0; i < cells.length; i++) {\n let x = pos[0] + cells[i][0]; \n let y = pos[1] + cells[i][1];\n \n if (0 <= x && x < r && 0 <= y && y < c && A[x][y] != 2) {\n if (A[x][y] == 1) return count;\n A[x][y] = 2;\n replace.push([x, y]);\n }\n }\n \n if (!queue.length) {\n queue = replace;\n replace = [];\n count++;\n }\n }\n};\n\nfunction dfs(A, x, y, queue) {\n if (x < 0 || x >= A.length || y < 0 || y >= A[0].length || A[x][y] == 0 || A[x][y] == 2) return;\n \n A[x][y] = 2;\n queue.push([x, y]);\n dfs(A, x-1, y, queue);\n dfs(A, x+1, y, queue);\n dfs(A, x, y-1, queue);\n dfs(A, x, y+1, queue);\n}" ]
935
knight-dialer
[]
/** * @param {number} n * @return {number} */ var knightDialer = function(n) { };
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the chess diagram below: We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell). Given an integer n, return how many distinct phone numbers of length n we can dial. You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps. As the answer may be very large, return the answer modulo 109 + 7.   Example 1: Input: n = 1 Output: 10 Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient. Example 2: Input: n = 2 Output: 20 Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94] Example 3: Input: n = 3131 Output: 136006598 Explanation: Please take care of the mod.   Constraints: 1 <= n <= 5000
Medium
[ "dynamic-programming" ]
null
[]
936
stamping-the-sequence
[]
/** * @param {string} stamp * @param {string} target * @return {number[]} */ var movesToStamp = function(stamp, target) { };
You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'. In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp. For example, if stamp = "abc" and target = "abcba", then s is "?????" initially. In one turn you can: place stamp at index 0 of s to obtain "abc??", place stamp at index 1 of s to obtain "?abc?", or place stamp at index 2 of s to obtain "??abc". Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s). We want to convert s to target using at most 10 * target.length turns. Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array.   Example 1: Input: stamp = "abc", target = "ababc" Output: [0,2] Explanation: Initially s = "?????". - Place stamp at index 0 to get "abc??". - Place stamp at index 2 to get "ababc". [1,0,2] would also be accepted as an answer, as well as some other answers. Example 2: Input: stamp = "abca", target = "aabcaca" Output: [3,0,1] Explanation: Initially s = "???????". - Place stamp at index 3 to get "???abca". - Place stamp at index 0 to get "abcabca". - Place stamp at index 1 to get "aabcaca".   Constraints: 1 <= stamp.length <= target.length <= 1000 stamp and target consist of lowercase English letters.
Hard
[ "string", "stack", "greedy", "queue" ]
[ "const movesToStamp = function (stamp, target) {\n const S = stamp.split('')\n const T = target.split('')\n const res = []\n const visited = Array(T.length).fill(false)\n let stars = 0\n\n while (stars < T.length) {\n let doneReplace = false\n for (let i = 0; i <= T.length - S.length; i++) {\n if (!visited[i] && canReplace(T, i, S)) {\n stars = doReplace(T, i, S.length, stars)\n doneReplace = true\n visited[i] = true\n res.unshift(i)\n if (stars === T.length) {\n break\n }\n }\n }\n\n if (!doneReplace) {\n return []\n }\n }\n\n return res\n function canReplace(T, p, S) {\n for (let i = 0; i < S.length; i++) {\n if (T[i + p] !== '*' && T[i + p] !== S[i]) {\n return false\n }\n }\n return true\n }\n\n function doReplace(T, p, len, count) {\n for (let i = 0; i < len; i++) {\n if (T[i + p] !== '*') {\n T[i + p] = '*'\n count++\n }\n }\n return count\n }\n}" ]
937
reorder-data-in-log-files
[]
/** * @param {string[]} logs * @return {string[]} */ var reorderLogFiles = function(logs) { };
You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier. There are two types of logs: Letter-logs: All words (except the identifier) consist of lowercase English letters. Digit-logs: All words (except the identifier) consist of digits. Reorder these logs so that: The letter-logs come before all digit-logs. The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers. The digit-logs maintain their relative ordering. Return the final order of the logs.   Example 1: Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"] Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"] Explanation: The letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig". The digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6". Example 2: Input: logs = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"] Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]   Constraints: 1 <= logs.length <= 100 3 <= logs[i].length <= 100 All the tokens of logs[i] are separated by a single space. logs[i] is guaranteed to have an identifier and at least one word after the identifier.
Medium
[ "array", "string", "sorting" ]
[ "const reorderLogFiles = function(logs) {\n const letterLog = [],\n digitLog = []\n for (let log of logs) {\n if (isNaN(log.split(' ')[1])) {\n letterLog.push(log)\n } else {\n digitLog.push(log)\n }\n }\n letterLog.sort((log1, log2) => {\n let body1 = log1.slice(log1.indexOf(' '))\n let body2 = log2.slice(log2.indexOf(' '))\n if (body1 === body2) {\n return log1.split(' ')[0] > log2.split(' ')[0] ? 1 : -1\n } else {\n return body1 > body2 ? 1 : -1\n }\n })\n return [...letterLog, ...digitLog]\n}", "const reorderLogFiles = function(logs) {\n if(logs == null || logs.length === 0) return []\n const ll = []\n const dl = []\n const zero = '0'.charCodeAt(0)\n const nine = '9'.charCodeAt(0)\n for(let e of logs) {\n const arr = e.split(' ')\n if(arr[1].charCodeAt(0) >= zero && arr[1].charCodeAt(0) <= nine) {\n dl.push(arr)\n } else {\n ll.push(arr)\n }\n }\n const rll = ll.map(el => {\n const r = el.slice(1).join(' ')\n return [el[0], r]\n }).sort((a, b) => {\n if(a[1] < b[1]) return -1\n else if(a[1] > b[1]) return 1\n else {\n if(`${a[0]} ${a[1]}` > `${b[0]} ${b[1]}`) return 1\n else if(`${a[0]} ${a[1]}` < `${b[0]} ${b[1]}`) return -1\n else return 0\n }\n }).map(el => el.join(' '))\n \n const rdl = dl.map(el => el.join(' '))\n return rll.concat(rdl)\n};" ]
938
range-sum-of-bst
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} low * @param {number} high * @return {number} */ var rangeSumBST = function(root, low, high) { };
Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].   Example 1: Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 Output: 32 Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32. Example 2: Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 Output: 23 Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.   Constraints: The number of nodes in the tree is in the range [1, 2 * 104]. 1 <= Node.val <= 105 1 <= low <= high <= 105 All Node.val are unique.
Easy
[ "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 rangeSumBST = function(root, L, R) {\n const payload = {sum: 0} \n traverse(root, payload, L, R)\n return payload.sum\n};\n\nfunction traverse(node, obj, L, R) {\n if(node == null) return\n if(node.val >= L && node.val <= R) obj.sum += node.val\n traverse(node.left, obj, L, R)\n traverse(node.right, obj, L, R)\n}" ]
939
minimum-area-rectangle
[]
/** * @param {number[][]} points * @return {number} */ var minAreaRect = function(points) { };
You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.   Example 1: Input: points = [[1,1],[1,3],[3,1],[3,3],[2,2]] Output: 4 Example 2: Input: points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]] Output: 2   Constraints: 1 <= points.length <= 500 points[i].length == 2 0 <= xi, yi <= 4 * 104 All the given points are unique.
Medium
[ "array", "hash-table", "math", "geometry", "sorting" ]
[ "const minAreaRect = function(points) {\n const xmap = {}, ymap = {}\n points.forEach(e => {\n const [x, y] = e\n if(!xmap.hasOwnProperty(x)) xmap[x] = new Set()\n if(!ymap.hasOwnProperty(y)) ymap[y] = new Set()\n xmap[x].add(y)\n ymap[y].add(x)\n })\n let res = Infinity\n for(let i = 0, len = points.length; i < len - 1; i++) {\n const [x, y] = points[i]\n for(let j = i + 1; j < len; j++) {\n const [x1, y1] = points[j]\n if(x === x1 || y === y1) continue\n let area = Infinity\n if(xmap[x].has(y1) && ymap[y].has(x1)) area = Math.abs(x - x1) * Math.abs(y - y1)\n else continue\n res = Math.min(res, area)\n }\n }\n return res === Infinity ? 0 : res\n};", "const minAreaRect = function (points) {\n let ans = Infinity\n const isPoint = {}\n points.forEach(([x, y]) => (isPoint[x * 40000 + y] = true))\n for (let idx1 = 0; idx1 < points.length - 1; idx1++) {\n const [x1, y1] = points[idx1]\n for (let idx2 = idx1 + 1; idx2 < points.length; idx2++) {\n const [x2, y2] = points[idx2]\n const area = Math.abs((x1 - x2) * (y1 - y2))\n if (area === 0 || area >= ans) continue\n if (isPoint[x1 * 40000 + y2] && isPoint[x2 * 40000 + y1]) ans = area\n }\n }\n return ans !== Infinity ? ans : 0\n}" ]
940
distinct-subsequences-ii
[]
/** * @param {string} s * @return {number} */ var distinctSubseqII = function(s) { };
Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 109 + 7. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not.   Example 1: Input: s = "abc" Output: 7 Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc". Example 2: Input: s = "aba" Output: 6 Explanation: The 6 distinct subsequences are "a", "b", "ab", "aa", "ba", and "aba". Example 3: Input: s = "aaa" Output: 3 Explanation: The 3 distinct subsequences are "a", "aa" and "aaa".   Constraints: 1 <= s.length <= 2000 s consists of lowercase English letters.
Hard
[ "string", "dynamic-programming" ]
[ "const distinctSubseqII = function(s) {\n const n = s.length,\n dp = Array(26).fill(0),\n a = 'a'.charCodeAt(0),\n mod = 1e9 + 7\n let res = 0\n for(let ch of s) {\n const idx = ch.charCodeAt(0) - a\n let tmp = 0\n for(let i = 0; i < 26; i++) tmp = (tmp + dp[i]) % mod\n tmp = (tmp + 1) % mod\n dp[idx] = tmp\n }\n return dp.reduce((ac, e) => (ac + e) % mod, 0)\n};", "const distinctSubseqII = function(S) {\n // let end = new Array(26).fill(0), res = 0, added = 0, mod = 10 ** 9 + 7;\n // const aCode = ('a').charCodeAt(0)\n // for (let c of S) {\n // added = (res + 1 - end[c.charCodeAt(0) - aCode]) % mod;\n // res = (res + added) % mod;\n // end[c.charCodeAt(0) - aCode] = (end[c.charCodeAt(0) - aCode] + added) % mod;\n // }\n // return (res + mod) % mod;\n const m = new Map(),\n dp = [1],\n M = 1000000007\n for (let i = 0; i < S.length; i++) {\n const c = S.charAt(i)\n let prev = 0\n if (m.has(c)) {\n prev = dp[m.get(c)]\n }\n m.set(c, i)\n dp.push((((dp[i] * 2) % M) - prev) % M)\n if (dp[i + 1] < 0) {\n dp[i + 1] += M\n }\n }\n return dp[S.length] - 1\n}" ]
941
valid-mountain-array
[ "It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and you will be able to come up with a straightforward solution." ]
/** * @param {number[]} arr * @return {boolean} */ var validMountainArray = function(arr) { };
Given an array of integers arr, return true if and only if it is a valid mountain array. Recall that arr is a mountain array if and only if: arr.length >= 3 There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]   Example 1: Input: arr = [2,1] Output: false Example 2: Input: arr = [3,5,5] Output: false Example 3: Input: arr = [0,3,2,1] Output: true   Constraints: 1 <= arr.length <= 104 0 <= arr[i] <= 104
Easy
[ "array" ]
[ "const validMountainArray = function(A) {\n if (A.length < 3) return false;\n let start = 0;\n let end = A.length - 1;\n while (start < end) {\n while (A[end - 1] > A[end]) {\n end--;\n }\n while (A[start] < A[start + 1]) {\n start++;\n }\n if (start !== end || start === 0 || end === A.length - 1) return false;\n }\n return true;\n};" ]
942
di-string-match
[]
/** * @param {string} s * @return {number[]} */ var diStringMatch = function(s) { };
A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: s[i] == 'I' if perm[i] < perm[i + 1], and s[i] == 'D' if perm[i] > perm[i + 1]. Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.   Example 1: Input: s = "IDID" Output: [0,4,1,3,2] Example 2: Input: s = "III" Output: [0,1,2,3] Example 3: Input: s = "DDI" Output: [3,2,0,1]   Constraints: 1 <= s.length <= 105 s[i] is either 'I' or 'D'.
Easy
[ "array", "two-pointers", "string", "greedy" ]
[ "const diStringMatch = function(S) {\n const N = S.length\n const arr = []\n for(let i = 0; i <= N; i++) {\n arr[i] = i\n }\n const res = []\n for(let i = 0; i < N; i++) {\n if(S[i] === 'I') {\n res.push(arr.shift())\n } else if(S[i] === 'D') {\n res.push(arr.pop())\n }\n }\n res.push(arr.pop())\n return res\n};", "const diStringMatch = function(s) {\n const n = s.length\n let l = 0, r = n\n const res = []\n for(let i = 0; i < n; i++) {\n res.push(s[i] === 'I' ? l++ : r--)\n }\n res.push(r)\n return res\n};" ]
943
find-the-shortest-superstring
[]
/** * @param {string[]} words * @return {string} */ var shortestSuperstring = function(words) { };
Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them. You may assume that no string in words is a substring of another string in words.   Example 1: Input: words = ["alex","loves","leetcode"] Output: "alexlovesleetcode" Explanation: All permutations of "alex","loves","leetcode" would also be accepted. Example 2: Input: words = ["catg","ctaagt","gcta","ttca","atgcatc"] Output: "gctaagttcatgcatc"   Constraints: 1 <= words.length <= 12 1 <= words[i].length <= 20 words[i] consists of lowercase English letters. All the strings of words are unique.
Hard
[ "array", "string", "dynamic-programming", "bit-manipulation", "bitmask" ]
[ "const shortestSuperstring = function(arr) {\n while (arr.length > 1) {\n let maxCommonLength = 0\n let maxCommonString = arr[0] + arr[1]\n let maxCommonWords = [arr[0], arr[1]]\n for (let i = 0; i < arr.length - 1; i++) {\n for (let j = i + 1; j < arr.length; j++) {\n const { commonLength, commonString } = checkCommonPair(arr[i], arr[j])\n if (commonString && commonLength >= maxCommonLength) {\n maxCommonLength = commonLength\n maxCommonString = commonString\n maxCommonWords = [arr[i], arr[j]]\n }\n }\n }\n arr = arr.filter(\n word => word !== maxCommonWords[0] && word !== maxCommonWords[1]\n )\n arr.unshift(maxCommonString)\n }\n return arr[0]\n}\n\nconst checkCommonPair = function(s1, s2) {\n let maxCommonLength = 0\n let commonString = ''\n if (s1.length > s2.length) s1, (s2 = s2), s1\n for (let stringLength = 1; stringLength < s1.length; stringLength++) {\n const s1Suffix = s1.substring(s1.length - stringLength)\n const s2Prefix = s2.substring(0, stringLength)\n if (s1Suffix === s2Prefix && stringLength > maxCommonLength) {\n maxCommonLength = stringLength\n commonString = s1 + s2.substring(stringLength)\n }\n }\n for (let stringLength = 1; stringLength < s1.length; stringLength++) {\n const s1Prefix = s1.substring(0, stringLength)\n const s2Suffix = s2.substring(s2.length - stringLength)\n if (s1Prefix === s2Suffix && stringLength > maxCommonLength) {\n if (stringLength > maxCommonLength) {\n maxCommonLength = stringLength\n commonString = s2 + s1.substring(stringLength)\n }\n }\n }\n\n return {\n commonLength: maxCommonLength,\n commonString\n }\n}" ]
944
delete-columns-to-make-sorted
[]
/** * @param {string[]} strs * @return {number} */ var minDeletionSize = function(strs) { };
You are given an array of n strings strs, all of the same length. The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as follows: abc bce cae You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted, while column 1 ('b', 'c', 'a') is not, so you would delete column 1. Return the number of columns that you will delete.   Example 1: Input: strs = ["cba","daf","ghi"] Output: 1 Explanation: The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. Example 2: Input: strs = ["a","b"] Output: 0 Explanation: The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. Example 3: Input: strs = ["zyx","wvu","tsr"] Output: 3 Explanation: The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3.   Constraints: n == strs.length 1 <= n <= 100 1 <= strs[i].length <= 1000 strs[i] consists of lowercase English letters.
Easy
[ "array", "string" ]
[ "const minDeletionSize = function(A) {\n // increment this if we find a\n // column that is out of order\n let numColumnsToDelete = 0;\n\n // all strings in the array\n // are the same length\n const strLength = A[0].length;\n\n // outer loop checks entire string\n for (let i = 0; i < strLength; i++) {\n // inner loop checks the colunns\n for (let j = 0; j < A.length - 1; j++) {\n const top = A[j][i];\n const bottom = A[j + 1][i];\n\n if (top > bottom) {\n numColumnsToDelete++;\n break;\n }\n }\n }\n return numColumnsToDelete;\n};" ]
945
minimum-increment-to-make-array-unique
[]
/** * @param {number[]} nums * @return {number} */ var minIncrementForUnique = function(nums) { };
You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1. Return the minimum number of moves to make every value in nums unique. The test cases are generated so that the answer fits in a 32-bit integer.   Example 1: Input: nums = [1,2,2] Output: 1 Explanation: After 1 move, the array could be [1, 2, 3]. Example 2: Input: nums = [3,2,1,2,1,7] Output: 6 Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. It can be shown with 5 or less moves that it is impossible for the array to have all unique values.   Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 105
Medium
[ "array", "greedy", "sorting", "counting" ]
[ "const minIncrementForUnique = function(nums) {\n const seen = new Set()\n const queue = []\n let res = 0\n for(const e of nums) {\n if(!seen.has(e)) seen.add(e)\n else queue.push(e)\n }\n queue.sort((a, b) => b - a)\n for(let i = 0; i <= 1e5 || queue.length; i++) {\n if(!seen.has(i) && i > last(queue)) {\n res += i - queue.pop()\n }\n }\n \n return res\n \n function last(arr) {\n return arr[arr.length - 1]\n }\n};", "const minIncrementForUnique = function(nums) {\n let res = 0, nxt = 0\n nums.sort((a, b) => a - b)\n for(const e of nums) {\n res += Math.max(0, nxt - e)\n nxt = Math.max(nxt, e) + 1\n }\n \n return res\n};" ]
946
validate-stack-sequences
[]
/** * @param {number[]} pushed * @param {number[]} popped * @return {boolean} */ var validateStackSequences = function(pushed, popped) { };
Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.   Example 1: Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] Output: true Explanation: We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 Example 2: Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2] Output: false Explanation: 1 cannot be popped before 2.   Constraints: 1 <= pushed.length <= 1000 0 <= pushed[i] <= 1000 All the elements of pushed are unique. popped.length == pushed.length popped is a permutation of pushed.
Medium
[ "array", "stack", "simulation" ]
[ "const validateStackSequences = function(pushed, popped) {\n const arr = []\n for (let i = 0, len = pushed.length; i < len; i++) {\n if (!helper(arr, pushed, popped)) return false\n }\n return true\n}\n\nfunction helper(arr, pu, po) {\n let target = po[0]\n\n while (arr.length || pu.length) {\n let curP = pu[0]\n if (curP === target) {\n po.shift()\n pu.shift()\n return true\n } else if (arr.length && arr[arr.length - 1] === target) {\n arr.pop()\n po.shift()\n return true\n } else {\n if (curP == null) {\n return false\n } else {\n arr.push(curP)\n pu.shift()\n }\n }\n }\n return false\n}" ]
947
most-stones-removed-with-same-row-or-column
[]
/** * @param {number[][]} stones * @return {number} */ var removeStones = function(stones) { };
On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.   Example 1: Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]] Output: 5 Explanation: One way to remove 5 stones is as follows: 1. Remove stone [2,2] because it shares the same row as [2,1]. 2. Remove stone [2,1] because it shares the same column as [0,1]. 3. Remove stone [1,2] because it shares the same row as [1,0]. 4. Remove stone [1,0] because it shares the same column as [0,0]. 5. Remove stone [0,1] because it shares the same row as [0,0]. Stone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane. Example 2: Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]] Output: 3 Explanation: One way to make 3 moves is as follows: 1. Remove stone [2,2] because it shares the same row as [2,0]. 2. Remove stone [2,0] because it shares the same column as [0,0]. 3. Remove stone [0,2] because it shares the same row as [0,0]. Stones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane. Example 3: Input: stones = [[0,0]] Output: 0 Explanation: [0,0] is the only stone on the plane, so you cannot remove it.   Constraints: 1 <= stones.length <= 1000 0 <= xi, yi <= 104 No two stones are at the same coordinate point.
Medium
[ "hash-table", "depth-first-search", "union-find", "graph" ]
[ "const removeStones = function(stones) {\n const f = new Map()\n let islands = 0\n for (let i = 0; i < stones.length; i++) {\n union(stones[i][0], ~stones[i][1]) // row, col\n }\n return stones.length - islands\n\n function find(x) {\n if (!f.has(x)) {\n islands++\n f.set(x, x)\n }\n if (x != f.get(x)) {\n f.set(x, find(f.get(x)))\n }\n return f.get(x)\n }\n\n function union(x, y) {\n x = find(x)\n y = find(y)\n if (x !== y) {\n f.set(x, y)\n islands--\n }\n }\n}" ]
948
bag-of-tokens
[]
/** * @param {number[]} tokens * @param {number} power * @return {number} */ var bagOfTokensScore = function(tokens, power) { };
You have an initial power of power, an initial score of 0, and a bag of tokens where tokens[i] is the value of the ith token (0-indexed). Your goal is to maximize your total score by potentially playing each token in one of two ways: If your current power is at least tokens[i], you may play the ith token face up, losing tokens[i] power and gaining 1 score. If your current score is at least 1, you may play the ith token face down, gaining tokens[i] power and losing 1 score. Each token may be played at most once and in any order. You do not have to play all the tokens. Return the largest possible score you can achieve after playing any number of tokens.   Example 1: Input: tokens = [100], power = 50 Output: 0 Explanation: Playing the only token in the bag is impossible because you either have too little power or too little score. Example 2: Input: tokens = [100,200], power = 150 Output: 1 Explanation: Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. Example 3: Input: tokens = [100,200,300,400], power = 200 Output: 2 Explanation: Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.   Constraints: 0 <= tokens.length <= 1000 0 <= tokens[i], power < 104
Medium
[ "array", "two-pointers", "greedy", "sorting" ]
[ "const bagOfTokensScore = function (tokens, P) {\n tokens.sort((a, b) => a - b)\n let res = 0,\n score = 0,\n i = 0,\n j = tokens.length - 1\n while (i <= j) {\n if (P >= tokens[i]) {\n P -= tokens[i++]\n res = Math.max(res, ++score)\n } else if (score > 0) {\n score--\n P += tokens[j--]\n } else break\n }\n return res\n}" ]
949
largest-time-for-given-digits
[]
/** * @param {number[]} arr * @return {string} */ var largestTimeFromDigits = function(arr) { };
Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. Return the latest 24-hour time in "HH:MM" format. If no valid time can be made, return an empty string.   Example 1: Input: arr = [1,2,3,4] Output: "23:41" Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest. Example 2: Input: arr = [5,5,5,5] Output: "" Explanation: There are no valid 24-hour times as "55:55" is not valid.   Constraints: arr.length == 4 0 <= arr[i] <= 9
Medium
[ "string", "enumeration" ]
[ "const largestTimeFromDigits = function(A) {\n let ans = \"\";\n for (let i = 0; i < 4; ++i) {\n for (let j = 0; j < 4; ++j) {\n for (let k = 0; k < 4; ++k) {\n // avoid duplicate among i, j & k.\n if (i == j || i == k || j == k) continue; \n // hour, minutes, & time.\n let h = \"\" + A[i] + A[j], m = \"\" + A[k] + A[6 - i - j - k], t = h + \":\" + m; \n // hour < 24; minute < 60; update result.\n if (h < \"24\" && m < \"60\" && ans < t) ans = t; \n }\n }\n }\n return ans;\n};" ]
950
reveal-cards-in-increasing-order
[]
/** * @param {number[]} deck * @return {number[]} */ var deckRevealedIncreasing = function(deck) { };
You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i]. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: Take the top card of the deck, reveal it, and take it out of the deck. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return an ordering of the deck that would reveal the cards in increasing order. Note that the first entry in the answer is considered to be the top of the deck.   Example 1: Input: deck = [17,13,11,2,3,5,7] Output: [2,13,3,11,5,17,7] Explanation: We get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it. After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13]. We reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11]. We reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17]. We reveal 7, and move 13 to the bottom. The deck is now [11,17,13]. We reveal 11, and move 17 to the bottom. The deck is now [13,17]. We reveal 13, and move 17 to the bottom. The deck is now [17]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. Example 2: Input: deck = [1,1000] Output: [1,1000]   Constraints: 1 <= deck.length <= 1000 1 <= deck[i] <= 106 All the values of deck are unique.
Medium
[ "array", "queue", "sorting", "simulation" ]
[ "const deckRevealedIncreasing = function(deck) {\n const n= deck.length;\n\n deck.sort((a, b) => a - b)\n const q = [];\n for (let i=0; i<n; i++) q.push(i);\n const res = new Array(n).fill(0);\n for (let i=0; i<n; i++){\n res[q.shift()]=deck[i];\n q.push(q.shift());\n }\n return res;\n};" ]
951
flip-equivalent-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 {boolean} */ var flipEquiv = function(root1, root2) { };
For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees. A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations. Given the roots of two binary trees root1 and root2, return true if the two trees are flip equivalent or false otherwise.   Example 1: Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7] Output: true Explanation: We flipped at nodes with values 1, 3, and 5. Example 2: Input: root1 = [], root2 = [] Output: true Example 3: Input: root1 = [], root2 = [1] Output: false   Constraints: The number of nodes in each tree is in the range [0, 100]. Each tree will have unique node values in the range [0, 99].
Medium
[ "tree", "depth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const flipEquiv = function(root1, root2) {\n if(root1 == null || root2 == null) return root1 === root2\n return root1.val === root2.val &&\n (\n (flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right)) ||\n (flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left))\n )\n};" ]
952
largest-component-size-by-common-factor
[]
/** * @param {number[]} nums * @return {number} */ var largestComponentSize = function(nums) { };
You are given an integer array of unique positive integers nums. Consider the following graph: There are nums.length nodes, labeled nums[0] to nums[nums.length - 1], There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1. Return the size of the largest connected component in the graph.   Example 1: Input: nums = [4,6,15,35] Output: 4 Example 2: Input: nums = [20,50,9,63] Output: 2 Example 3: Input: nums = [2,3,6,7,4,12,21,39] Output: 8   Constraints: 1 <= nums.length <= 2 * 104 1 <= nums[i] <= 105 All the values of nums are unique.
Hard
[ "array", "hash-table", "math", "union-find", "number-theory" ]
[ "const largestComponentSize = function (nums) {\n const { sqrt } = Math\n const n = nums.length\n const uf = new UF(n)\n const primes = {}\n for (let i = 0; i < n; i++) {\n const num = nums[i]\n const prSet = primesSet(num)\n for (const e of prSet) {\n if (primes[e] == null) primes[e] = []\n primes[e].push(i)\n }\n }\n\n const vals = Object.values(primes)\n for(const idxArr of vals) {\n const len = idxArr.length\n for(let i = 0; i < len - 1; i++) {\n uf.union(idxArr[i], idxArr[i + 1])\n }\n }\n let res = 0\n const hash = {}\n for(let i = 0; i < n; i++) {\n const root = uf.find(i)\n if(hash[root] == null) hash[root] = 0\n hash[root]++\n }\n return Math.max(...Object.values(hash))\n\n function primesSet(n) {\n const limit = ~~(sqrt(n) + 1)\n for (let i = 2; i < limit; i++) {\n if (n % i === 0) {\n const res = primesSet(n / i)\n res.add(i)\n return res\n }\n }\n return new Set([n])\n }\n}\n\nclass UF {\n constructor(n) {\n this.root = Array(n)\n .fill(null)\n .map((_, i) => i)\n }\n find(x) {\n if (this.root[x] !== x) {\n this.root[x] = this.find(this.root[x])\n }\n return this.root[x]\n }\n union(x, y) {\n const xr = this.find(x)\n const yr = this.find(y)\n this.root[yr] = xr\n }\n}", "class UF {\n constructor(N) {\n this.parent = []\n this.size = []\n this.max = 1\n for (let i = 0; i < N; i++) {\n this.parent[i] = i\n this.size[i] = 1\n }\n }\n find(x) {\n if (x === this.parent[x]) {\n return x\n }\n return (this.parent[x] = this.find(this.parent[x]))\n }\n union(x, y) {\n let rootX = this.find(x)\n let rootY = this.find(y)\n if (rootX != rootY) {\n this.parent[rootX] = rootY\n this.size[rootY] += this.size[rootX]\n this.max = Math.max(this.max, this.size[rootY])\n }\n }\n}\nconst largestComponentSize = A => {\n let N = A.length\n const map = {} // key is the factor, val is the node index\n const uf = new UF(N)\n for (let i = 0; i < N; i++) {\n let a = A[i]\n for (let j = 2; j * j <= a; j++) {\n if (a % j == 0) {\n if (!map.hasOwnProperty(j)) {\n //this means that no index has claimed the factor yet\n map[j] = i\n } else {\n //this means that one index already claimed, so union that one with current\n uf.union(i, map[j])\n }\n if (!map.hasOwnProperty(a / j)) {\n map[a / j] = i\n } else {\n uf.union(i, map[a / j])\n }\n }\n }\n if (!map.hasOwnProperty(a)) {\n //a could be factor too. Don't miss this\n map[a] = i\n } else {\n uf.union(i, map[a])\n }\n }\n return uf.max\n}" ]
953
verifying-an-alien-dictionary
[]
/** * @param {string[]} words * @param {string} order * @return {boolean} */ var isAlienSorted = function(words, order) { };
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.   Example 1: Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" Output: true Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted. Example 2: Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted. Example 3: Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" Output: false Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).   Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 20 order.length == 26 All characters in words[i] and order are English lowercase letters.
Easy
[ "array", "hash-table", "string" ]
[ "const isAlienSorted = function(words, order) {\n const mapping = Array(26).fill(0), a = 'a'.charCodeAt(0)\n for(let i = 0, len = order.length; i < len; i++) {\n mapping[order.charCodeAt(i) - a] = i\n }\n\n for(let i = 1, n = words.length; i < n; i++) {\n if(bigger(words[i - 1], words[i])) return false\n }\n \n return true\n \n function bigger(s1, s2) {\n const n = s1.length, m = s2.length;\n for (let i = 0; i < n && i < m; ++i) {\n if (s1.charAt(i) != s2.charAt(i)) return mapping[s1.charCodeAt(i) - a] > mapping[s2.charCodeAt(i) - a]; \n }\n\n return n > m;\n }\n\n};" ]
954
array-of-doubled-pairs
[]
/** * @param {number[]} arr * @return {boolean} */ var canReorderDoubled = function(arr) { };
Given an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise.   Example 1: Input: arr = [3,1,3,6] Output: false Example 2: Input: arr = [2,1,2,6] Output: false Example 3: Input: arr = [4,-2,2,-4] Output: true Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].   Constraints: 2 <= arr.length <= 3 * 104 arr.length is even. -105 <= arr[i] <= 105
Medium
[ "array", "hash-table", "greedy", "sorting" ]
[ "const canReorderDoubled = function(A) {\n const cnt = {}\n for(let val of A) {\n val = Math.abs(val)\n cnt[val] ? cnt[val]++ : cnt[val] = 1\n }\n for(let val in cnt) {\n let sibling = val * 2\n if(val == '0') {\n if(cnt[val] % 2) return false\n cnt[val] = 0 \n } else if(cnt[val] && cnt[sibling]) {\n cnt[sibling] -= cnt[val]\n cnt[val] = 0\n }\n }\n for(let val in cnt)\n if(cnt[val]) return false\n return true\n};" ]
955
delete-columns-to-make-sorted-ii
[]
/** * @param {string[]} strs * @return {number} */ var minDeletionSize = function(strs) { };
You are given an array of n strings strs, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"]. Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]). Return the minimum possible value of answer.length.   Example 1: Input: strs = ["ca","bb","ac"] Output: 1 Explanation: After deleting the first column, strs = ["a", "b", "c"]. Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]). We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1. Example 2: Input: strs = ["xc","yb","za"] Output: 0 Explanation: strs is already in lexicographic order, so we do not need to delete anything. Note that the rows of strs are not necessarily in lexicographic order: i.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...) Example 3: Input: strs = ["zyx","wvu","tsr"] Output: 3 Explanation: We have to delete every column.   Constraints: n == strs.length 1 <= n <= 100 1 <= strs[i].length <= 100 strs[i] consists of lowercase English letters.
Medium
[ "array", "string", "greedy" ]
[ "const minDeletionSize = function (A) {\n let res = 0,\n i,\n j //n: 有多少个字符串,对应i. m:每个字符串的长度,对应j\n const n = A.length,\n m = A[0].length,\n sorted = new Array(n - 1).fill(false)\n for (j = 0; j < m; ++j) {\n //从第一个字符到最后一个字符\n for (i = 0; i < n - 1; ++i) {\n //i从第一个字到最后一个字\n if (!sorted[i] && A[i].charAt(j) > A[i + 1].charAt(j)) {\n res++\n break\n }\n }\n if (i < n - 1) continue\n\n //假设输入是[\"xgag\",\"xfba\",\"yfac\"]\n //那么第一轮j=0,比较第一列: x=x<y,合理,所以此时res=0,然后运行了下面的循环, 可以使得sorted[xfb] = true;\n //然后第二轮j=1,第二列g>f,进入if条件语句,所以res = 1, break\n //然后第三轮j=2,a<b>a,这里b虽然>a,但是由于sorted[xfb] = true,所以不会进入到上面的循环体,然后sorted[xga] = true\n //然后第四轮j=3,这一轮已经不再重要,因为通过前面几轮 sorted[0] = true, sorted[1] = true, 这意味着已经实现了排序,所以res最终结果就是1\n\n for (\n i = 0;\n i < n - 1;\n ++i //这一段代码结合最外面的循环可以用作比较string大小的通用代码\n )\n if (A[i].charAt(j) < A[i + 1].charAt(j)) sorted[i] = true\n }\n return res\n}", "const minDeletionSize = function (A) {\n const set = new Set()\n const m = A.length\n let res = 0\n if(m === 0) return 0\n const n = A[0].length\n for(j = 0; j < n; j++) {\n if(set.size === m - 1) return res\n for(i = 0; i < m - 1; i++) {\n if(!set.has(i) && A[i][j] > A[i + 1][j]) {\n res++\n break\n }\n }\n if(i < m - 1) continue\n for(i = 0; i < m - 1; i++) {\n if(A[i][j] < A[i + 1][j]) set.add(i)\n }\n }\n \n return res\n}" ]
956
tallest-billboard
[]
/** * @param {number[]} rods * @return {number} */ var tallestBillboard = function(rods) { };
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6. Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0.   Example 1: Input: rods = [1,2,3,6] Output: 6 Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6. Example 2: Input: rods = [1,2,3,4,5,6] Output: 10 Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10. Example 3: Input: rods = [1,2] Output: 0 Explanation: The billboard cannot be supported, so we return 0.   Constraints: 1 <= rods.length <= 20 1 <= rods[i] <= 1000 sum(rods[i]) <= 5000
Hard
[ "array", "dynamic-programming" ]
[ "const tallestBillboard = function(rods) {\n const dp = {0 : 0}\n for(let el of rods) {\n for(let [diff, y] of Object.entries(dp)) {\n diff = +diff\n dp[diff + el] = Math.max(dp[diff + el] || 0, y)\n if(diff >= el) dp[diff - el] = Math.max(dp[diff - el] || 0, y + el)\n else dp[el - diff] = Math.max(dp[el - diff] || 0, y + diff)\n }\n }\n return dp['0']\n};" ]
957
prison-cells-after-n-days
[]
/** * @param {number[]} cells * @param {number} n * @return {number[]} */ var prisonAfterNDays = function(cells, n) { };
There are 8 prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. Otherwise, it becomes vacant. Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors. You are given an integer array cells where cells[i] == 1 if the ith cell is occupied and cells[i] == 0 if the ith cell is vacant, and you are given an integer n. Return the state of the prison after n days (i.e., n such changes described above).   Example 1: Input: cells = [0,1,0,1,1,0,0,1], n = 7 Output: [0,0,1,1,0,0,0,0] Explanation: The following table summarizes the state of the prison on each day: Day 0: [0, 1, 0, 1, 1, 0, 0, 1] Day 1: [0, 1, 1, 0, 0, 0, 0, 0] Day 2: [0, 0, 0, 0, 1, 1, 1, 0] Day 3: [0, 1, 1, 0, 0, 1, 0, 0] Day 4: [0, 0, 0, 0, 0, 1, 0, 0] Day 5: [0, 1, 1, 1, 0, 1, 0, 0] Day 6: [0, 0, 1, 0, 1, 1, 0, 0] Day 7: [0, 0, 1, 1, 0, 0, 0, 0] Example 2: Input: cells = [1,0,0,1,0,0,1,0], n = 1000000000 Output: [0,0,1,1,1,1,1,0]   Constraints: cells.length == 8 cells[i] is either 0 or 1. 1 <= n <= 109
Medium
[ "array", "hash-table", "math", "bit-manipulation" ]
[ "const prisonAfterNDays = function (cells, N) {\n const temp = [...cells]\n const maxIter = 2 * cells.length - 2\n N = N % maxIter === 0 ? maxIter : N % maxIter\n while (N > 0) {\n for (let i = 0; i < cells.length; i++) {\n temp[i] = cells[i - 1] === cells[i + 1] ? 1 : 0\n }\n cells = [...temp]\n N--\n }\n return cells\n}" ]
958
check-completeness-of-a-binary-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {boolean} */ var isCompleteTree = function(root) { };
Given the root of a binary tree, determine if it is a complete binary tree. In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.   Example 1: Input: root = [1,2,3,4,5,6] Output: true Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible. Example 2: Input: root = [1,2,3,4,5,null,7] Output: false Explanation: The node with value 7 isn't as far left as possible.   Constraints: The number of nodes in the tree is in the range [1, 100]. 1 <= Node.val <= 1000
Medium
[ "tree", "breadth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const isCompleteTree = function(root) {\n let cur = [root]\n let depth = 1\n while(cur.length) {\n const nxt = []\n // console.log(cur)\n for(let i = 0; i < cur.length; i++) {\n const e = cur[i]\n if(e == null) nxt.push(null, null)\n else if(e) nxt.push(e.left, e.right)\n }\n \n if(!valid(cur) || (cur[cur.length - 1] == null && valid(nxt))) {\n return false\n }\n \n if(nxt.some(e => e != null)) {\n cur = nxt\n } else {\n cur = []\n }\n depth++\n }\n \n return true\n \n function valid(arr) {\n let firstNull = arr.length, lastNonNull = arr.length\n for(let i = 0; i < arr.length; i++) {\n const e = arr[i]\n if(firstNull === arr.length && e == null) firstNull = i\n if(e != null) lastNonNull = i\n }\n // console.log(firstNull, lastNonNull)\n return firstNull >= lastNonNull\n }\n};" ]
959
regions-cut-by-slashes
[]
/** * @param {string[]} grid * @return {number} */ var regionsBySlashes = function(grid) { };
An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions. Given the grid grid represented as a string array, return the number of regions. Note that backslash characters are escaped, so a '\' is represented as '\\'.   Example 1: Input: grid = [" /","/ "] Output: 2 Example 2: Input: grid = [" /"," "] Output: 1 Example 3: Input: grid = ["/\\","\\/"] Output: 5 Explanation: Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.   Constraints: n == grid.length == grid[i].length 1 <= n <= 30 grid[i][j] is either '/', '\', or ' '.
Medium
[ "array", "hash-table", "depth-first-search", "breadth-first-search", "union-find", "matrix" ]
[ "const regionsBySlashes = function(grid) {\n const len = grid.length\n let regionsNum = 0\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n const matrix = Array.from({ length: 3 * len }, () => new Array(3 * len).fill(0))\n\n // 把每个格子切成3 * 3个小格子,再标记出现线段的位置\n for (let i = 0; i < len; i++) {\n for (let j = 0; j < len; j++) {\n if (grid[i][j] === '/') matrix[i * 3][j * 3 + 2] = matrix[i * 3 + 1][j * 3 + 1] = matrix[i * 3 + 2][j * 3] = 1\n if (grid[i][j] === '\\\\') matrix[i * 3][j * 3] = matrix[i * 3 + 1][j * 3 + 1] = matrix[i * 3 + 2][j * 3 + 2] = 1\n }\n }\n\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix.length; j++) {\n if (matrix[i][j] === 0) {\n dfs(matrix, i, j, dirs)\n regionsNum++\n }\n }\n }\n return regionsNum\n}\nfunction dfs(m, i, j, dirs) {\n if (i >= 0 && j >= 0 && i < m.length && j < m.length && m[i][j] === 0) {\n m[i][j] = 1\n for (let dir of dirs) dfs(m, i + dir[0], j + dir[1], dirs)\n }\n}" ]
960
delete-columns-to-make-sorted-iii
[]
/** * @param {string[]} strs * @return {number} */ var minDeletionSize = function(strs) { };
You are given an array of n strings strs, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"]. Suppose we chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), and so on). Return the minimum possible value of answer.length.   Example 1: Input: strs = ["babca","bbazb"] Output: 3 Explanation: After deleting columns 0, 1, and 4, the final array is strs = ["bc", "az"]. Both these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]). Note that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order. Example 2: Input: strs = ["edcba"] Output: 4 Explanation: If we delete less than 4 columns, the only row will not be lexicographically sorted. Example 3: Input: strs = ["ghi","def","abc"] Output: 0 Explanation: All rows are already lexicographically sorted.   Constraints: n == strs.length 1 <= n <= 100 1 <= strs[i].length <= 100 strs[i] consists of lowercase English letters.  
Hard
[ "array", "string", "dynamic-programming" ]
[ "const minDeletionSize = function(A) {\n const dp = new Array(A[0].length).fill(1)\n for (let i = 0; i < A[0].length; i++) {\n for (let j = 0; j < i; j++) {\n for (let k = 0; k <= A.length; k++) {\n if (k === A.length) dp[i] = Math.max(dp[i], dp[j] + 1)\n else if (A[k][j] > A[k][i]) break\n }\n }\n }\n return A[0].length - Math.max(...dp)\n}", "const minDeletionSize = function(A) {\n const rows = A.length\n const cols = A[0].length\n let res = cols - 1\n let k\n const dp = new Array(cols).fill(1)\n for (let i = 0; i < cols; i++) {\n for (let j = 0; j < i; j++) {\n for (k = 0; k < rows; k++) {\n if (A[k][j] > A[k][i]) break\n }\n if (k === rows && dp[j] + 1 > dp[i]) dp[i] = dp[j] + 1\n }\n res = Math.min(res, cols - dp[i])\n }\n return res\n}" ]
961
n-repeated-element-in-size-2n-array
[]
/** * @param {number[]} nums * @return {number} */ var repeatedNTimes = function(nums) { };
You are given an integer array nums with the following properties: nums.length == 2 * n. nums contains n + 1 unique elements. Exactly one element of nums is repeated n times. Return the element that is repeated n times.   Example 1: Input: nums = [1,2,3,3] Output: 3 Example 2: Input: nums = [2,1,2,5,3,2] Output: 2 Example 3: Input: nums = [5,1,5,2,5,3,5,4] Output: 5   Constraints: 2 <= n <= 5000 nums.length == 2 * n 0 <= nums[i] <= 104 nums contains n + 1 unique elements and one of them is repeated exactly n times.
Easy
[ "array", "hash-table" ]
[ "const repeatedNTimes = function(A) {\n const checkerSet = new Set();\n for (let num of A){\n if (!checkerSet.has(num)){\n checkerSet.add(num);\n } else{\n return num;\n }\n }\n};" ]
962
maximum-width-ramp
[]
/** * @param {number[]} nums * @return {number} */ var maxWidthRamp = function(nums) { };
A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i. Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.   Example 1: Input: nums = [6,0,8,2,1,5] Output: 4 Explanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5. Example 2: Input: nums = [9,8,1,0,1,9,4,0,4,1] Output: 7 Explanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.   Constraints: 2 <= nums.length <= 5 * 104 0 <= nums[i] <= 5 * 104
Medium
[ "array", "stack", "monotonic-stack" ]
null
[]
963
minimum-area-rectangle-ii
[]
/** * @param {number[][]} points * @return {number} */ var minAreaFreeRect = function(points) { };
You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return 0. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: points = [[1,2],[2,1],[1,0],[0,1]] Output: 2.00000 Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2. Example 2: Input: points = [[0,1],[2,1],[1,1],[1,0],[2,0]] Output: 1.00000 Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1. Example 3: Input: points = [[0,3],[1,2],[3,1],[1,3],[2,1]] Output: 0 Explanation: There is no possible rectangle to form from these points.   Constraints: 1 <= points.length <= 50 points[i].length == 2 0 <= xi, yi <= 4 * 104 All the given points are unique.
Medium
[ "array", "math", "geometry" ]
null
[]
964
least-operators-to-express-number
[]
/** * @param {number} x * @param {number} target * @return {number} */ var leastOpsExpressTarget = function(x, target) { };
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happen before addition and subtraction. It is not allowed to use the unary negation operator (-). For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Constraints: 2 <= x <= 100 1 <= target <= 2 * 108
Hard
[ "math", "dynamic-programming", "memoization" ]
[ "const leastOpsExpressTarget = function(x, target) {\n let pows = [1]\n while (pows[pows.length - 1] < target) {\n pows.push(pows[pows.length - 1] * x)\n }\n let dp = {}\n for (let i = 0; i < pows.length; i++) {\n dp[pows[i]] = Math.abs(i - 1) + 1\n }\n let dpFunc = (t, unit) => {\n if (t <= 0) return 0\n if (dp[t]) return dp[t]\n let cur = t % (unit * x)\n let count = dp[unit]\n let pos = dpFunc(t - cur, unit * x) + (cur / unit) * count\n let neg = dpFunc(t + x * unit - cur, unit * x) + (x - cur / unit) * count\n dp[t] = Math.min(pos, neg)\n return dp[t]\n }\n return dpFunc(target, 1) - 1\n}", "const leastOpsExpressTarget = function(x, y) {\n let pos = 0,\n neg = 0,\n k = 0,\n pos2,\n neg2,\n cur\n while (y > 0) {\n cur = y % x\n y = (y / x) >> 0\n if (k > 0) {\n pos2 = Math.min(cur * k + pos, (cur + 1) * k + neg)\n neg2 = Math.min((x - cur) * k + pos, (x - cur - 1) * k + neg)\n pos = pos2\n neg = neg2\n } else {\n pos = cur * 2\n neg = (x - cur) * 2\n }\n k++\n }\n return Math.min(pos, k + neg) - 1\n}" ]
965
univalued-binary-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {boolean} */ var isUnivalTree = function(root) { };
A binary tree is uni-valued if every node in the tree has the same value. Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.   Example 1: Input: root = [1,1,1,1,1,null,1] Output: true Example 2: Input: root = [2,2,2,5,2] Output: false   Constraints: The number of nodes in the tree is in the range [1, 100]. 0 <= Node.val < 100
Easy
[ "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const isUnivalTree = function(root) {\n const arr = []\n dfs(root, arr)\n for(let i = 1; i < arr.length; i++) {\n if(arr[i] !== arr[i- 1]) return false\n }\n return true\n};\n\nfunction dfs(node, arr) {\n if(node === null) return\n arr.push(node.val)\n dfs(node.left, arr)\n dfs(node.right, arr)\n}" ]
966
vowel-spellchecker
[]
/** * @param {string[]} wordlist * @param {string[]} queries * @return {string[]} */ var spellchecker = function(wordlist, queries) { };
Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word. For a given query word, the spell checker handles two categories of spelling mistakes: Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist. Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow" Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow" Example: wordlist = ["yellow"], query = "yellow": correct = "yellow" Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist. Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw" Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match) Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match) In addition, the spell checker operates under the following precedence rules: When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back. When the query matches a word up to capitlization, you should return the first such match in the wordlist. When the query matches a word up to vowel errors, you should return the first such match in the wordlist. If the query has no matches in the wordlist, you should return the empty string. Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].   Example 1: Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"] Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"] Example 2: Input: wordlist = ["yellow"], queries = ["YellOw"] Output: ["yellow"]   Constraints: 1 <= wordlist.length, queries.length <= 5000 1 <= wordlist[i].length, queries[i].length <= 7 wordlist[i] and queries[i] consist only of only English letters.
Medium
[ "array", "hash-table", "string" ]
null
[]
967
numbers-with-same-consecutive-differences
[]
/** * @param {number} n * @param {number} k * @return {number[]} */ var numsSameConsecDiff = function(n, k) { };
Given two integers n and k, return an array of all the integers of length n where the difference between every two consecutive digits is k. You may return the answer in any order. Note that the integers should not have leading zeros. Integers as 02 and 043 are not allowed.   Example 1: Input: n = 3, k = 7 Output: [181,292,707,818,929] Explanation: Note that 070 is not a valid number, because it has leading zeroes. Example 2: Input: n = 2, k = 1 Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]   Constraints: 2 <= n <= 9 0 <= k <= 9
Medium
[ "backtracking", "breadth-first-search" ]
[ "const numsSameConsecDiff = function (n, k) {\n const res = []\n \n for(let i = 1; i <= 9; i++) {\n dfs(n - 1, [i])\n }\n \n return res\n\n function dfs(num, arr) {\n if(num === 0) {\n res.push(+arr.join(''))\n return \n }\n\n for(let i = 0; i <= 9; i++) {\n if(Math.abs(i - arr[arr.length - 1]) === k) {\n arr.push(i)\n dfs(num - 1, arr)\n arr.pop()\n }\n }\n }\n}" ]
968
binary-tree-cameras
[]
/** * 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 minCameraCover = function(root) { };
You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all nodes of the tree.   Example 1: Input: root = [0,0,null,0,0] Output: 1 Explanation: One camera is enough to monitor all nodes if placed as shown. Example 2: Input: root = [0,0,null,0,null,0,null,null,0] Output: 2 Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.   Constraints: The number of nodes in the tree is in the range [1, 1000]. Node.val == 0
Hard
[ "dynamic-programming", "tree", "depth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const minCameraCover = function(root) {\n if (root === null) return 0;\n let max = 0;\n return (helper(root) < 1 ? 1 : 0) + max;\n function helper(root) {\n if (root === null) return 2;\n if (root.left === null && root.right === null) return 0;\n let left = helper(root.left);\n let right = helper(root.right);\n if (left === 0 || right === 0) {\n max++;\n return 1;\n }\n return left === 1 || right === 1 ? 2 : 0;\n }\n};\n\n // another\n\n\nconst minCameraCover = function(root) {\n let ans = 0\n const covered = new Set([null])\n dfs(root, null)\n return ans\n function dfs(node, parent) {\n if (node) {\n dfs(node.left, node)\n dfs(node.right, node)\n if (\n !(\n (parent || covered.has(node)) &&\n covered.has(node.left) &&\n covered.has(node.right)\n )\n ) {\n ans += 1\n covered\n .add(node)\n .add(parent)\n .add(node.left)\n .add(node.right)\n }\n }\n }\n};" ]
969
pancake-sorting
[]
/** * @param {number[]} arr * @return {number[]} */ var pancakeSort = function(arr) { };
Given an array of integers arr, sort the array by performing a series of pancake flips. In one pancake flip we do the following steps: Choose an integer k where 1 <= k <= arr.length. Reverse the sub-array arr[0...k-1] (0-indexed). For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3. Return an array of the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.   Example 1: Input: arr = [3,2,4,1] Output: [4,2,4,3] Explanation: We perform 4 pancake flips, with k values 4, 2, 4, and 3. Starting state: arr = [3, 2, 4, 1] After 1st flip (k = 4): arr = [1, 4, 2, 3] After 2nd flip (k = 2): arr = [4, 1, 2, 3] After 3rd flip (k = 4): arr = [3, 2, 1, 4] After 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted. Example 2: Input: arr = [1,2,3] Output: [] Explanation: The input is already sorted, so there is no need to flip anything. Note that other answers, such as [3, 3], would also be accepted.   Constraints: 1 <= arr.length <= 100 1 <= arr[i] <= arr.length All integers in arr are unique (i.e. arr is a permutation of the integers from 1 to arr.length).
Medium
[ "array", "two-pointers", "greedy", "sorting" ]
[ " const pancakeSort = function (arr) {\n const res = []\n let n = arr.length\n while(n) {\n const idx = indexOf(0, n - 1, n)\n if(idx === n - 1) {\n n--\n } else {\n flip(0, idx)\n flip(0, n - 1)\n res.push(idx + 1, n)\n n--\n }\n }\n return res\n\n function flip(l, r) {\n while(l < r) {\n const tmp = arr[l]\n arr[l] = arr[r]\n arr[r] = tmp\n l++\n r--\n }\n }\n\n function indexOf(start, end, target) {\n let res = -1\n for(let i = start; i <= end; i++) {\n if(arr[i]===target) {\n res = i\n break\n }\n }\n return res\n }\n}" ]
970
powerful-integers
[]
/** * @param {number} x * @param {number} y * @param {number} bound * @return {number[]} */ var powerfulIntegers = function(x, y, bound) { };
Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound. An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0. You may return the answer in any order. In your answer, each value should occur at most once.   Example 1: Input: x = 2, y = 3, bound = 10 Output: [2,3,4,5,7,9,10] Explanation: 2 = 20 + 30 3 = 21 + 30 4 = 20 + 31 5 = 21 + 31 7 = 22 + 31 9 = 23 + 30 10 = 20 + 32 Example 2: Input: x = 3, y = 5, bound = 15 Output: [2,4,6,8,10,14]   Constraints: 1 <= x, y <= 100 0 <= bound <= 106
Medium
[ "hash-table", "math" ]
null
[]
971
flip-binary-tree-to-match-preorder-traversal
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number[]} voyage * @return {number[]} */ var flipMatchVoyage = function(root, voyage) { };
You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree. Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage. Return a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage, return the list [-1].   Example 1: Input: root = [1,2], voyage = [2,1] Output: [-1] Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage. Example 2: Input: root = [1,2,3], voyage = [1,3,2] Output: [1] Explanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. Example 3: Input: root = [1,2,3], voyage = [1,2,3] Output: [] Explanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.   Constraints: The number of nodes in the tree is n. n == voyage.length 1 <= n <= 100 1 <= Node.val, voyage[i] <= n All the values in the tree are unique. All the values in voyage are unique.
Medium
[ "tree", "depth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const flipMatchVoyage = function (root, voyage) {\n const n = voyage.length\n const res = []\n let idx = 0\n return dfs(root, 0) ? res : [-1]\n\n function dfs(node) {\n if (node == null) return true\n if (node.val !== voyage[idx]) {\n return false\n }\n idx++\n if (node.left && node.left.val !== voyage[idx]) {\n res.push(node.val)\n return dfs(node.right) && dfs(node.left)\n }\n return dfs(node.left) && dfs(node.right)\n }\n}" ]
972
equal-rational-numbers
[]
/** * @param {string} s * @param {string} t * @return {boolean} */ var isRationalEqual = function(s, t) { };
Given two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A rational number can be represented using up to three parts: <IntegerPart>, <NonRepeatingPart>, and a <RepeatingPart>. The number will be represented in one of the following three ways: <IntegerPart> For example, 12, 0, and 123. <IntegerPart><.><NonRepeatingPart> For example, 0.5, 1., 2.12, and 123.0001. <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)> For example, 0.1(6), 1.(9), 123.00(1212). The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: 1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66).   Example 1: Input: s = "0.(52)", t = "0.5(25)" Output: true Explanation: Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number. Example 2: Input: s = "0.1666(6)", t = "0.166(66)" Output: true Example 3: Input: s = "0.9(9)", t = "1." Output: true Explanation: "0.9(9)" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.] "1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "".   Constraints: Each part consists only of digits. The <IntegerPart> does not have leading zeros (except for the zero itself). 1 <= <IntegerPart>.length <= 4 0 <= <NonRepeatingPart>.length <= 4 1 <= <RepeatingPart>.length <= 4
Hard
[ "math", "string" ]
[ "const isRationalEqual = function (S, T) {\n return f(S) === f(T)\n}\n\nfunction f(S) {\n let i = S.indexOf('(')\n if (i > 0) {\n let base = S.slice(0, i)\n let rep = S.slice(i + 1, S.length - 1)\n for (let j = 0; j < 20; ++j) base += rep\n return +base\n }\n return +S\n}" ]
973
k-closest-points-to-origin
[]
/** * @param {number[][]} points * @param {number} k * @return {number[][]} */ var kClosest = function(points, k) { };
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).   Example 1: Input: points = [[1,3],[-2,2]], k = 1 Output: [[-2,2]] Explanation: The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. Example 2: Input: points = [[3,3],[5,-1],[-2,4]], k = 2 Output: [[3,3],[-2,4]] Explanation: The answer [[-2,4],[3,3]] would also be accepted.   Constraints: 1 <= k <= points.length <= 104 -104 <= xi, yi <= 104
Medium
[ "array", "math", "divide-and-conquer", "geometry", "sorting", "heap-priority-queue", "quickselect" ]
[ "const kClosest = (points, K) => {\n let len = points.length,\n l = 0,\n r = len - 1\n while (l <= r) {\n let mid = helper(points, l, r)\n if (mid === K) break\n if (mid < K) {\n l = mid + 1\n } else {\n r = mid - 1\n }\n }\n return points.slice(0, K)\n}\n\nfunction helper(A, l, r) {\n let pivot = A[l]\n let ll = l\n while (l < r) {\n while (l < r && compare(A[r], pivot) >= 0) r--\n while (l < r && compare(A[l], pivot) <= 0) l++\n swap(A, l, r)\n }\n swap(A, ll, l)\n return l\n}\nfunction swap(arr, i, j) {\n let tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n}\n\nfunction compare(p1, p2) {\n return p1[0] * p1[0] + p1[1] * p1[1] - p2[0] * p2[0] - p2[1] * p2[1]\n}", "const kClosest = (points, K) => {\n const pq = new PriorityQueue(\n (p1, p2) => p1[0] * p1[0] + p1[1] * p1[1] > p2[0] * p2[0] + p2[1] * p2[1]\n )\n for (let p of points) {\n pq.push(p)\n if (pq.size() > K) {\n pq.pop()\n }\n }\n const res = new Array(K)\n while (K > 0) {\n res[--K] = pq.pop()\n }\n return res\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}", "const kClosest = function(points, k) {\n let len = points.length, l = 0, r = len - 1\n while (l <= r) {\n let mid = helper(points, l, r)\n if (mid === k) break\n if (mid < k) l = mid + 1\n else r = mid - 1\n }\n return points.slice(0, k)\n\n function helper(arr, l, r) {\n const pivot = arr[l]\n while(l < r) {\n while(l < r && cmp(arr[r], pivot) >= 0) r--\n arr[l] = arr[r]\n while(l < r && cmp(arr[l], pivot) <= 0) l++\n arr[r] = arr[l]\n }\n arr[l] = pivot\n return l\n }\n \n function cmp(a, b) {\n return a[0] * a[0] + a[1] * a[1] - b[0] * b[0] - b[1] * b[1]\n }\n};" ]
974
subarray-sums-divisible-by-k
[]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var subarraysDivByK = function(nums, k) { };
Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k. A subarray is a contiguous part of an array.   Example 1: Input: nums = [4,5,0,-2,-3,1], k = 5 Output: 7 Explanation: There are 7 subarrays with a sum divisible by k = 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] Example 2: Input: nums = [5], k = 9 Output: 0   Constraints: 1 <= nums.length <= 3 * 104 -104 <= nums[i] <= 104 2 <= k <= 104
Medium
[ "array", "hash-table", "prefix-sum" ]
[ "const subarraysDivByK = function (nums, k) {\n const memo = {0: 1}\n let sum = 0, res = 0\n for(const e of nums) {\n sum += e\n const remain = ( sum % k + k) % k\n res += memo[remain] ?? 0\n memo[remain] = (memo[remain] ?? 0) + 1 \n }\n return res\n}", "const subarraysDivByK = function(nums, k) {\n const memo = {0: 1}\n let sum = 0, res = 0\n for(const e of nums) {\n sum += e\n const remain = (k - (sum % k)) % k\n res += memo[remain] ?? 0\n memo[remain] = (memo[remain] ?? 0) + 1 \n }\n return res\n};" ]
975
odd-even-jump
[]
/** * @param {number[]} arr * @return {number} */ var oddEvenJumps = function(arr) { };
You are given an integer array arr. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices. You may jump forward from index i to index j (with i < j) in the following way: During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j, you can only jump to the smallest such index j. During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j, you can only jump to the smallest such index j. It may be the case that for some index i, there are no legal jumps. A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once). Return the number of good starting indices.   Example 1: Input: arr = [10,13,12,14,15] Output: 2 Explanation: From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more. From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more. From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end. From starting index i = 4, we have reached the end already. In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of jumps. Example 2: Input: arr = [2,3,1,1,4] Output: 3 Explanation: From starting index i = 0, we make jumps to i = 1, i = 2, i = 3: During our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0]. During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3 During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2]. We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good. In a similar manner, we can deduce that: From starting index i = 1, we jump to i = 4, so we reach the end. From starting index i = 2, we jump to i = 3, and then we can't jump anymore. From starting index i = 3, we jump to i = 4, so we reach the end. From starting index i = 4, we are already at the end. In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some number of jumps. Example 3: Input: arr = [5,1,3,4,2] Output: 3 Explanation: We can reach the end from starting indices 1, 2, and 4.   Constraints: 1 <= arr.length <= 2 * 104 0 <= arr[i] < 105
Hard
[ "array", "dynamic-programming", "stack", "monotonic-stack", "ordered-set" ]
[ "const oddEvenJumps = function (A) {\n // Creates an array with ONLY the indices of the sorted array\n let sorted = A.map((el, idx) => idx).sort((a, b) => A[a] - A[b] || a - b)\n // Create an array of '-1's of the same array length for odd and even jumps\n let oddJumps = new Array(A.length).fill(-1)\n let evenJumps = new Array(A.length).fill(-1)\n // Create an empty stack\n let stack = []\n // Loop the the sorted array of the indices\n for (let i of sorted) {\n // Loops as long the stack is full OR if the index is greater than the the last index of the stack\n while (stack.length && i > stack[stack.length - 1]) {\n // Pops the index from the stack and place and add the 'i' index in sortedJumps\n oddJumps[stack.pop()] = i\n }\n // Pushes the index onto the stack\n stack.push(i)\n }\n // Empty the stack\n stack = []\n // Reverses the sorted index array\n let reverseSorted = sorted.sort((a, b) => A[b] - A[a] || a - b)\n // Does the exact thing but for even jumps\n for (let i of reverseSorted) {\n while (stack.length && i > stack[stack.length - 1]) {\n evenJumps[stack.pop()] = i\n }\n stack.push(i)\n }\n // Starts the count at 0\n let count = 1\n // Creates a boolean array of false elements for even and odd ends\n let oddEnd = new Array(A.length).fill(false)\n let evenEnd = new Array(A.length).fill(false)\n // Switches the end of each array to true\n oddEnd[A.length - 1] = true\n evenEnd[A.length - 1] = true\n // Loops through the array, starting from the 2nd from the right (since we do not need to worry about the last index)\n for (let i = A.length - 2; i >= 0; --i) {\n // If even jumps does\n if (evenJumps[i] !== -1 && oddEnd[evenJumps[i]]) evenEnd[i] = true\n if (oddJumps[i] !== -1 && evenEnd[oddJumps[i]]) {\n oddEnd[i] = true\n count++\n }\n }\n return count\n}" ]
976
largest-perimeter-triangle
[]
/** * @param {number[]} nums * @return {number} */ var largestPerimeter = function(nums) { };
Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.   Example 1: Input: nums = [2,1,2] Output: 5 Explanation: You can form a triangle with three side lengths: 1, 2, and 2. Example 2: Input: nums = [1,2,1,10] Output: 0 Explanation: You cannot use the side lengths 1, 1, and 2 to form a triangle. You cannot use the side lengths 1, 1, and 10 to form a triangle. You cannot use the side lengths 1, 2, and 10 to form a triangle. As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.   Constraints: 3 <= nums.length <= 104 1 <= nums[i] <= 106
Easy
[ "array", "math", "greedy", "sorting" ]
[ "const largestPerimeter = function(nums) {\n nums.sort((a, b) => a - b)\n for(let i = nums.length - 1; i > 1; i--) {\n if(nums[i] < nums[i - 1] + nums[i - 2]) return nums[i - 2] + nums[i - 1] + nums[i]\n }\n return 0\n};" ]
977
squares-of-a-sorted-array
[]
/** * @param {number[]} nums * @return {number[]} */ var sortedSquares = function(nums) { };
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.   Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121]   Constraints: 1 <= nums.length <= 104 -104 <= nums[i] <= 104 nums is sorted in non-decreasing order.   Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?
Easy
[ "array", "two-pointers", "sorting" ]
[ "const sortedSquares = function(A) {\n const result = [];\n let i = A.length - 1;\n let left = 0;\n let right = A.length -1;\n while (left <= right) {\n if (Math.abs(A[left]) < A[right]) {\n result.unshift(A[right] * A[right])\n right--;\n } else {\n result.unshift(A[left] * A[left])\n left++\n }\n }\n return result;\n};" ]
978
longest-turbulent-subarray
[]
/** * @param {number[]} arr * @return {number} */ var maxTurbulenceSize = function(arr) { };
Given an integer array arr, return the length of a maximum size turbulent subarray of arr. A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if: For i <= k < j: arr[k] > arr[k + 1] when k is odd, and arr[k] < arr[k + 1] when k is even. Or, for i <= k < j: arr[k] > arr[k + 1] when k is even, and arr[k] < arr[k + 1] when k is odd.   Example 1: Input: arr = [9,4,2,10,7,8,8,1,9] Output: 5 Explanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5] Example 2: Input: arr = [4,8,12,16] Output: 2 Example 3: Input: arr = [100] Output: 1   Constraints: 1 <= arr.length <= 4 * 104 0 <= arr[i] <= 109
Medium
[ "array", "dynamic-programming", "sliding-window" ]
[ "const maxTurbulenceSize = function(arr) {\n const n = arr.length\n \n return Math.max(helper(), helper1())\n // < > <\n function helper() {\n const cnt = Array(n).fill(1)\n \n for(let i = 0; i < n - 1; i++) {\n if(i % 2 === 1 && arr[i] > arr[i + 1]) {\n cnt[i + 1] = cnt[i] + 1\n } else if(i % 2 === 0 && arr[i] < arr[i + 1]) {\n cnt[i + 1] = cnt[i] + 1\n }\n }\n \n return Math.max(...cnt)\n }\n \n function helper1() {\n const cnt = Array(n).fill(1)\n \n for(let i = 0; i < n - 1; i++) {\n if(i % 2 === 1 && arr[i] < arr[i + 1] ) {\n cnt[i + 1] = cnt[i] + 1\n } else if(i % 2 === 0 && arr[i] > arr[i + 1] ) {\n cnt[i + 1] = cnt[i] + 1\n }\n }\n \n return Math.max(...cnt)\n }\n};" ]
979
distribute-coins-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 distributeCoins = function(root) { };
You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the minimum number of moves required to make every node have exactly one coin.   Example 1: Input: root = [3,0,0] Output: 2 Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child. Example 2: Input: root = [0,3,0] Output: 3 Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.   Constraints: The number of nodes in the tree is n. 1 <= n <= 100 0 <= Node.val <= n The sum of all Node.val is n.
Medium
[ "tree", "depth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const distributeCoins = function(root) {\n let res = 0\n helper(root)\n return res\n \n function helper(node) {\n if(node == null) return 0\n const left = helper(node.left)\n const right = helper(node.right)\n res += Math.abs(left) + Math.abs(right)\n return node.val + left + right - 1\n }\n};" ]
980
unique-paths-iii
[]
/** * @param {number[][]} grid * @return {number} */ var uniquePathsIII = function(grid) { };
You are given an m x n integer array grid where grid[i][j] could be: 1 representing the starting square. There is exactly one starting square. 2 representing the ending square. There is exactly one ending square. 0 representing empty squares we can walk over. -1 representing obstacles that we cannot walk over. Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.   Example 1: Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]] Output: 2 Explanation: We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) Example 2: Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]] Output: 4 Explanation: We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) Example 3: Input: grid = [[0,1],[2,0]] Output: 0 Explanation: There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 20 1 <= m * n <= 20 -1 <= grid[i][j] <= 2 There is exactly one starting cell and one ending cell.
Hard
[ "array", "backtracking", "bit-manipulation", "matrix" ]
[ "const uniquePathsIII = function(grid) {\n const obj = {\n eNum: 1,\n res: 0,\n rows: grid.length,\n dirs: [[-1, 0], [1, 0], [0, -1], [0, 1]],\n sr: 0,\n sc: 0,\n er: 0,\n ec: 0\n }\n if (obj.rows === 0) return 0\n obj.cols = grid[0].length\n for (let i = 0; i < obj.rows; i++) {\n for (let j = 0; j < obj.cols; j++) {\n if (grid[i][j] === 0) obj.eNum++\n else if (grid[i][j] === 1) (obj.sr = i), (obj.sc = j)\n else if (grid[i][j] === 2) (obj.er = i), (obj.ec = j)\n }\n }\n bt(grid, obj.sr, obj.sc, obj)\n return obj.res\n}\n\nfunction bt(grid, x, y, obj) {\n if (x < 0 || x >= obj.rows || y < 0 || y >= obj.cols || grid[x][y] < 0) return\n if (x === obj.er && y === obj.ec) {\n if (obj.eNum === 0) obj.res++\n return\n }\n grid[x][y] = -2\n obj.eNum--\n for (let dir of obj.dirs) {\n bt(grid, x + dir[0], y + dir[1], obj)\n }\n obj.eNum++\n grid[x][y] = 0\n}" ]
981
time-based-key-value-store
[]
var TimeMap = function() { }; /** * @param {string} key * @param {string} value * @param {number} timestamp * @return {void} */ TimeMap.prototype.set = function(key, value, timestamp) { }; /** * @param {string} key * @param {number} timestamp * @return {string} */ TimeMap.prototype.get = function(key, timestamp) { }; /** * Your TimeMap object will be instantiated and called as such: * var obj = new TimeMap() * obj.set(key,value,timestamp) * var param_2 = obj.get(key,timestamp) */
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp. Implement the TimeMap class: TimeMap() Initializes the object of the data structure. void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp. String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns "".   Example 1: Input ["TimeMap", "set", "get", "get", "set", "get", "get"] [[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]] Output [null, null, "bar", "bar", null, "bar2", "bar2"] Explanation TimeMap timeMap = new TimeMap(); timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1. timeMap.get("foo", 1); // return "bar" timeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar". timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4. timeMap.get("foo", 4); // return "bar2" timeMap.get("foo", 5); // return "bar2"   Constraints: 1 <= key.length, value.length <= 100 key and value consist of lowercase English letters and digits. 1 <= timestamp <= 107 All the timestamps timestamp of set are strictly increasing. At most 2 * 105 calls will be made to set and get.
Medium
[ "hash-table", "string", "binary-search", "design" ]
[ "const TimeMap = function() {\n this.hash = {}\n};\n\n\nTimeMap.prototype.set = function(key, value, timestamp) {\n if(this.hash[key] == null) this.hash[key] = []\n this.hash[key].push([value, timestamp])\n};\n\n\nTimeMap.prototype.get = function(key, timestamp) {\n if(this.hash[key] == null) return ''\n const arr = this.hash[key]\n\n let l = 0, r = arr.length - 1;\n while(l <= r) {\n const pick = Math.floor((l + r) / 2);\n if (arr[pick][1] < timestamp) {\n l = pick + 1;\n } else if (arr[pick][1] > timestamp) {\n r = pick - 1\n } else {\n return arr[pick][0];\n }\n }\n return arr[r]?.[0] || ''\n};", "const TimeMap = function() {\n this.hash = {}\n};\n\n\nTimeMap.prototype.set = function(key, value, timestamp) {\n if(this.hash[key] == null) this.hash[key] = []\n this.hash[key].push([value, timestamp])\n};\n\n\nTimeMap.prototype.get = function(key, timestamp) {\n if(this.hash[key] == null) return ''\n const arr = this.hash[key]\n\n let l = 0, r = arr.length\n while(l < r) {\n const mid = l + ((r - l) >> 1)\n if(arr[mid][1] <= timestamp) {\n l = mid + 1\n } else {\n r = mid\n }\n }\n\n if(r === 0) return ''\n return arr[r - 1][0]\n};" ]
982
triples-with-bitwise-and-equal-to-zero
[]
/** * @param {number[]} nums * @return {number} */ var countTriplets = function(nums) { };
Given an integer array nums, return the number of AND triples. An AND triple is a triple of indices (i, j, k) such that: 0 <= i < nums.length 0 <= j < nums.length 0 <= k < nums.length nums[i] & nums[j] & nums[k] == 0, where & represents the bitwise-AND operator.   Example 1: Input: nums = [2,1,3] Output: 12 Explanation: We could choose the following i, j, k triples: (i=0, j=0, k=1) : 2 & 2 & 1 (i=0, j=1, k=0) : 2 & 1 & 2 (i=0, j=1, k=1) : 2 & 1 & 1 (i=0, j=1, k=2) : 2 & 1 & 3 (i=0, j=2, k=1) : 2 & 3 & 1 (i=1, j=0, k=0) : 1 & 2 & 2 (i=1, j=0, k=1) : 1 & 2 & 1 (i=1, j=0, k=2) : 1 & 2 & 3 (i=1, j=1, k=0) : 1 & 1 & 2 (i=1, j=2, k=0) : 1 & 3 & 2 (i=2, j=0, k=1) : 3 & 2 & 1 (i=2, j=1, k=0) : 3 & 1 & 2 Example 2: Input: nums = [0,0,0] Output: 27   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] < 216
Hard
[ "array", "hash-table", "bit-manipulation" ]
[ "const countTriplets = function (A) {\n const N = 1 << 16,\n M = 3\n const dp = Array.from({ length: M + 1 }, () => Array(N).fill(0))\n dp[0][N - 1] = 1\n for (let i = 0; i < M; i++) {\n for (let k = 0; k < N; k++) {\n for (let a of A) {\n dp[i + 1][k & a] += dp[i][k]\n }\n }\n }\n return dp[M][0]\n}" ]
983
minimum-cost-for-tickets
[]
/** * @param {number[]} days * @param {number[]} costs * @return {number} */ var mincostTickets = function(days, costs) { };
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365. Train tickets are sold in three different ways: a 1-day pass is sold for costs[0] dollars, a 7-day pass is sold for costs[1] dollars, and a 30-day pass is sold for costs[2] dollars. The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8. Return the minimum number of dollars you need to travel every day in the given list of days.   Example 1: Input: days = [1,4,6,7,8,20], costs = [2,7,15] Output: 11 Explanation: For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. Example 2: Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15] Output: 17 Explanation: For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel.   Constraints: 1 <= days.length <= 365 1 <= days[i] <= 365 days is in strictly increasing order. costs.length == 3 1 <= costs[i] <= 1000
Medium
[ "array", "dynamic-programming" ]
[ "const mincostTickets = function(days, costs) {\n const last7 = [], last30 = []\n let res = 0\n for(let d of days) {\n while(last7.length && last7[0][0] + 7 <= d) last7.shift()\n while(last30.length && last30[0][0] + 30 <= d) last30.shift()\n last7.push([d, res + costs[1]])\n last30.push([d, res + costs[2]])\n res = Math.min(res + costs[0], last7[0][1], last30[0][1])\n }\n return res\n};" ]
984
string-without-aaa-or-bbb
[]
/** * @param {number} a * @param {number} b * @return {string} */ var strWithout3a3b = function(a, b) { };
Given two integers a and b, return any string s such that: s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters, The substring 'aaa' does not occur in s, and The substring 'bbb' does not occur in s.   Example 1: Input: a = 1, b = 2 Output: "abb" Explanation: "abb", "bab" and "bba" are all correct answers. Example 2: Input: a = 4, b = 1 Output: "aabaa"   Constraints: 0 <= a, b <= 100 It is guaranteed such an s exists for the given a and b.
Medium
[ "string", "greedy" ]
[ "const strWithout3a3b = function (a, b) {\n let res = ''\n\n while(a > 0 || b > 0) {\n if(endsWith(res, 'aa')) {\n res += 'b'\n b--\n } else if(endsWith(res, 'bb')) {\n res += 'a'\n a--\n } else if(a >= b) {\n res += 'a'\n a--\n } else {\n res += 'b'\n b--\n }\n }\n\n return res\n\n function endsWith(str, sub) {\n let i = str.length - 1, j = sub.length - 1\n for(; i >=0 && j >= 0;i--,j--) {\n if(str[i] !== sub[j]) return false\n }\n if(j >= 0) return false\n\n return true\n }\n}", "const strWithout3a3b = function(a, b) {\n let m = a, n = b, ch1 = 'a', ch2 = 'b'\n if(b > a) {\n m = b, n = a, ch1 = 'b', ch2 = 'a'\n }\n let res = ''\n while(m-- > 0) {\n res += ch1\n if(m > n) {\n res += ch1\n m--\n }\n if(n > 0) {\n res += ch2\n n--\n }\n }\n return res\n};", "const strWithout3a3b = function (a, b, ac = 'a', bc = 'b') {\n const delta = a - b\n let res = ''\n if (delta < 0) {\n return strWithout3a3b(b, a, 'b', 'a')\n } else {\n while(a-- > 0) {\n res += ac\n if(a > b) res += ac, a--\n if(b-- > 0) res += bc\n }\n }\n\n return res\n}" ]
985
sum-of-even-numbers-after-queries
[]
/** * @param {number[]} nums * @param {number[][]} queries * @return {number[]} */ var sumEvenAfterQueries = function(nums, queries) { };
You are given an integer array nums and an array queries where queries[i] = [vali, indexi]. For each query i, first, apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values of nums. Return an integer array answer where answer[i] is the answer to the ith query.   Example 1: Input: nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]] Output: [8,6,2,4] Explanation: At the beginning, the array is [1,2,3,4]. After adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8. After adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6. After adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2. After adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4. Example 2: Input: nums = [1], queries = [[4,0]] Output: [0]   Constraints: 1 <= nums.length <= 104 -104 <= nums[i] <= 104 1 <= queries.length <= 104 -104 <= vali <= 104 0 <= indexi < nums.length
Medium
[ "array", "simulation" ]
[ "const sumEvenAfterQueries = function(A, queries) {\n const res = []\n for(let i = 0; i < queries.length; i++) {\n A[queries[i][1]] += queries[i][0]\n res.push(sum(A))\n }\n return res\n};\n\nfunction sum(arr) {\n return arr.reduce((ac, el) => ac + (el % 2 === 0 ? el : 0), 0)\n}", "const sumEvenAfterQueries = function(A, queries) {\n let sum = A.reduce((acc, cur) => cur%2 == 0 ? acc + cur : acc, 0);\n return queries.map((q) => {\n let i = q[1];\n let s = A[i] + q[0];\n if(s%2 === 0) {\n sum += q[0];\n if(A[i]%2 !== 0) sum += A[i];\n } else if(A[i]%2 === 0) sum -= A[i];\n A[i] = s;\n return sum;\n });\n};" ]
986
interval-list-intersections
[]
/** * @param {number[][]} firstList * @param {number[][]} secondList * @return {number[][]} */ var intervalIntersection = function(firstList, secondList) { };
You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists. A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].   Example 1: Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]] Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] Example 2: Input: firstList = [[1,3],[5,9]], secondList = [] Output: []   Constraints: 0 <= firstList.length, secondList.length <= 1000 firstList.length + secondList.length >= 1 0 <= starti < endi <= 109 endi < starti+1 0 <= startj < endj <= 109 endj < startj+1
Medium
[ "array", "two-pointers" ]
[ "const intervalIntersection = function (A, B) {\n const intersection = []\n let i = (j = 0)\n while (i < A.length && j < B.length) {\n const min = Math.max(A[i][0], B[j][0])\n const max = Math.min(A[i][1], B[j][1])\n if (min <= max) intersection.push([min, max])\n A[i][1] > B[j][1] ? j++ : i++\n }\n return intersection\n}" ]
987
vertical-order-traversal-of-a-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 verticalTraversal = function(root) { };
Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0). The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree.   Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[9],[3,15],[20],[7]] Explanation: Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. Example 2: Input: root = [1,2,3,4,5,6,7] Output: [[4],[2],[1,5,6],[3],[7]] Explanation: Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. Example 3: Input: root = [1,2,3,4,6,5,7] Output: [[4],[2],[1,5,6],[3],[7]] Explanation: This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.   Constraints: The number of nodes in the tree is in the range [1, 1000]. 0 <= Node.val <= 1000
Hard
[ "hash-table", "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const verticalTraversal = function(root) {\n const arr = []\n helper(root, 0, 0, arr)\n arr.sort((a, b) => a[0] - b[0] || b[1] - a[1] || a[2] - b[2])\n const res = new Map()\n\n for(let [x, y, val] of arr) {\n if(!res.has(x)) res.set(x, [])\n res.get(x).push(val)\n }\n return [...res.values()]\n};\n\nfunction helper(node, x, y, arr) {\n if(node) {\n helper(node.left, x - 1, y - 1, arr)\n arr.push([x, y, node.val])\n helper(node.right, x + 1, y - 1, arr)\n }\n}" ]
988
smallest-string-starting-from-leaf
[]
/** * 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 smallestFromLeaf = function(root) { };
You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'. Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root. As a reminder, any shorter prefix of a string is lexicographically smaller. For example, "ab" is lexicographically smaller than "aba". A leaf of a node is a node that has no children.   Example 1: Input: root = [0,1,2,3,4,3,4] Output: "dba" Example 2: Input: root = [25,1,3,1,3,0,2] Output: "adz" Example 3: Input: root = [2,2,1,null,1,0,null,0] Output: "abc"   Constraints: The number of nodes in the tree is in the range [1, 8500]. 0 <= Node.val <= 25
Medium
[ "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 smallestFromLeaf = function(root) {\n const res = []\n chk(root, [], res)\n res.sort()\n return res[0]\n};\n\nfunction chk(node, path, res) {\n if(node == null) return\n path.push(node.val)\n if(node.left == null && node.right == null) {\n res.push(arrToStr( path.slice(0).reverse() ))\n return\n }\n chk(node.left, path.slice(0), res)\n chk(node.right, path.slice(0), res)\n}\n\nfunction numToChar(num) {\n const str = 'abcdefghijklmnopqrstuvwxyz'\n return str[num]\n}\n\nfunction arrToStr(arr) {\n let res = ''\n for(let i = 0; i < arr.length; i++) {\n res += numToChar(arr[i])\n }\n return res\n}", "const smallestFromLeaf = function(root) {\n if (!root) return ''\n const char = String.fromCharCode(97 + root.val)\n let left = smallestFromLeaf(root.left)\n let right = smallestFromLeaf(root.right)\n if (!left) return right + char\n if (!right) return left + char\n return (left < right ? left : right) + char\n};" ]
989
add-to-array-form-of-integer
[]
/** * @param {number[]} num * @param {number} k * @return {number[]} */ var addToArrayForm = function(num, k) { };
The array-form of an integer num is an array representing its digits in left to right order. For example, for num = 1321, the array form is [1,3,2,1]. Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.   Example 1: Input: num = [1,2,0,0], k = 34 Output: [1,2,3,4] Explanation: 1200 + 34 = 1234 Example 2: Input: num = [2,7,4], k = 181 Output: [4,5,5] Explanation: 274 + 181 = 455 Example 3: Input: num = [2,1,5], k = 806 Output: [1,0,2,1] Explanation: 215 + 806 = 1021   Constraints: 1 <= num.length <= 104 0 <= num[i] <= 9 num does not contain any leading zeros except for the zero itself. 1 <= k <= 104
Easy
[ "array", "math" ]
[ "const addToArrayForm = function(num, k) {\n const res = []\n for(let i = num.length - 1; i >= 0; i--) {\n const tmp = num[i] + k\n res.push(tmp % 10)\n k = ~~(tmp / 10)\n }\n\n while(k > 0) {\n res.push(k % 10)\n k = ~~(k / 10)\n }\n res.reverse()\n return res\n};" ]
990
satisfiability-of-equality-equations
[]
/** * @param {string[]} equations * @return {boolean} */ var equationsPossible = function(equations) { };
You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: "xi==yi" or "xi!=yi".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names. Return true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise.   Example 1: Input: equations = ["a==b","b!=a"] Output: false Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second. There is no way to assign the variables to satisfy both equations. Example 2: Input: equations = ["b==a","a==b"] Output: true Explanation: We could assign a = 1 and b = 1 to satisfy both equations.   Constraints: 1 <= equations.length <= 500 equations[i].length == 4 equations[i][0] is a lowercase letter. equations[i][1] is either '=' or '!'. equations[i][2] is '='. equations[i][3] is a lowercase letter.
Medium
[ "array", "string", "union-find", "graph" ]
[ "const equationsPossible = function(equations) {\n const uf = new Array(26).fill(0);\n const aCode = ('a').charCodeAt(0)\n\n for (let i = 0; i < 26; ++i) uf[i] = i;\n for (let e of equations)\n if (e.charAt(1) === '=')\n uf[find(e.charCodeAt(0) - aCode)] = find(e.charCodeAt(3) - aCode);\n for (let e of equations)\n if (e.charAt(1) === '!' && find(e.charCodeAt(0) - aCode) === find(e.charCodeAt(3) - aCode))\n return false;\n return true;\n\n\n function find(x) {\n if (x != uf[x]) uf[x] = find(uf[x]);\n return uf[x];\n }\n};", "const equationsPossible = function(equations) {\n const num = 26\n const visited = new Array(num).fill(false)\n const color = new Array(num).fill(-1)\n const adj = Array.from(new Array(num), el => [])\n const aCode = ('a').charCodeAt(0)\n for(let el of equations) {\n if(el[1] === '=') {\n adj[el[0].charCodeAt(0) - aCode].push(el[3].charCodeAt(0) - aCode)\n adj[el[3].charCodeAt(0) - aCode].push(el[0].charCodeAt(0) - aCode)\n }\n }\n let c = 0\n for(let i = 0; i < num; i++) {\n !visited[i] && dfs(i, c)\n c++\n }\n for(let el of equations) {\n if(el[1] === '!' && color[el[0].charCodeAt(0) - aCode] === color[el[3].charCodeAt(0) - aCode]) {\n return false\n }\n }\n return true\n \n function dfs(idx, val) {\n visited[idx] = true\n color[idx] = val\n for(let el of adj[idx]) {\n !visited[el] && dfs(el, val)\n }\n }\n};" ]