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
1,312
minimum-insertion-steps-to-make-a-string-palindrome
[ "Is dynamic programming suitable for this problem ?", "If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome." ]
/** * @param {string} s * @return {number} */ var minInsertions = function(s) { };
Given a string s. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward.   Example 1: Input: s = "zzazz" Output: 0 Explanation: The string "zzazz" is already palindrome we do not need any insertions. Example 2: Input: s = "mbadm" Output: 2 Explanation: String can be "mbdadbm" or "mdbabdm". Example 3: Input: s = "leetcode" Output: 5 Explanation: Inserting 5 characters the string becomes "leetcodocteel".   Constraints: 1 <= s.length <= 500 s consists of lowercase English letters.
Hard
[ "string", "dynamic-programming" ]
[ "const minInsertions = function (s) {\n const dp = [...Array(501)].map((x) => Array(501).fill(0))\n const N = s.length\n for (let i = N - 1; i >= 0; --i)\n for (let j = i + 1; j <= N; ++j)\n if (s[i] == s[j - 1]) dp[i][j] = dp[i + 1][j - 1]\n else dp[i][j] = 1 + Math.min(dp[i + 1][j], dp[i][j - 1])\n return dp[0][N]\n}" ]
1,313
decompress-run-length-encoded-list
[ "Decompress the given array by repeating nums[2*i+1] a number of times equal to nums[2*i]." ]
/** * @param {number[]} nums * @return {number[]} */ var decompressRLElist = function(nums) { };
We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0).  For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list.   Example 1: Input: nums = [1,2,3,4] Output: [2,4,4,4] Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2]. The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4]. At the end the concatenation [2] + [4,4,4] is [2,4,4,4]. Example 2: Input: nums = [1,1,2,3] Output: [1,3,3]   Constraints: 2 <= nums.length <= 100 nums.length % 2 == 0 1 <= nums[i] <= 100
Easy
[ "array" ]
[ "const decompressRLElist = function(nums) {\n const res = []\n for(let i = 0, n = nums.length; i < n - 1; i += 2) {\n const [freq, val] = [nums[i], nums[i + 1]]\n for(let j = 0; j < freq; j++) res.push(val)\n } \n \n return res\n};" ]
1,314
matrix-block-sum
[ "How to calculate the required sum for a cell (i,j) fast ?", "Use the concept of cumulative sum array.", "Create a cumulative sum matrix where dp[i][j] is the sum of all cells in the rectangle from (0,0) to (i,j), use inclusion-exclusion idea." ]
/** * @param {number[][]} mat * @param {number} k * @return {number[][]} */ var matrixBlockSum = function(mat, k) { };
Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for: i - k <= r <= i + k, j - k <= c <= j + k, and (r, c) is a valid position in the matrix.   Example 1: Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1 Output: [[12,21,16],[27,45,33],[24,39,28]] Example 2: Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2 Output: [[45,45,45],[45,45,45],[45,45,45]]   Constraints: m == mat.length n == mat[i].length 1 <= m, n, k <= 100 1 <= mat[i][j] <= 100
Medium
[ "array", "matrix", "prefix-sum" ]
[ "const matrixBlockSum = function(mat, k) {\n const m = mat.length, n = mat[0].length\n const rangeSum = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n rangeSum[i + 1][j + 1] = rangeSum[i + 1][j] + rangeSum[i][j + 1] - rangeSum[i][j] + mat[i][j]\n }\n }\n const res = Array.from({ length: m }, () => Array(n).fill(0))\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n let r1 = Math.max(0, i - k), c1 = Math.max(0, j - k)\n let r2 = Math.min(m, i + k + 1), c2 = Math.min(n, j + k + 1)\n res[i][j] = rangeSum[r2][c2] - rangeSum[r2][c1] - rangeSum[r1][c2] + rangeSum[r1][c1]\n }\n }\n\n return res\n};" ]
1,315
sum-of-nodes-with-even-valued-grandparent
[ "Traverse the tree keeping the parent and the grandparent.", "If the grandparent of the current node is even-valued, add the value of this node to the answer." ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var sumEvenGrandparent = function(root) { };
Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0. A grandparent of a node is the parent of its parent if it exists.   Example 1: Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 18 Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents. Example 2: Input: root = [1] Output: 0   Constraints: The number of nodes in the tree is in the range [1, 104]. 1 <= Node.val <= 100
Medium
[ "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const sumEvenGrandparent = function(root) {\n let res = 0\n dfs(root, null, null)\n return res\n \n \n function dfs(node, parent, gp) {\n if(node == null) return\n if(parent && gp && gp.val % 2 === 0) {\n res += node.val\n }\n dfs(node.left, node, parent)\n dfs(node.right, node, parent)\n }\n \n};" ]
1,316
distinct-echo-substrings
[ "Given a substring of the text, how to check if it can be written as the concatenation of a string with itself ?", "We can do that in linear time, a faster way is to use hashing.", "Try all substrings and use hashing to check them." ]
/** * @param {string} text * @return {number} */ var distinctEchoSubstrings = function(text) { };
Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).   Example 1: Input: text = "abcabcabc" Output: 3 Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab". Example 2: Input: text = "leetcodeleetcode" Output: 2 Explanation: The 2 substrings are "ee" and "leetcodeleetcode".   Constraints: 1 <= text.length <= 2000 text has only lowercase English letters.
Hard
[ "string", "trie", "rolling-hash", "hash-function" ]
[ "const distinctEchoSubstrings = function (text) {\n const set = new Set()\n for(let len = 1; len <= text.length / 2; len++) {\n for(let l = 0, r = len, count = 0; l < text.length - len; l++, r++) {\n if(text.charAt(l) === text.charAt(r)) count++\n else count = 0\n\n if(count === len) {\n set.add(text.slice(l - len + 1, l + 1))\n count--\n }\n }\n }\n return set.size\n}" ]
1,317
convert-integer-to-the-sum-of-two-no-zero-integers
[ "Loop through all elements from 1 to n.", "Choose A = i and B = n - i then check if A and B are both No-Zero integers." ]
/** * @param {number} n * @return {number[]} */ var getNoZeroIntegers = function(n) { };
No-Zero integer is a positive integer that does not contain any 0 in its decimal representation. Given an integer n, return a list of two integers [a, b] where: a and b are No-Zero integers. a + b = n The test cases are generated so that there is at least one valid solution. If there are many valid solutions, you can return any of them.   Example 1: Input: n = 2 Output: [1,1] Explanation: Let a = 1 and b = 1. Both a and b are no-zero integers, and a + b = 2 = n. Example 2: Input: n = 11 Output: [2,9] Explanation: Let a = 2 and b = 9. Both a and b are no-zero integers, and a + b = 9 = n. Note that there are other valid answers as [8, 3] that can be accepted.   Constraints: 2 <= n <= 104
Easy
[ "math" ]
null
[]
1,318
minimum-flips-to-make-a-or-b-equal-to-c
[ "Check the bits one by one whether they need to be flipped." ]
/** * @param {number} a * @param {number} b * @param {number} c * @return {number} */ var minFlips = function(a, b, c) { };
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation). Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.   Example 1: Input: a = 2, b = 6, c = 5 Output: 3 Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c) Example 2: Input: a = 4, b = 2, c = 7 Output: 1 Example 3: Input: a = 1, b = 2, c = 3 Output: 0   Constraints: 1 <= a <= 10^9 1 <= b <= 10^9 1 <= c <= 10^9
Medium
[ "bit-manipulation" ]
null
[]
1,319
number-of-operations-to-make-network-connected
[ "As long as there are at least (n - 1) connections, there is definitely a way to connect all computers.", "Use DFS to determine the number of isolated computer clusters." ]
/** * @param {number} n * @param {number[][]} connections * @return {number} */ var makeConnected = function(n, connections) { };
There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.   Example 1: Input: n = 4, connections = [[0,1],[0,2],[1,2]] Output: 1 Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3. Example 2: Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]] Output: 2 Example 3: Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]] Output: -1 Explanation: There are not enough cables.   Constraints: 1 <= n <= 105 1 <= connections.length <= min(n * (n - 1) / 2, 105) connections[i].length == 2 0 <= ai, bi < n ai != bi There are no repeated connections. No two computers are connected by more than one cable.
Medium
[ "depth-first-search", "breadth-first-search", "union-find", "graph" ]
null
[]
1,320
minimum-distance-to-type-a-word-using-two-fingers
[ "Use dynamic programming.", "dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word." ]
/** * @param {string} word * @return {number} */ var minimumDistance = function(word) { };
You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate. For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1). Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|. Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.   Example 1: Input: word = "CAKE" Output: 3 Explanation: Using two fingers, one optimal way to type "CAKE" is: Finger 1 on letter 'C' -> cost = 0 Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 Finger 2 on letter 'K' -> cost = 0 Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 Total distance = 3 Example 2: Input: word = "HAPPY" Output: 6 Explanation: Using two fingers, one optimal way to type "HAPPY" is: Finger 1 on letter 'H' -> cost = 0 Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2 Finger 2 on letter 'P' -> cost = 0 Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0 Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4 Total distance = 6   Constraints: 2 <= word.length <= 300 word consists of uppercase English letters.
Hard
[ "string", "dynamic-programming" ]
[ "const minimumDistance = function (word) {\n const dp = Array.from({ length: 2 }, () =>\n new Array(27).fill(0).map(() => Array(27).fill(0))\n )\n const A = 'A'.charCodeAt(0)\n for (let pos = word.length - 1; pos >= 0; --pos) {\n let to = word[pos].charCodeAt(0) - A\n for (let i = 0; i < 27; ++i) {\n for (let j = 0; j < 27; ++j) {\n dp[pos % 2][i][j] = Math.min(\n dp[(pos + 1) % 2][to][i] + cost(j, to),\n dp[(pos + 1) % 2][to][j] + cost(i, to)\n )\n }\n }\n }\n return dp[0][26][26]\n}\nfunction cost(from, to) {\n if (from === 26) return 0\n return (\n Math.abs(((from / 6) >> 0) - ((to / 6) >> 0)) +\n Math.abs((from % 6) - (to % 6))\n )\n}" ]
1,323
maximum-69-number
[ "Convert the number in an array of its digits.", "Brute force on every digit to get the maximum number." ]
/** * @param {number} num * @return {number} */ var maximum69Number = function(num) { };
You are given a positive integer num consisting only of digits 6 and 9. Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).   Example 1: Input: num = 9669 Output: 9969 Explanation: Changing the first digit results in 6669. Changing the second digit results in 9969. Changing the third digit results in 9699. Changing the fourth digit results in 9666. The maximum number is 9969. Example 2: Input: num = 9996 Output: 9999 Explanation: Changing the last digit 6 to 9 results in the maximum number. Example 3: Input: num = 9999 Output: 9999 Explanation: It is better not to apply any change.   Constraints: 1 <= num <= 104 num consists of only 6 and 9 digits.
Easy
[ "math", "greedy" ]
[ "var maximum69Number = function(num) {\n const arr = (num+'').split('')\n for(let i = 0; i < arr.length; i++) {\n if(arr[i] === '6') {\n arr[i] = '9'\n break\n }\n }\n return arr.join('')\n};" ]
1,324
print-words-vertically
[ "Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces." ]
/** * @param {string} s * @return {string[]} */ var printVertically = function(s) { };
Given a string s. Return all the words vertically in the same order in which they appear in s. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word.   Example 1: Input: s = "HOW ARE YOU" Output: ["HAY","ORO","WEU"] Explanation: Each word is printed vertically. "HAY"  "ORO"  "WEU" Example 2: Input: s = "TO BE OR NOT TO BE" Output: ["TBONTB","OEROOE"," T"] Explanation: Trailing spaces is not allowed. "TBONTB" "OEROOE" " T" Example 3: Input: s = "CONTEST IS COMING" Output: ["CIC","OSO","N M","T I","E N","S G","T"]   Constraints: 1 <= s.length <= 200 s contains only upper case English letters. It's guaranteed that there is only one space between 2 words.
Medium
[ "array", "string", "simulation" ]
[ "const printVertically = function(s) {\n const arr = s.split(' ').filter(e => e !== '')\n const m = arr.length\n let n = 0\n for(const e of arr) {\n n = Math.max(n, e.length)\n }\n \n const mat = Array.from({ length: m }, () => Array(n).fill(' '))\n for(let i = 0; i < arr.length; i++) {\n const cur = mat[i]\n for(let j = 0; j < arr[i].length; j++) {\n mat[i][j] = arr[i][j]\n }\n }\n const res = []\n for(let j = 0; j < n; j++) {\n const col = []\n for(let i = 0; i < m; i++) {\n col.push(mat[i][j])\n }\n res.push(col.join('').trimEnd())\n }\n \n return res\n};" ]
1,325
delete-leaves-with-a-given-value
[ "Use the DFS to reconstruct the tree such that no leaf node is equal to the target. If the leaf node is equal to the target, return an empty object instead." ]
/** * 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} target * @return {TreeNode} */ var removeLeafNodes = function(root, target) { };
Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).   Example 1: Input: root = [1,2,3,2,null,2,4], target = 2 Output: [1,null,3,null,4] Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). After removing, new nodes become leaf nodes with value (target = 2) (Picture in center). Example 2: Input: root = [1,3,3,3,2], target = 3 Output: [1,3,null,null,2] Example 3: Input: root = [1,2,null,2,null,2], target = 2 Output: [1] Explanation: Leaf nodes in green with value (target = 2) are removed at each step.   Constraints: The number of nodes in the tree is in the range [1, 3000]. 1 <= Node.val, target <= 1000
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 removeLeafNodes = function(root, target) {\n return dfs(root, target)\n};\n\nfunction dfs(node, target) {\n if(node == null) return node\n if(node.left == null && node.right == null) {\n if(node.val === target) return null\n else return node\n }\n node.right = dfs(node.right, target)\n node.left = dfs(node.left, target)\n if(node.right == null && node.left == null) return dfs(node, target)\n return node\n}", "const removeLeafNodes = function(root, target) {\n if(root.left) root.left = removeLeafNodes(root.left, target)\n if(root.right) root.right = removeLeafNodes(root.right, target)\n return root.left == root.right && root.val === target ? null : root\n};" ]
1,326
minimum-number-of-taps-to-open-to-water-a-garden
[ "Create intervals of the area covered by each tap, sort intervals by the left end.", "We need to cover the interval [0, n]. we can start with the first interval and out of all intervals that intersect with it we choose the one that covers the farthest point to the right.", "What if there is a gap between intervals that is not covered ? we should stop and return -1 as there is some interval that cannot be covered." ]
/** * @param {number} n * @param {number[]} ranges * @return {number} */ var minTaps = function(n, ranges) { };
There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e., the length of the garden is n). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.   Example 1: Input: n = 5, ranges = [3,4,1,1,0,0] Output: 1 Explanation: The tap at point 0 can cover the interval [-3,3] The tap at point 1 can cover the interval [-3,5] The tap at point 2 can cover the interval [1,3] The tap at point 3 can cover the interval [2,4] The tap at point 4 can cover the interval [4,4] The tap at point 5 can cover the interval [5,5] Opening Only the second tap will water the whole garden [0,5] Example 2: Input: n = 3, ranges = [0,0,0,0] Output: -1 Explanation: Even if you activate all the four taps you cannot water the whole garden.   Constraints: 1 <= n <= 104 ranges.length == n + 1 0 <= ranges[i] <= 100
Hard
[ "array", "dynamic-programming", "greedy" ]
[ "const minTaps = function (n, ranges) {\n const starts = new Array(n + 1).fill(0)\n for (let i = 0; i <= n; i++) {\n const start = Math.max(0, i - ranges[i])\n starts[start] = Math.max(starts[start], i + ranges[i])\n }\n let count = 0\n let max = 0\n let i = 0\n while (max < n) {\n const end = max\n for (let j = i; j <= end; j++) {\n max = Math.max(max, starts[j])\n }\n if (i === max) return -1\n i = end\n count++\n }\n return count\n}", "const minTaps = function (n, ranges) {\n const dp = new Array(n + 1).fill(n + 2)\n dp[0] = 0\n for (let i = 0; i <= n; ++i)\n for (let j = Math.max(i - ranges[i] + 1, 0); j <= Math.min(i + ranges[i], n); ++j)\n dp[j] = Math.min(dp[j], dp[Math.max(0, i - ranges[i])] + 1)\n return dp[n] < n + 2 ? dp[n] : -1\n}" ]
1,328
break-a-palindrome
[ "How to detect if there is impossible to perform the replacement? Only when the length = 1.", "Change the first non 'a' character to 'a'.", "What if the string has only 'a'?", "Change the last character to 'b'." ]
/** * @param {string} palindrome * @return {string} */ var breakPalindrome = function(palindrome) { };
Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible. Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string. A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, "abcc" is lexicographically smaller than "abcd" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'.   Example 1: Input: palindrome = "abccba" Output: "aaccba" Explanation: There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba". Of all the ways, "aaccba" is the lexicographically smallest. Example 2: Input: palindrome = "a" Output: "" Explanation: There is no way to replace a single character to make "a" not a palindrome, so return an empty string.   Constraints: 1 <= palindrome.length <= 1000 palindrome consists of only lowercase English letters.
Medium
[ "string", "greedy" ]
null
[]
1,329
sort-the-matrix-diagonally
[ "Use a data structure to store all values of each diagonal.", "How to index the data structure with the id of the diagonal?", "All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j." ]
/** * @param {number[][]} mat * @return {number[][]} */ var diagonalSort = function(mat) { };
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.   Example 1: Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] Example 2: Input: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]] Output: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 100 1 <= mat[i][j] <= 100
Medium
[ "array", "sorting", "matrix" ]
[ "const diagonalSort = function(mat) {\n const m = mat.length, n = mat[0].length\n \n for(let j = 0; j < n; j++) {\n let i = 0, jj = j\n const tmp = []\n while(jj < n && i < m) {\n tmp.push(mat[i++][jj++])\n }\n tmp.sort((a, b) => a - b)\n let idx = 0\n jj = j\n let ii = 0\n while(ii < m && jj < n) {\n mat[ii++][jj++] = tmp[idx++]\n }\n }\n \n for(let i = 1; i < m; i++) {\n let j = 0\n let ii = i\n const tmp = []\n while(j < n && ii < m) {\n tmp.push(mat[ii++][j++])\n }\n tmp.sort((a, b) => a - b)\n let idx = 0\n ii = i\n j = 0\n while(ii < m && j < n) {\n mat[ii++][j++] = tmp[idx++]\n }\n }\n return mat\n};" ]
1,330
reverse-subarray-to-maximize-array-value
[ "What's the score after reversing a sub-array [L, R] ?", "It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1])", "How to maximize that formula given that abs(x - y) = max(x - y, y - x) ?", "This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[R + 1] - a[L], a[L] - a[R + 1]) - value(L) - value(R + 1)) over all L < R where value(i) = abs(a[i] - a[i-1])", "This can be divided into 4 cases." ]
/** * @param {number[]} nums * @return {number} */ var maxValueAfterReverse = function(nums) { };
You are given an integer array nums. The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1. You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once. Find maximum possible value of the final array.   Example 1: Input: nums = [2,3,1,5,4] Output: 10 Explanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10. Example 2: Input: nums = [2,4,9,24,2,1,10] Output: 68   Constraints: 1 <= nums.length <= 3 * 104 -105 <= nums[i] <= 105
Hard
[ "array", "math", "greedy" ]
[ "const maxValueAfterReverse = function (nums) {\n let minOfMaxPair = -Infinity\n let maxOfMinPair = Infinity\n let originalTotal = 0\n let maximumBenefit = 0\n for (let i = 1; i < nums.length; i++) {\n const [left, right] = [nums[i - 1], nums[i]]\n const diff = Math.abs(right - left)\n originalTotal += diff\n maximumBenefit = Math.max(\n maximumBenefit,\n Math.abs(right - nums[0]) - diff,\n Math.abs(left - nums[nums.length - 1]) - diff\n )\n minOfMaxPair = Math.max(minOfMaxPair, Math.min(left, right))\n maxOfMinPair = Math.min(maxOfMinPair, Math.max(left, right))\n }\n maximumBenefit = Math.max(maximumBenefit, 2 * (minOfMaxPair - maxOfMinPair))\n return originalTotal + maximumBenefit\n}" ]
1,331
rank-transform-of-an-array
[ "Use a temporary array to copy the array and sort it.", "The rank of each element is the number of elements smaller than it in the sorted array plus one." ]
/** * @param {number[]} arr * @return {number[]} */ var arrayRankTransform = function(arr) { };
Given an array of integers arr, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: Rank is an integer starting from 1. The larger the element, the larger the rank. If two elements are equal, their rank must be the same. Rank should be as small as possible.   Example 1: Input: arr = [40,10,20,30] Output: [4,1,2,3] Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest. Example 2: Input: arr = [100,100,100] Output: [1,1,1] Explanation: Same elements share the same rank. Example 3: Input: arr = [37,12,28,9,100,56,80,5,12] Output: [5,3,4,2,8,6,7,1,3]   Constraints: 0 <= arr.length <= 105 -109 <= arr[i] <= 109
Easy
[ "array", "hash-table", "sorting" ]
[ "const arrayRankTransform = function(arr) {\n const hash = {}\n for(let e of arr) {\n hash[e] = 1\n }\n const keys = Object.keys(hash)\n keys.sort((a, b) => a - b)\n const rank = {}\n for(let i = 0, n= keys.length; i < n; i++) {\n rank[keys[i]] = i + 1\n }\n \n return arr.map(e => rank[e])\n};" ]
1,332
remove-palindromic-subsequences
[ "Use the fact that string contains only 2 characters.", "Are subsequences composed of only one type of letter always palindrome strings ?" ]
/** * @param {string} s * @return {number} */ var removePalindromeSub = function(s) { };
You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s. Return the minimum number of steps to make the given string empty. A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous. A string is called palindrome if is one that reads the same backward as well as forward.   Example 1: Input: s = "ababa" Output: 1 Explanation: s is already a palindrome, so its entirety can be removed in a single step. Example 2: Input: s = "abb" Output: 2 Explanation: "abb" -> "bb" -> "". Remove palindromic subsequence "a" then "bb". Example 3: Input: s = "baabb" Output: 2 Explanation: "baabb" -> "b" -> "". Remove palindromic subsequence "baab" then "b".   Constraints: 1 <= s.length <= 1000 s[i] is either 'a' or 'b'.
Easy
[ "two-pointers", "string" ]
[ "const removePalindromeSub = function(s) {\n if(s == null || s === '') return 0\n if(chk(s)) return 1\n return 2\n};\n\nfunction chk(s) {\n let l = 0, r = s.length - 1\n while(l < r) {\n if(s[l] !== s[r]) return false\n l++\n r--\n }\n \n return true\n}" ]
1,333
filter-restaurants-by-vegan-friendly-price-and-distance
[ "Do the filtering and sort as said. Note that the id may not be the index in the array." ]
/** * @param {number[][]} restaurants * @param {number} veganFriendly * @param {number} maxPrice * @param {number} maxDistance * @return {number[]} */ var filterRestaurants = function(restaurants, veganFriendly, maxPrice, maxDistance) { };
Given the array restaurants where  restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters. The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively. Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false.   Example 1: Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10 Output: [3,1,5] Explanation: The restaurants are: Restaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10] Restaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5] Restaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4] Restaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3] Restaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest). Example 2: Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10 Output: [4,3,2,1,5] Explanation: The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered. Example 3: Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3 Output: [4,5]   Constraints: 1 <= restaurants.length <= 10^4 restaurants[i].length == 5 1 <= idi, ratingi, pricei, distancei <= 10^5 1 <= maxPrice, maxDistance <= 10^5 veganFriendlyi and veganFriendly are 0 or 1. All idi are distinct.
Medium
[ "array", "sorting" ]
null
[]
1,334
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
[ "Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative).", "For each city calculate the number of reachable cities within the threshold, then search for the optimal city." ]
/** * @param {number} n * @param {number[][]} edges * @param {number} distanceThreshold * @return {number} */ var findTheCity = function(n, edges, distanceThreshold) { };
There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold. Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.   Example 1: Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4 Output: 3 Explanation: The figure above describes the graph.  The neighboring cities at a distanceThreshold = 4 for each city are: City 0 -> [City 1, City 2]  City 1 -> [City 0, City 2, City 3]  City 2 -> [City 0, City 1, City 3]  City 3 -> [City 1, City 2]  Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number. Example 2: Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2 Output: 0 Explanation: The figure above describes the graph.  The neighboring cities at a distanceThreshold = 2 for each city are: City 0 -> [City 1]  City 1 -> [City 0, City 4]  City 2 -> [City 3, City 4]  City 3 -> [City 2, City 4] City 4 -> [City 1, City 2, City 3]  The city 0 has 1 neighboring city at a distanceThreshold = 2.   Constraints: 2 <= n <= 100 1 <= edges.length <= n * (n - 1) / 2 edges[i].length == 3 0 <= fromi < toi < n 1 <= weighti, distanceThreshold <= 10^4 All pairs (fromi, toi) are distinct.
Medium
[ "dynamic-programming", "graph", "shortest-path" ]
null
[]
1,335
minimum-difficulty-of-a-job-schedule
[ "Use DP. Try to cut the array into d non-empty sub-arrays. Try all possible cuts for the array.", "Use dp[i][j] where DP states are i the index of the last cut and j the number of remaining cuts. Complexity is O(n * n * d)." ]
/** * @param {number[]} jobDifficulty * @param {number} d * @return {number} */ var minDifficulty = function(jobDifficulty, d) { };
You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i). You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day. You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i]. Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.   Example 1: Input: jobDifficulty = [6,5,4,3,2,1], d = 2 Output: 7 Explanation: First day you can finish the first 5 jobs, total difficulty = 6. Second day you can finish the last job, total difficulty = 1. The difficulty of the schedule = 6 + 1 = 7 Example 2: Input: jobDifficulty = [9,9,9], d = 4 Output: -1 Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs. Example 3: Input: jobDifficulty = [1,1,1], d = 3 Output: 3 Explanation: The schedule is one job per day. total difficulty will be 3.   Constraints: 1 <= jobDifficulty.length <= 300 0 <= jobDifficulty[i] <= 1000 1 <= d <= 10
Hard
[ "array", "dynamic-programming" ]
[ "const minDifficulty = function (jobDifficulty, d) {\n if (jobDifficulty.length < d) return -1\n const cache = {}\n const dfs = (start, numDays) => {\n if (numDays === d) {\n return start === jobDifficulty.length ? 0 : Infinity\n }\n const key = `${start}-${numDays}`\n if (cache[key] !== undefined) return cache[key]\n const end = jobDifficulty.length - d + numDays\n let result = Infinity\n let max = -Infinity\n for (let i = start; i <= end; i++) {\n max = Math.max(max, jobDifficulty[i])\n result = Math.min(result, max + dfs(i + 1, numDays + 1))\n }\n return (cache[key] = result)\n }\n return dfs(0, 0)\n}" ]
1,337
the-k-weakest-rows-in-a-matrix
[ "Sort the matrix row indexes by the number of soldiers and then row indexes." ]
/** * @param {number[][]} mat * @param {number} k * @return {number[]} */ var kWeakestRows = function(mat, k) { };
You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row. A row i is weaker than a row j if one of the following is true: The number of soldiers in row i is less than the number of soldiers in row j. Both rows have the same number of soldiers and i < j. Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.   Example 1: Input: mat = [[1,1,0,0,0], [1,1,1,1,0], [1,0,0,0,0], [1,1,0,0,0], [1,1,1,1,1]], k = 3 Output: [2,0,3] Explanation: The number of soldiers in each row is: - Row 0: 2 - Row 1: 4 - Row 2: 1 - Row 3: 2 - Row 4: 5 The rows ordered from weakest to strongest are [2,0,3,1,4]. Example 2: Input: mat = [[1,0,0,0], [1,1,1,1], [1,0,0,0], [1,0,0,0]], k = 2 Output: [0,2] Explanation: The number of soldiers in each row is: - Row 0: 1 - Row 1: 4 - Row 2: 1 - Row 3: 1 The rows ordered from weakest to strongest are [0,2,3,1].   Constraints: m == mat.length n == mat[i].length 2 <= n, m <= 100 1 <= k <= m matrix[i][j] is either 0 or 1.
Easy
[ "array", "binary-search", "sorting", "heap-priority-queue", "matrix" ]
[ "const kWeakestRows = function(mat, k) {\n const pq = new PriorityQueue((a, b) => a[0] === b[0] ? a[1] > b[1] : a[0] > b[0])\n const res = [], m = mat.length\n for(let i = 0; i < m; i++) {\n pq.push([oneNum(mat[i]), i])\n if(pq.size() > k) pq.pop()\n }\n while(k > 0) res[--k] = pq.pop()[1]\n return res\n};\n\nfunction oneNum(arr) {\n let l = 0, h = arr.length\n while(l < h) {\n const mid = l + ((h - l) >> 1)\n if(arr[mid] === 1) l = mid + 1\n else h = mid\n }\n return l\n}\n\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}" ]
1,338
reduce-array-size-to-the-half
[ "Count the frequency of each integer in the array.", "Start with an empty set, add to the set the integer with the maximum frequency.", "Keep Adding the integer with the max frequency until you remove at least half of the integers." ]
/** * @param {number[]} arr * @return {number} */ var minSetSize = function(arr) { };
You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array. Return the minimum size of the set so that at least half of the integers of the array are removed.   Example 1: Input: arr = [3,3,3,3,5,5,5,2,2,7] Output: 2 Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array). Possible sets of size 2 are {3,5},{3,2},{5,2}. Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array. Example 2: Input: arr = [7,7,7,7,7,7] Output: 1 Explanation: The only possible set you can choose is {7}. This will make the new array empty.   Constraints: 2 <= arr.length <= 105 arr.length is even. 1 <= arr[i] <= 105
Medium
[ "array", "hash-table", "greedy", "sorting", "heap-priority-queue" ]
[ "var minSetSize = function(arr) {\n const hash = {}\n for(const e of arr) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n const n = arr.length\n const entries = Object.entries(hash)\n entries.sort((a, b) => b[1] - a[1])\n let res= 0\n let cnt = 0\n for(const [k, v] of entries) {\n cnt += v\n res++\n if(cnt >= n / 2) break\n }\n \n return res\n};" ]
1,339
maximum-product-of-splitted-binary-tree
[ "If we know the sum of a subtree, the answer is max( (total_sum - subtree_sum) * subtree_sum) in each node." ]
/** * 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 maxProduct = function(root) { };
Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7. Note that you need to maximize the answer before taking the mod and not after taking it.   Example 1: Input: root = [1,2,3,4,5,6] Output: 110 Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10) Example 2: Input: root = [1,null,2,3,4,null,null,5,6] Output: 90 Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)   Constraints: The number of nodes in the tree is in the range [2, 5 * 104]. 1 <= Node.val <= 104
Medium
[ "tree", "depth-first-search", "binary-tree" ]
null
[]
1,340
jump-game-v
[ "Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]).", "dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i." ]
/** * @param {number[]} arr * @param {number} d * @return {number} */ var maxJumps = function(arr, d) { };
Given an array of integers arr and an integer d. In one step you can jump from index i to index: i + x where: i + x < arr.length and 0 < x <= d. i - x where: i - x >= 0 and 0 < x <= d. In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)). You can choose any index of the array and start jumping. Return the maximum number of indices you can visit. Notice that you can not jump outside of the array at any time.   Example 1: Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2 Output: 4 Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown. Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9. Similarly You cannot jump from index 3 to index 2 or index 1. Example 2: Input: arr = [3,3,3,3,3], d = 3 Output: 1 Explanation: You can start at any index. You always cannot jump to any index. Example 3: Input: arr = [7,6,5,4,3,2,1], d = 1 Output: 7 Explanation: Start at index 0. You can visit all the indicies.   Constraints: 1 <= arr.length <= 1000 1 <= arr[i] <= 105 1 <= d <= arr.length
Hard
[ "array", "dynamic-programming", "sorting" ]
[ "const maxJumps = function (arr, d, res = 1) {\n const dp = Array(1001).fill(0)\n for (let i = 0, len = arr.length; i < len; ++i)\n res = Math.max(res, dfs(arr, i, d))\n return res\n\n function dfs(arr, i, d, res = 1) {\n if (dp[i]) return dp[i]\n for (\n let j = i + 1;\n j <= Math.min(i + d, arr.length - 1) && arr[j] < arr[i];\n ++j\n )\n res = Math.max(res, 1 + dfs(arr, j, d))\n for (let j = i - 1; j >= Math.max(0, i - d) && arr[j] < arr[i]; --j)\n res = Math.max(res, 1 + dfs(arr, j, d))\n return (dp[i] = res)\n }\n}", "const maxJumps = function (arr, d) {\n const cache = new Array(arr.length)\n const diffs = [1, -1]\n const dfs = (i) => {\n if (cache[i]) return cache[i]\n let max = 0\n for (let diff of diffs) {\n for (let j = diff; Math.abs(j) <= d; j += diff) {\n const nextPosition = i + j\n const isValidJump =\n nextPosition >= 0 &&\n nextPosition < arr.length &&\n arr[i] > arr[nextPosition]\n if (isValidJump) max = Math.max(max, dfs(nextPosition))\n else break\n }\n }\n const result = max + 1\n cache[i] = result\n return result\n }\n for (let i = 0; i < arr.length; i++) dfs(i)\n return Math.max(...cache)\n}", "const maxJumps = function (arr, d, res = 0) {\n const n = arr.length\n const stack = [], stack2 = []\n const dp = Array(n + 1).fill(1)\n arr.push(Infinity)\n for(let i = 0; i <= n; i++) {\n while(stack.length && arr[stack[stack.length - 1]] < arr[i]) {\n const pre = arr[stack[stack.length - 1]]\n while(stack.length && pre === arr[stack[stack.length - 1]]) {\n const j = stack[stack.length - 1]\n stack.pop()\n if(i - j <= d) dp[i] = Math.max(dp[i], dp[j] + 1)\n stack2.push(j)\n }\n while(stack2.length) {\n const j = stack2[stack2.length - 1]\n stack2.pop()\n if(stack.length && j - stack[stack.length - 1] <= d) {\n dp[stack[stack.length - 1]] = Math.max(dp[stack[stack.length - 1]], dp[j] + 1)\n }\n }\n }\n stack.push(i)\n }\n for(let i = 0; i < n; i++) res = Math.max(res, dp[i]) \n return res\n}" ]
1,342
number-of-steps-to-reduce-a-number-to-zero
[ "Simulate the process to get the final answer." ]
/** * @param {number} num * @return {number} */ var numberOfSteps = function(num) { };
Given an integer num, return the number of steps to reduce it to zero. In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.   Example 1: Input: num = 14 Output: 6 Explanation:  Step 1) 14 is even; divide by 2 and obtain 7.  Step 2) 7 is odd; subtract 1 and obtain 6. Step 3) 6 is even; divide by 2 and obtain 3.  Step 4) 3 is odd; subtract 1 and obtain 2.  Step 5) 2 is even; divide by 2 and obtain 1.  Step 6) 1 is odd; subtract 1 and obtain 0. Example 2: Input: num = 8 Output: 4 Explanation:  Step 1) 8 is even; divide by 2 and obtain 4.  Step 2) 4 is even; divide by 2 and obtain 2.  Step 3) 2 is even; divide by 2 and obtain 1.  Step 4) 1 is odd; subtract 1 and obtain 0. Example 3: Input: num = 123 Output: 12   Constraints: 0 <= num <= 106
Easy
[ "math", "bit-manipulation" ]
[ "const numberOfSteps = function(num) {\n let res = 0\n while(num !== 0) {\n if(num % 2 === 0) {\n num /= 2\n } else num--\n res++\n }\n \n return res\n};" ]
1,343
number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold
[ "Start with a window of size K and test its average against the threshold.", "Keep moving the window by one element maintaining its size k until you cover the whole array. count number of windows that satisfy that its average is greater than the threshold." ]
/** * @param {number[]} arr * @param {number} k * @param {number} threshold * @return {number} */ var numOfSubarrays = function(arr, k, threshold) { };
Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold.   Example 1: Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4 Output: 3 Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold). Example 2: Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5 Output: 6 Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.   Constraints: 1 <= arr.length <= 105 1 <= arr[i] <= 104 1 <= k <= arr.length 0 <= threshold <= 104
Medium
[ "array", "sliding-window" ]
[ "const numOfSubarrays = function(arr, k, threshold) {\n const n = arr.length\n const pre = Array(n).fill(0)\n pre[0] = arr[0]\n for(let i = 1; i < n; i++) {\n pre[i] = pre[i - 1] + arr[i]\n }\n \n let res = 0\n if(pre[k - 1] / k >= threshold) res++\n for(let i = k; i < n; i++) {\n if(pre[i] - pre[i - k] >= k * threshold) res++\n }\n return res\n};" ]
1,344
angle-between-hands-of-a-clock
[ "The tricky part is determining how the minute hand affects the position of the hour hand.", "Calculate the angles separately then find the difference." ]
/** * @param {number} hour * @param {number} minutes * @return {number} */ var angleClock = function(hour, minutes) { };
Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand. Answers within 10-5 of the actual value will be accepted as correct.   Example 1: Input: hour = 12, minutes = 30 Output: 165 Example 2: Input: hour = 3, minutes = 30 Output: 75 Example 3: Input: hour = 3, minutes = 15 Output: 7.5   Constraints: 1 <= hour <= 12 0 <= minutes <= 59
Medium
[ "math" ]
[ "const angleClock = function(hour, minutes) {\n const minutesAngle = minutes * 6;\n const hoursAngle = (hour + minutes / 60) * 30;\n const diff = Math.abs(minutesAngle - hoursAngle);\n return Math.min(diff, 360 - diff);\n};" ]
1,345
jump-game-iv
[ "Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j].", "Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1." ]
/** * @param {number[]} arr * @return {number} */ var minJumps = function(arr) { };
Given an array of integers arr, you are initially positioned at the first index of the array. In one step you can jump from index i to index: i + 1 where: i + 1 < arr.length. i - 1 where: i - 1 >= 0. j where: arr[i] == arr[j] and i != j. Return the minimum number of steps to reach the last index of the array. Notice that you can not jump outside of the array at any time.   Example 1: Input: arr = [100,-23,-23,404,100,23,23,23,3,404] Output: 3 Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array. Example 2: Input: arr = [7] Output: 0 Explanation: Start index is the last index. You do not need to jump. Example 3: Input: arr = [7,6,9,6,9,6,9,7] Output: 1 Explanation: You can jump directly from index 0 to index 7 which is last index of the array.   Constraints: 1 <= arr.length <= 5 * 104 -108 <= arr[i] <= 108
Hard
[ "array", "hash-table", "breadth-first-search" ]
[ "var minJumps = function (arr) {\n if (arr.length === 1) return 0\n const n = arr.length\n const indexMap = new Map()\n for (let i = n - 1; i >= 0; i--) {\n if (!indexMap.has(arr[i])) {\n indexMap.set(arr[i], [])\n }\n indexMap.get(arr[i]).push(i)\n }\n let distance = 0\n const queue = [0, null]\n const visited = new Set([0])\n while (queue.length > 0) {\n const index = queue.shift()\n if (index !== null) {\n if (index > 0 && !visited.has(index - 1)) {\n visited.add(index - 1)\n queue.push(index - 1)\n }\n if (index < n - 1 && !visited.has(index + 1)) {\n if (index + 1 === n - 1) return distance + 1\n visited.add(index + 1)\n queue.push(index + 1)\n }\n for (const nb of indexMap.get(arr[index])) {\n if (!visited.has(nb) && nb !== index - 1 && nb !== index + 1) {\n if (nb === n - 1) return distance + 1\n visited.add(nb)\n queue.push(nb)\n }\n }\n } else {\n distance++\n if (queue.length > 0) {\n queue.push(null)\n }\n }\n }\n return -1\n}", "const minJumps = function (arr) {\n if (arr.length === 1) return 0\n const n = arr.length\n const indexMap = new Map()\n for (let i = n - 1; i >= 0; i--) {\n if (!indexMap.has(arr[i])) {\n indexMap.set(arr[i], [])\n }\n indexMap.get(arr[i]).push(i)\n }\n let distance = 0\n const queue = [0]\n const visited = new Set()\n visited.add(0)\n while (queue.length) {\n const len = queue.length\n for(let i = 0; i < len; i++) {\n const cur = queue.shift()\n if(cur === n - 1) return distance\n const tmp = indexMap.get(arr[cur])\n tmp.push(cur - 1)\n tmp.push(cur + 1)\n for(let e of tmp) {\n if(e >= 0 && e < n && !visited.has(e)) {\n visited.add(e)\n queue.push(e)\n }\n }\n indexMap.set(arr[cur], [])\n }\n distance++\n }\n return -1\n}" ]
1,346
check-if-n-and-its-double-exist
[ "Loop from i = 0 to arr.length, maintaining in a hashTable the array elements from [0, i - 1].", "On each step of the loop check if we have seen the element 2 * arr[i] so far or arr[i] / 2 was seen if arr[i] % 2 == 0." ]
/** * @param {number[]} arr * @return {boolean} */ var checkIfExist = function(arr) { };
Given an array arr of integers, check if there exist two indices i and j such that : i != j 0 <= i, j < arr.length arr[i] == 2 * arr[j]   Example 1: Input: arr = [10,2,5,3] Output: true Explanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j] Example 2: Input: arr = [3,1,7,11] Output: false Explanation: There is no i and j that satisfy the conditions.   Constraints: 2 <= arr.length <= 500 -103 <= arr[i] <= 103
Easy
[ "array", "hash-table", "two-pointers", "binary-search", "sorting" ]
null
[]
1,347
minimum-number-of-steps-to-make-two-strings-anagram
[ "Count the frequency of characters of each string.", "Loop over all characters if the frequency of a character in t is less than the frequency of the same character in s then add the difference between the frequencies to the answer." ]
/** * @param {string} s * @param {string} t * @return {number} */ var minSteps = function(s, t) { };
You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character. Return the minimum number of steps to make t an anagram of s. An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.   Example 1: Input: s = "bab", t = "aba" Output: 1 Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s. Example 2: Input: s = "leetcode", t = "practice" Output: 5 Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s. Example 3: Input: s = "anagram", t = "mangaar" Output: 0 Explanation: "anagram" and "mangaar" are anagrams.   Constraints: 1 <= s.length <= 5 * 104 s.length == t.length s and t consist of lowercase English letters only.
Medium
[ "hash-table", "string", "counting" ]
[ "const minSteps = function(s, t) {\n const as = Array(26).fill(0), ts = Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n for(const e of s){\n as[e.charCodeAt(0) - a]++\n }\n for(const e of t){\n ts[e.charCodeAt(0) - a]++\n }\n \n let com = 0\n for(let i = 0; i < 26; i++) {\n com += Math.min(as[i], ts[i])\n }\n return t.length - com\n};" ]
1,348
tweet-counts-per-frequency
[]
var TweetCounts = function() { }; /** * @param {string} tweetName * @param {number} time * @return {void} */ TweetCounts.prototype.recordTweet = function(tweetName, time) { }; /** * @param {string} freq * @param {string} tweetName * @param {number} startTime * @param {number} endTime * @return {number[]} */ TweetCounts.prototype.getTweetCountsPerFrequency = function(freq, tweetName, startTime, endTime) { }; /** * Your TweetCounts object will be instantiated and called as such: * var obj = new TweetCounts() * obj.recordTweet(tweetName,time) * var param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime) */
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day). For example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies: Every minute (60-second chunks): [10,69], [70,129], [130,189], ..., [9970,10000] Every hour (3600-second chunks): [10,3609], [3610,7209], [7210,10000] Every day (86400-second chunks): [10,10000] Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example). Design and implement an API to help the company with their analysis. Implement the TweetCounts class: TweetCounts() Initializes the TweetCounts object. void recordTweet(String tweetName, int time) Stores the tweetName at the recorded time (in seconds). List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime, endTime] (in seconds) and frequency freq. freq is one of "minute", "hour", or "day" representing a frequency of every minute, hour, or day respectively.   Example: Input ["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"] [[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]] Output [null,null,null,null,[2],[2,1],null,[4]] Explanation TweetCounts tweetCounts = new TweetCounts(); tweetCounts.recordTweet("tweet3", 0); // New tweet "tweet3" at time 0 tweetCounts.recordTweet("tweet3", 60); // New tweet "tweet3" at time 60 tweetCounts.recordTweet("tweet3", 10); // New tweet "tweet3" at time 10 tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]; chunk [0,59] had 2 tweets tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet tweetCounts.recordTweet("tweet3", 120); // New tweet "tweet3" at time 120 tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]; chunk [0,210] had 4 tweets   Constraints: 0 <= time, startTime, endTime <= 109 0 <= endTime - startTime <= 104 There will be at most 104 calls in total to recordTweet and getTweetCountsPerFrequency.
Medium
[ "hash-table", "binary-search", "design", "sorting", "ordered-set" ]
[ "const createNode = val => ({ val, left: null, right: null });\nclass BinarySearchTree {\n constructor() {\n this.root = null;\n }\n insert(val, cur = this.root) {\n const node = createNode(val);\n if (!this.root) { this.root = node; return; }\n if (val >= cur.val) {\n !cur.right ? (cur.right = node) : this.insert(val, cur.right);\n } else {\n !cur.left ? (cur.left = node) : this.insert(val, cur.left);\n }\n }\n traversal(low, high, interval, intervals, cur = this.root) {\n if (!cur) return;\n if (cur.val <= high && cur.val >= low) {\n ++intervals[Math.floor((cur.val - low + 1) / interval)];\n }\n cur.val > low && this.traversal(low, high, interval, intervals, cur.left);\n cur.val < high && this.traversal(low, high, interval, intervals, cur.right);\n }\n};\nclass TweetCounts {\n constructor() {\n this.freqInterval = {\n minute: 60,\n hour: 3600,\n day: 86400,\n };\n this.data = new Map();\n }\n\n recordTweet(name, time) {\n if (this.data.has(name) === false) {\n this.data.set(name, new BinarySearchTree());\n }\n this.data.get(name).insert(time);\n }\n\n getTweetCountsPerFrequency(freq, name, start, end) {\n const interval = this.freqInterval[freq];\n const ret = new Array(Math.ceil((end - start + 1) / interval)).fill(0);\n this.data.has(name) && this.data.get(name).traversal(start, end, interval, ret);\n return ret;\n }\n};" ]
1,349
maximum-students-taking-exam
[ "Students in row i only can see exams in row i+1.", "Use Dynamic programming to compute the result given a (current row, bitmask people seated in previous row)." ]
/** * @param {character[][]} seats * @return {number} */ var maxStudents = function(seats) { };
Given a m * n matrix seats  that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible.. Students must be placed in seats in good condition.   Example 1: Input: seats = [["#",".","#","#",".","#"],   [".","#","#","#","#","."],   ["#",".","#","#",".","#"]] Output: 4 Explanation: Teacher can place 4 students in available seats so they don't cheat on the exam. Example 2: Input: seats = [[".","#"],   ["#","#"],   ["#","."],   ["#","#"],   [".","#"]] Output: 3 Explanation: Place all students in available seats. Example 3: Input: seats = [["#",".",".",".","#"],   [".","#",".","#","."],   [".",".","#",".","."],   [".","#",".","#","."],   ["#",".",".",".","#"]] Output: 10 Explanation: Place students in available seats in column 1, 3 and 5.   Constraints: seats contains only characters '.' and'#'. m == seats.length n == seats[i].length 1 <= m <= 8 1 <= n <= 8
Hard
[ "array", "dynamic-programming", "bit-manipulation", "matrix", "bitmask" ]
[ "const maxStudents = function(seats) {\n const m = seats.length, n = seats[0].length, limit = 1 << n\n const dp = Array.from({ length: m + 1}, () => Array(limit).fill(0))\n \n let res = 0\n for(let i = 1; i <= m; i++) {\n for(let mask = 0; mask < limit; mask++) {\n let valid = true\n for(let j = 0; j < n; j++) {\n if(seats[i - 1][j] === '#' && ((mask >> j) & 1) ) {\n valid = false\n break\n }\n if(j < n - 1 && ((mask >> j) & 1) && ((mask >> (j + 1)) & 1) ) {\n valid = false\n break\n }\n }\n \n if(!valid) {\n dp[i][mask] = -1\n continue\n }\n \n for(let pre = 0; pre < limit; pre++) {\n if(dp[i - 1][pre] === -1) continue\n if( (pre & (mask >> 1)) !== 0 || (pre & (mask << 1)) !== 0 ) continue\n dp[i][mask] = Math.max(dp[i][mask], dp[i - 1][pre])\n }\n \n dp[i][mask] += bitCnt(mask)\n \n res = Math.max(res, dp[i][mask])\n }\n }\n \n return res\n \n function bitCnt(num) {\n let res = 0\n while(num) {\n if(num & 1) res++\n num = num >> 1\n }\n \n return res\n }\n};", "const maxStudents = function (seats) {\n if (!seats.length) return 0\n const lastPos = 1 << seats[0].length\n const classroom = seats.map((row) =>\n row.reduce((a, c, i) => (c === '#' ? a : a | (1 << i)), 0)\n )\n const dp = new Array(seats.length + 1).fill(null).map(() => new Map())\n dp[0].set(0, 0)\n for (let row = 0; row < seats.length; row++) {\n let queue = [0]\n let numStudents = 0\n while (queue.length > 0) {\n const next = []\n for (let arrangement of queue) {\n let max = 0\n for (let [prevArrang, count] of dp[row]) {\n if (conflicts(prevArrang, arrangement)) continue\n max = Math.max(max, count + numStudents)\n }\n dp[row + 1].set(arrangement, max)\n for (let i = 1; i < lastPos; i <<= 1) {\n if (canSit(classroom[row], arrangement, i)) next.push(arrangement | i)\n }\n }\n queue = next\n numStudents++\n }\n }\n return Math.max(...dp[seats.length].values())\n}\nfunction conflicts(prev, curr) {\n return prev & (curr << 1) || prev & (curr >> 1)\n}\nfunction canSit(row, arrangement, newStudent) {\n return (\n row & newStudent &&\n !(arrangement & newStudent) &&\n !(arrangement & (newStudent << 1)) &&\n !(arrangement & (newStudent >> 1))\n )\n}", "const maxStudents = function (seats) {\n const m = seats.length\n const n = seats[0].length\n const validity = []\n for (let i = 0; i < m; i++) {\n let cur = 0\n for (let j = 0; j < n; j++) {\n cur = (cur << 1) + (seats[i][j] === '.' ? 1 : 0)\n }\n validity.push(cur)\n }\n const f = Array.from({ length: m + 1 }, () => Array(1 << n).fill(-1))\n f[0][0] = 0\n for (let i = 1; i <= m; i++) {\n const valid = validity[i - 1]\n for (let j = 0; j < 1 << n; j++) {\n if ((j & valid) === j && !(j & (j >> 1))) {\n for (let k = 0; k < 1 << n; k++) {\n if (!(j & (k >> 1)) && !((j >> 1) & k) && f[i - 1][k] !== -1) {\n f[i][j] = Math.max(f[i][j], f[i - 1][k] + bitCount(j))\n }\n }\n }\n }\n }\n return Math.max(...f[m])\n}\nfunction bitCount(n) {\n const res = n.toString(2).match(/1/g)\n return res === null ? 0 : res.length\n}" ]
1,351
count-negative-numbers-in-a-sorted-matrix
[ "Use binary search for optimization or simply brute force." ]
/** * @param {number[][]} grid * @return {number} */ var countNegatives = function(grid) { };
Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.   Example 1: Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] Output: 8 Explanation: There are 8 negatives number in the matrix. Example 2: Input: grid = [[3,2],[1,0]] Output: 0   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 -100 <= grid[i][j] <= 100   Follow up: Could you find an O(n + m) solution?
Easy
[ "array", "binary-search", "matrix" ]
[ "const countNegatives = function(grid) {\n const m = grid.length, n = grid[0].length\n let res = 0, r = m - 1, c = 0\n while(r >= 0 && c < n) {\n if(grid[r][c] < 0) {\n res += n - c\n r--\n } else c++\n }\n\n return res\n};" ]
1,352
product-of-the-last-k-numbers
[ "Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity.", "When a zero number is added, clean the array of prefix products." ]
var ProductOfNumbers = function() { }; /** * @param {number} num * @return {void} */ ProductOfNumbers.prototype.add = function(num) { }; /** * @param {number} k * @return {number} */ ProductOfNumbers.prototype.getProduct = function(k) { }; /** * Your ProductOfNumbers object will be instantiated and called as such: * var obj = new ProductOfNumbers() * obj.add(num) * var param_2 = obj.getProduct(k) */
Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream. Implement the ProductOfNumbers class: ProductOfNumbers() Initializes the object with an empty stream. void add(int num) Appends the integer num to the stream. int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers. The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.   Example: Input ["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"] [[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]] Output [null,null,null,null,null,null,20,40,0,null,32] Explanation ProductOfNumbers productOfNumbers = new ProductOfNumbers(); productOfNumbers.add(3); // [3] productOfNumbers.add(0); // [3,0] productOfNumbers.add(2); // [3,0,2] productOfNumbers.add(5); // [3,0,2,5] productOfNumbers.add(4); // [3,0,2,5,4] productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20 productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40 productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0 productOfNumbers.add(8); // [3,0,2,5,4,8] productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32   Constraints: 0 <= num <= 100 1 <= k <= 4 * 104 At most 4 * 104 calls will be made to add and getProduct. The product of the stream at any point in time will fit in a 32-bit integer.
Medium
[ "array", "math", "design", "queue", "data-stream" ]
[ "// @lc code=start\n\nconst ProductOfNumbers = function() {\n this.sum = [1]\n};\n\n\nProductOfNumbers.prototype.add = function(num) {\n if(num > 0) {\n this.sum.push(this.sum[this.sum.length - 1] * num)\n } else {\n this.sum = [1]\n }\n};\n\n\nProductOfNumbers.prototype.getProduct = function(k) {\n const len = this.sum.length\n return k < len ? this.sum[len - 1] / this.sum[len - 1 - k] : 0\n};" ]
1,353
maximum-number-of-events-that-can-be-attended
[ "Sort the events by the start time and in case of tie by the end time in ascending order.", "Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in." ]
/** * @param {number[][]} events * @return {number} */ var maxEvents = function(events) { };
You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi. You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d. Return the maximum number of events you can attend.   Example 1: Input: events = [[1,2],[2,3],[3,4]] Output: 3 Explanation: You can attend all the three events. One way to attend them all is as shown. Attend the first event on day 1. Attend the second event on day 2. Attend the third event on day 3. Example 2: Input: events= [[1,2],[2,3],[3,4],[1,2]] Output: 4   Constraints: 1 <= events.length <= 105 events[i].length == 2 1 <= startDayi <= endDayi <= 105
Medium
[ "array", "greedy", "sorting", "heap-priority-queue" ]
[ "class PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\nfunction maxEvents(events) {\n const pq = new PriorityQueue((a, b) => a < b)\n \n events.sort((a, b) => a[0] - b[0])\n let i = 0, res = 0, d = 0, n = events.length\n\n while(!pq.isEmpty() || i < n) {\n if(pq.isEmpty()) {\n d = events[i][0]\n }\n while(i < n && events[i][0] <= d) {\n pq.push(events[i++][1])\n }\n pq.pop()\n res++\n d++\n while(!pq.isEmpty() && pq.peek() < d) {\n pq.pop()\n }\n }\n\n return res\n}", "class PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\nfunction maxEvents(events) {\n const pq = new PriorityQueue((a, b) => a < b)\n events.sort((a, b) => a[0] - b[0])\n let res = 0, i = 0, n = events.length\n for(let d = 1; d <= 100000; d++) {\n while(i < n && events[i][0] === d) {\n pq.push(events[i++][1])\n }\n while(!pq.isEmpty() && pq.peek() < d) {\n pq.pop()\n }\n if(!pq.isEmpty()) {\n res++\n pq.pop()\n }\n }\n return res\n}", "function maxEvents(events) {\n events.sort(([, aEnd], [, bEnd]) => aEnd - bEnd);\n const lastDay = events[events.length - 1][1];\n const segmentTree = new SegmentTree(Array.from({ length: lastDay }, (_, i) => i), Infinity, (a, b) => Math.min(a, b));\n let daysAttended = 0;\n\n for (const [start, end] of events) {\n // earliest attendable day\n const ead = segmentTree.queryIn(start - 1, end);\n if (ead <= end) {\n daysAttended += 1;\n segmentTree.setAt(ead, Infinity);\n }\n }\n\n return daysAttended;\n}\n\n// https://github.com/axross/complex-data-structures\n// new SegmentTree(values, identity, associate)\n// segmentTree.getAt(i)\n// segmentTree.queryIn(from, to)\n// segmentTree.setAt(i, value)\n// segmentTree.length\nclass SegmentTree{constructor(t,e,s){if(this.valueLength=t.length,this.identity=e,this.associate=s,0===t.length)this.tree=[];else{const h=2**Math.ceil(Math.log2(t.length))*2-1,i=[];for(let s=0;s<=h>>1;++s)i[(h>>1)+s]=s<t.length?t[s]:e;for(let t=(h>>1)-1;t>=0;--t)i[t]=s(i[2*t+1],i[2*t+2]);this.tree=i}}get length(){return this.valueLength}getAt(t){return this.tree[t+(this.tree.length>>1)]}queryIn(t,e){let s=this.identity;const h=[[0,0,1+(this.tree.length>>1)]];for(;h.length>0;){const[i,r,n]=h.pop();r>=t&&n<=e?s=this.associate(s,this.tree[i]):r>=e||n<t||i>this.tree.length>>1||h.push([2*i+1,r,r+n>>1],[2*i+2,r+n>>1,n])}return s}setAt(t,e){const s=t+(this.tree.length>>1);this.tree[s]=e;let h=s-1>>1;for(;h>=0;)this.tree[h]=this.associate(this.tree[2*h+1],this.tree[2*h+2]),h=h-1>>1}}", "function maxEvents(events) {\n const pq = new MinPriorityQueue ()\n events.sort((a, b) => a[0] - b[0])\n let res = 0, i = 0, n = events.length\n for(let d = 1; d <= 1e5; d++) {\n while(i < n && events[i][0] === d) {\n pq.enqueue(events[i++][1])\n }\n while(!pq.isEmpty() && pq.front().element < d) {\n pq.dequeue()\n }\n if(!pq.isEmpty()) {\n res++\n pq.dequeue()\n }\n }\n return res\n}" ]
1,354
construct-target-array-with-multiple-sums
[ "Given that the sum is strictly increasing, the largest element in the target must be formed in the last step by adding the total sum in the previous step. Thus, we can simulate the process in a reversed way.", "Subtract the largest with the rest of the array, and put the new element into the array. Repeat until all elements become one" ]
/** * @param {number[]} target * @return {boolean} */ var isPossible = function(target) { };
You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure : let x be the sum of all elements currently in your array. choose index i, such that 0 <= i < n and set the value of arr at index i to x. You may repeat this procedure as many times as needed. Return true if it is possible to construct the target array from arr, otherwise, return false.   Example 1: Input: target = [9,3,5] Output: true Explanation: Start with arr = [1, 1, 1] [1, 1, 1], sum = 3 choose index 1 [1, 3, 1], sum = 5 choose index 2 [1, 3, 5], sum = 9 choose index 0 [9, 3, 5] Done Example 2: Input: target = [1,1,1,2] Output: false Explanation: Impossible to create target array from [1,1,1,1]. Example 3: Input: target = [8,5] Output: true   Constraints: n == target.length 1 <= n <= 5 * 104 1 <= target[i] <= 109
Hard
[ "array", "heap-priority-queue" ]
[ "const isPossible = function (target) {\n const pq = new PriorityQueue();\n let total = 0;\n for (let a of target) {\n total += a;\n pq.push(a);\n }\n while (true) {\n let a = pq.pop();\n total -= a;\n if (a === 1 || total === 1) return true;\n if (a < total || total === 0 || a % total === 0) return false;\n a %= total;\n total += a;\n pq.push(a);\n }\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = [];\n this.top = 0;\n this.comparator = comparator;\n }\n size() {\n return this.heap.length;\n }\n isEmpty() {\n return this.size() === 0;\n }\n peek() {\n return this.heap[this.top];\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value);\n this.siftUp();\n });\n return this.size();\n }\n pop() {\n const poppedValue = this.peek();\n const bottom = this.size() - 1;\n if (bottom > this.top) {\n this.swap(this.top, bottom);\n }\n this.heap.pop();\n this.siftDown();\n return poppedValue;\n }\n replace(value) {\n const replacedValue = this.peek();\n this.heap[this.top] = value;\n this.siftDown();\n return replacedValue;\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1;\n left = (i) => (i << 1) + 1;\n right = (i) => (i + 1) << 1;\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j]);\n swap = (i, j) =>\n ([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}" ]
1,356
sort-integers-by-the-number-of-1-bits
[ "Simulate the problem. Count the number of 1's in the binary representation of each integer.", "Sort by the number of 1's ascending and by the value in case of tie." ]
/** * @param {number[]} arr * @return {number[]} */ var sortByBits = function(arr) { };
You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order. Return the array after sorting it.   Example 1: Input: arr = [0,1,2,3,4,5,6,7,8] Output: [0,1,2,4,8,3,5,6,7] Explantion: [0] is the only integer with 0 bits. [1,2,4,8] all have 1 bit. [3,5,6] have 2 bits. [7] has 3 bits. The sorted array by bits is [0,1,2,4,8,3,5,6,7] Example 2: Input: arr = [1024,512,256,128,64,32,16,8,4,2,1] Output: [1,2,4,8,16,32,64,128,256,512,1024] Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.   Constraints: 1 <= arr.length <= 500 0 <= arr[i] <= 104
Easy
[ "array", "bit-manipulation", "sorting", "counting" ]
[ "const sortByBits = function(arr) {\n arr.sort((a, b) => {\n const an = numOfBits(a), bn = numOfBits(b)\n return an === bn ? a - b : an - bn\n })\n return arr\n};\n\nfunction numOfBits(n) {\n let res = 0\n for(let i = 0; i < 32; i++) {\n if((1 << i) & n) res++\n }\n return res\n}" ]
1,357
apply-discount-every-n-orders
[ "Keep track of the count of the customers.", "Check if the count of the customers is divisible by n then apply the discount formula." ]
/** * @param {number} n * @param {number} discount * @param {number[]} products * @param {number[]} prices */ var Cashier = function(n, discount, products, prices) { }; /** * @param {number[]} product * @param {number[]} amount * @return {number} */ Cashier.prototype.getBill = function(product, amount) { }; /** * Your Cashier object will be instantiated and called as such: * var obj = new Cashier(n, discount, products, prices) * var param_1 = obj.getBill(product,amount) */
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices, where the ith product has an ID of products[i] and a price of prices[i]. When a customer is paying, their bill is represented as two parallel integer arrays product and amount, where the jth product they purchased has an ID of product[j], and amount[j] is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the jth product). The supermarket decided to have a sale. Every nth customer paying for their groceries will be given a percentage discount. The discount amount is given by discount, where they will be given discount percent off their subtotal. More formally, if their subtotal is bill, then they would actually pay bill * ((100 - discount) / 100). Implement the Cashier class: Cashier(int n, int discount, int[] products, int[] prices) Initializes the object with n, the discount, and the products and their prices. double getBill(int[] product, int[] amount) Returns the final total of the bill with the discount applied (if any). Answers within 10-5 of the actual value will be accepted.   Example 1: Input ["Cashier","getBill","getBill","getBill","getBill","getBill","getBill","getBill"] [[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]] Output [null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0] Explanation Cashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]); cashier.getBill([1,2],[1,2]); // return 500.0. 1st customer, no discount. // bill = 1 * 100 + 2 * 200 = 500. cashier.getBill([3,7],[10,10]); // return 4000.0. 2nd customer, no discount. // bill = 10 * 300 + 10 * 100 = 4000. cashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]); // return 800.0. 3rd customer, 50% discount. // Original bill = 1600 // Actual bill = 1600 * ((100 - 50) / 100) = 800. cashier.getBill([4],[10]); // return 4000.0. 4th customer, no discount. cashier.getBill([7,3],[10,10]); // return 4000.0. 5th customer, no discount. cashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0. 6th customer, 50% discount. // Original bill = 14700, but with // Actual bill = 14700 * ((100 - 50) / 100) = 7350. cashier.getBill([2,3,5],[5,3,2]); // return 2500.0. 7th customer, no discount.   Constraints: 1 <= n <= 104 0 <= discount <= 100 1 <= products.length <= 200 prices.length == products.length 1 <= products[i] <= 200 1 <= prices[i] <= 1000 The elements in products are unique. 1 <= product.length <= products.length amount.length == product.length product[j] exists in products. 1 <= amount[j] <= 1000 The elements of product are unique. At most 1000 calls will be made to getBill. Answers within 10-5 of the actual value will be accepted.
Medium
[ "array", "hash-table", "design" ]
null
[]
1,358
number-of-substrings-containing-all-three-characters
[ "For each position we simply need to find the first occurrence of a/b/c on or after this position.", "So we can pre-compute three link-list of indices of each a, b, and c." ]
/** * @param {string} s * @return {number} */ var numberOfSubstrings = function(s) { };
Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c.   Example 1: Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). Example 2: Input: s = "aaacb" Output: 3 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". Example 3: Input: s = "abc" Output: 1   Constraints: 3 <= s.length <= 5 x 10^4 s only consists of a, b or c characters.
Medium
[ "hash-table", "string", "sliding-window" ]
null
[]
1,359
count-all-valid-pickup-and-delivery-options
[ "Use the permutation and combination theory to add one (P, D) pair each time until n pairs." ]
/** * @param {number} n * @return {number} */ var countOrders = function(n) { };
Given n orders, each order consist in pickup and delivery services.  Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).  Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: n = 1 Output: 1 Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1. Example 2: Input: n = 2 Output: 6 Explanation: All possible orders: (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. Example 3: Input: n = 3 Output: 90   Constraints: 1 <= n <= 500
Hard
[ "math", "dynamic-programming", "combinatorics" ]
[ "const countOrders = function(n) {\n let res = 1\n const MOD = 10 ** 9 + 7\n for(let i = 1; i <= n; i++) {\n res = res * (i * 2 - 1) * i % MOD;\n }\n return res\n};", "const countOrders = function(n) {\n let res = 1\n const MOD = 10 ** 9 + 7\n for(let i = 1; i <= n; i++) res = res * i % MOD\n for(let i = 1; i < 2 * n; i += 2) res = res * i % MOD\n return res\n};" ]
1,360
number-of-days-between-two-dates
[ "Create a function f(date) that counts the number of days from 1900-01-01 to date. How can we calculate the answer ?", "The answer is just |f(date1) - f(date2)|.", "How to construct f(date) ?", "For each year from 1900 to year - 1 sum up 365 or 366 in case of leap years. Then sum up for each month the number of days, consider the case when the current year is leap, finally sum up the days." ]
/** * @param {string} date1 * @param {string} date2 * @return {number} */ var daysBetweenDates = function(date1, date2) { };
Write a program to count the number of days between two dates. The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.   Example 1: Input: date1 = "2019-06-29", date2 = "2019-06-30" Output: 1 Example 2: Input: date1 = "2020-01-15", date2 = "2019-12-31" Output: 15   Constraints: The given dates are valid dates between the years 1971 and 2100.
Easy
[ "math", "string" ]
[ "const daysBetweenDates = function(date1, date2) {\n const d1 = new Date(date1)\n const d2 = new Date(date2)\n return Math.abs((d1.getTime() - d2.getTime()) / (1000 * 60 * 60 * 24))\n};" ]
1,361
validate-binary-tree-nodes
[ "Find the parent of each node.", "A valid tree must have nodes with only one parent and exactly one node with no parent." ]
/** * @param {number} n * @param {number[]} leftChild * @param {number[]} rightChild * @return {boolean} */ var validateBinaryTreeNodes = function(n, leftChild, rightChild) { };
You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree. If node i has no left child then leftChild[i] will equal -1, similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem.   Example 1: Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1] Output: true Example 2: Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1] Output: false Example 3: Input: n = 2, leftChild = [1,0], rightChild = [-1,-1] Output: false   Constraints: n == leftChild.length == rightChild.length 1 <= n <= 104 -1 <= leftChild[i], rightChild[i] <= n - 1
Medium
[ "tree", "depth-first-search", "breadth-first-search", "union-find", "graph", "binary-tree" ]
null
[]
1,362
closest-divisors
[ "Find the divisors of n+1 and n+2.", "To find the divisors of a number, you only need to iterate to the square root of that number." ]
/** * @param {number} num * @return {number[]} */ var closestDivisors = function(num) { };
Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2. Return the two integers in any order.   Example 1: Input: num = 8 Output: [3,3] Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen. Example 2: Input: num = 123 Output: [5,25] Example 3: Input: num = 999 Output: [40,25]   Constraints: 1 <= num <= 10^9
Medium
[ "math" ]
null
[]
1,363
largest-multiple-of-three
[ "A number is a multiple of three if and only if its sum of digits is a multiple of three.", "Use dynamic programming.", "To find the maximum number, try to maximize the number of digits of the number.", "Sort the digits in descending order to find the maximum number." ]
/** * @param {number[]} digits * @return {string} */ var largestMultipleOfThree = function(digits) { };
Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.   Example 1: Input: digits = [8,1,9] Output: "981" Example 2: Input: digits = [8,6,7,1,0] Output: "8760" Example 3: Input: digits = [1] Output: ""   Constraints: 1 <= digits.length <= 104 0 <= digits[i] <= 9
Hard
[ "array", "dynamic-programming", "greedy" ]
[ "const largestMultipleOfThree = function (digits) {\n const sum = digits.reduce((a, c) => a + c)\n if (sum === 0) return '0'\n const remainder = sum % 3\n digits.sort((a, b) => b - a)\n if (remainder === 0) return digits.join('')\n const doubleRemainder = remainder === 1 ? 2 : 1\n const idxs = []\n for (let i = digits.length - 1; i >= 0; i--) {\n const numRemainder = digits[i] % 3\n if (numRemainder === remainder) {\n digits[i] = ''\n return digits.join('')\n } else if (numRemainder === doubleRemainder) {\n idxs.push(i)\n }\n }\n const [idx1, idx2] = idxs\n if (idx2 === undefined) return ''\n\n digits[idx1] = ''\n digits[idx2] = ''\n return digits.join('')\n}" ]
1,365
how-many-numbers-are-smaller-than-the-current-number
[ "Brute force for each array element.", "In order to improve the time complexity, we can sort the array and get the answer for each array element." ]
/** * @param {number[]} nums * @return {number[]} */ var smallerNumbersThanCurrent = function(nums) { };
Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. Return the answer in an array.   Example 1: Input: nums = [8,1,2,2,3] Output: [4,0,1,1,3] Explanation: For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). For nums[1]=1 does not exist any smaller number than it. For nums[2]=2 there exist one smaller number than it (1). For nums[3]=2 there exist one smaller number than it (1). For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2). Example 2: Input: nums = [6,5,4,8] Output: [2,1,0,3] Example 3: Input: nums = [7,7,7,7] Output: [0,0,0,0]   Constraints: 2 <= nums.length <= 500 0 <= nums[i] <= 100
Easy
[ "array", "hash-table", "sorting", "counting" ]
[ "const smallerNumbersThanCurrent = function(nums) {\n const count = new Array(101).fill(0);\n const res = new Array(nums.length).fill(0);\n for (let i = 0; i < nums.length; i++) count[nums[i]]++\n for (let i = 1 ; i <= 100; i++) count[i] += count[i-1]\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] == 0) res[i] = 0\n else res[i] = count[nums[i] - 1]\n }\n return res;\n};" ]
1,366
rank-teams-by-votes
[ "Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank.", "Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order." ]
/** * @param {string[]} votes * @return {string} */ var rankTeams = function(votes) { };
In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. You are given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. Return a string of all teams sorted by the ranking system.   Example 1: Input: votes = ["ABC","ACB","ABC","ACB","ACB"] Output: "ACB" Explanation: Team A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team. Team B was ranked second by 2 voters and ranked third by 3 voters. Team C was ranked second by 3 voters and ranked third by 2 voters. As most of the voters ranked C second, team C is the second team, and team B is the third. Example 2: Input: votes = ["WXYZ","XYZW"] Output: "XWYZ" Explanation: X is the winner due to the tie-breaking rule. X has the same votes as W for the first position, but X has one vote in the second position, while W does not have any votes in the second position. Example 3: Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"] Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK" Explanation: Only one voter, so their votes are used for the ranking.   Constraints: 1 <= votes.length <= 1000 1 <= votes[i].length <= 26 votes[i].length == votes[j].length for 0 <= i, j < votes.length. votes[i][j] is an English uppercase letter. All characters of votes[i] are unique. All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length.
Medium
[ "array", "hash-table", "string", "sorting", "counting" ]
[ "const rankTeams = function(votes) {\n const hash = {}\n const l = votes[0].length\n for(let vote of votes) {\n for(let i = 0; i < l; i++) {\n const ch = vote[i]\n if(hash[ch] == null) hash[ch] = Array(l).fill(0)\n hash[ch][i]++\n }\n }\n const keys = Object.keys(hash)\n keys.sort((a, b) => {\n for(let i = 0; i < l; i++) {\n if(hash[a][i] !== hash[b][i]) {\n return hash[b][i] - hash[a][i]\n }\n }\n return a === b ? 0 : (a < b ? -1 : 1)\n })\n\n return keys.join('')\n};", "const rankTeams = function(votes) {\n if (votes.length === 1) return votes[0];\n const score = new Map(votes[0].split('').map(c => [c, new Array(votes[0].length).fill(0)]));\n for (s of votes) {\n for (let i = 0; i < s.length; i++) {\n score.get(s[i])[i]++;\n }\n }\n return votes[0].split('').sort((a,b) => {\n for (let i = 0; i < votes[0].length; i++) {\n if (score.get(a)[i] > score.get(b)[i]) return -1;\n if (score.get(a)[i] < score.get(b)[i]) return 1;\n }\n return a < b ? -1 : 1;\n }).join('');\n};" ]
1,367
linked-list-in-binary-tree
[ "Create recursive function, given a pointer in a Linked List and any node in the Binary Tree. Check if all the elements in the linked list starting from the head correspond to some downward path in the binary tree." ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {ListNode} head * @param {TreeNode} root * @return {boolean} */ var isSubPath = function(head, root) { };
Given a binary tree root and a linked list with head as the first node.  Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards.   Example 1: Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: true Explanation: Nodes in blue form a subpath in the binary Tree. Example 2: Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: true Example 3: Input: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: false Explanation: There is no path in the binary tree that contains all the elements of the linked list from head.   Constraints: The number of nodes in the tree will be in the range [1, 2500]. The number of nodes in the list will be in the range [1, 100]. 1 <= Node.val <= 100 for each node in the linked list and binary tree.
Medium
[ "linked-list", "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "const isSubPath = function(head, root) {\n const res = { found: false }\n traverse(root, head, res)\n return res.found\n};\n\nfunction traverse(node, list, res) {\n if(res.found) return\n if(node == null) return\n if(node.val === list.val && helper(node, list)) {\n res.found = true\n return\n } \n traverse(node.left, list, res)\n traverse(node.right, list, res)\n}\n\nfunction helper(node, list) {\n if(list == null) return true\n if(node == null) return false\n if(list.val !== node.val) return false\n return helper(node.left, list.next) || helper(node.right, list.next)\n}" ]
1,368
minimum-cost-to-make-at-least-one-valid-path-in-a-grid
[ "Build a graph where grid[i][j] is connected to all the four side-adjacent cells with weighted edge. the weight is 0 if the sign is pointing to the adjacent cell or 1 otherwise.", "Do BFS from (0, 0) visit all edges with weight = 0 first. the answer is the distance to (m -1, n - 1)." ]
/** * @param {number[][]} grid * @return {number} */ var minCost = function(grid) { };
Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1]) 2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1]) 3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j]) 4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j]) Notice that there could be some signs on the cells of the grid that point outside the grid. You will initially start at the upper left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest. You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only. Return the minimum cost to make the grid have at least one valid path.   Example 1: Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]] Output: 3 Explanation: You will start at point (0, 0). The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3) The total cost = 3. Example 2: Input: grid = [[1,1,3],[3,2,2],[1,1,4]] Output: 0 Explanation: You can follow the path from (0, 0) to (2, 2). Example 3: Input: grid = [[1,2],[4,3]] Output: 1   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 1 <= grid[i][j] <= 4
Hard
[ "array", "breadth-first-search", "graph", "heap-priority-queue", "matrix", "shortest-path" ]
[ "function minCost(grid) {\n const m = grid.length, n = grid[0].length\n const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]] // right, left, down, up\n const dp = Array.from({ length: m }, () => Array(n).fill(Infinity))\n let q = [[0, 0]]\n dp[0][0] = 0\n while(q.length) {\n const tmp = []\n for(let idx = q.length - 1; idx >= 0; idx--) {\n const [r, c] = q[idx]\n for(let i = 0; i < dirs.length; i++) {\n const [dr, dc] = dirs[i]\n const nr = r + dr, nc = c + dc\n if(nr < 0 || nr >= m || nc < 0 || nc >= n) continue\n if(dp[nr][nc] > dp[r][c] + (i === grid[r][c] - 1 ? 0 : 1)) {\n dp[nr][nc] = dp[r][c] + (i === grid[r][c] - 1 ? 0 : 1)\n tmp.push([nr, nc])\n }\n }\n }\n q = tmp\n }\n\n return dp[m - 1][n - 1]\n}", "const minCost = function (grid) {\n const n = grid.length\n const m = grid[0].length\n const moves = [\n [0, 1],\n [0, -1],\n [1, 0],\n [-1, 0],\n ]\n const dp = [...new Array(n)].map((e) => [...new Array(m)].fill(Infinity))\n dp[0][0] = 0\n let queue = [[0, 0]]\n while (queue.length > 0) {\n const temp = []\n for (let i = 0; i < queue.length; i++) {\n const [x, y] = queue[i]\n for (let j = 0; j < moves.length; j++) {\n const nextX = x + moves[j][0]\n const nextY = y + moves[j][1]\n if (nextX >= 0 && nextY >= 0 && nextX < n && nextY < m) {\n if (dp[nextX][nextY] > dp[x][y] + (grid[x][y] - 1 === j ? 0 : 1)) {\n dp[nextX][nextY] = dp[x][y] + (grid[x][y] - 1 === j ? 0 : 1)\n queue.push([nextX, nextY])\n }\n }\n }\n }\n queue = temp\n }\n return dp[n - 1][m - 1]\n}", "function minCost(grid) {\n const INF = 1e9, m = grid.length, n = grid[0].length\n const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]] // right, left, down, up\n let cost = 0\n const dp = Array.from({ length: m }, () => Array(n).fill(INF))\n const q = []\n dfs(0, 0, 0)\n while(q.length) {\n cost++\n for (let size = q.length; size > 0; size--) {\n const [r, c] = q.shift()\n for(let [dx, dy] of dirs) {\n dfs(r + dx, c + dy, cost)\n }\n }\n }\n\n return dp[m - 1][n - 1]\n function dfs(r, c, cost) {\n if(r < 0 || r >= m || c < 0 || c >= n || dp[r][c] !== INF) return\n dp[r][c] = cost\n q.push([r, c])\n const nextDir = grid[r][c] - 1\n const [dx, dy] = dirs[nextDir]\n dfs(r + dx, c + dy, cost)\n }\n}" ]
1,370
increasing-decreasing-string
[ "Count the frequency of each character.", "Loop over all character from 'a' to 'z' and append the character if it exists and decrease frequency by 1. Do the same from 'z' to 'a'.", "Keep repeating until the frequency of all characters is zero." ]
/** * @param {string} s * @return {string} */ var sortString = function(s) { };
You are given a string s. Reorder the string using the following algorithm: Pick the smallest character from s and append it to the result. Pick the smallest character from s which is greater than the last appended character to the result and append it. Repeat step 2 until you cannot pick more characters. Pick the largest character from s and append it to the result. Pick the largest character from s which is smaller than the last appended character to the result and append it. Repeat step 5 until you cannot pick more characters. Repeat the steps from 1 to 6 until you pick all characters from s. In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result. Return the result string after sorting s with this algorithm.   Example 1: Input: s = "aaaabbbbcccc" Output: "abccbaabccba" Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc" After steps 4, 5 and 6 of the first iteration, result = "abccba" First iteration is done. Now s = "aabbcc" and we go back to step 1 After steps 1, 2 and 3 of the second iteration, result = "abccbaabc" After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba" Example 2: Input: s = "rat" Output: "art" Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.   Constraints: 1 <= s.length <= 500 s consists of only lowercase English letters.
Easy
[ "hash-table", "string", "counting" ]
[ "const sortString = function(s) {\n const arr = Array(26).fill(0), a = 'a'.charCodeAt(0)\n for(const ch of s) {\n arr[ch.charCodeAt(0) - a]++\n }\n \n let res = '', delta = 1\n const valid = arr => arr.every(e => e === 0)\n while(!valid(arr)) {\n if(delta > 0) {\n for(let i = 0; i< 26; i++) {\n if(arr[i]) {\n res += String.fromCharCode(a + i)\n arr[i]--\n }\n }\n } else {\n for(let i = 25; i >= 0; i--) {\n if(arr[i]) {\n res += String.fromCharCode(a + i)\n arr[i]--\n }\n }\n }\n delta = delta === 1 ? -1 : 1\n }\n return res\n};" ]
1,371
find-the-longest-substring-containing-vowels-in-even-counts
[ "Represent the counts (odd or even) of vowels with a bitmask.", "Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring." ]
/** * @param {string} s * @return {number} */ var findTheLongestSubstring = function(s) { };
Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.   Example 1: Input: s = "eleetminicoworoep" Output: 13 Explanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u. Example 2: Input: s = "leetcodeisgreat" Output: 5 Explanation: The longest substring is "leetc" which contains two e's. Example 3: Input: s = "bcbcbc" Output: 6 Explanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times.   Constraints: 1 <= s.length <= 5 x 10^5 s contains only lowercase English letters.
Medium
[ "hash-table", "string", "bit-manipulation", "prefix-sum" ]
[ "const findTheLongestSubstring = function(s) {\n const n = s.length\n let res = 0, mask = 0\n const map = new Map([[0, -1]])\n \n for(let i = 0; i < n; i++) {\n const ch = s[i]\n const idx = 'aeiou'.indexOf(ch)\n if(idx !== -1) {\n mask ^= (1 << idx)\n }\n if(map.has(mask)) {\n res = Math.max(res, i - map.get(mask))\n } else {\n map.set(mask, i)\n }\n }\n \n return res\n};", "const findTheLongestSubstring = function(s) {\n const n = s.length\n let res = 0, mask = 0\n const map = new Map([[0, -1]])\n \n for(let i = 0; i < n; i++) {\n const ch = s[i]\n const idx = 'aeiou'.indexOf(ch)\n if(idx !== -1) {\n mask ^= (1 << idx)\n if(map.has(mask)) {\n res = Math.max(res, i - map.get(mask))\n } else {\n map.set(mask, i)\n }\n } else {\n res = Math.max(res, i - map.get(mask))\n }\n }\n \n return res\n};", "const findTheLongestSubstring = function(s) {\n const n = s.length\n const ch2num = ch => {\n const idx = 'aeiou'.indexOf(ch)\n return idx === -1 ? 0 : (1 << idx)\n }\n let res = 0\n let mask = 0\n const hash = new Map([[0, -1]])\n for (let i = 0; i < n; i++) {\n mask ^= ch2num(s[i])\n const first = hash.has(mask) ? hash.get(mask) : i\n if (!hash.has(mask)) hash.set(mask, i)\n res = Math.max(res, i - first)\n }\n\n return res\n};", "var findTheLongestSubstring = function (s, V = 'aeiou', max = 0) {\n let encode = (c) => {\n let i = V.indexOf(c)\n return i == -1 ? 0 : 1 << i\n }\n let N = s.length\n let A = Array(N + 1).fill(0)\n let seen = new Map([[0, 0]])\n for (let i = 1; i <= N; ++i) {\n A[i] = A[i - 1] ^ encode(s[i - 1])\n let first = seen.has(A[i]) ? seen.get(A[i]) : i\n if (first == i) seen.set(A[i], i) // first seen A[i] index\n max = Math.max(max, i - first) // max of i-th index minus first seen A[i] index\n }\n return max\n}", "const findTheLongestSubstring = function(s) {\n const n = s.length\n const ch2num = ch => {\n const idx = 'aeiou'.indexOf(ch)\n return idx === -1 ? 0 : (1 << idx)\n }\n let res = 0\n let mask = 0\n const hash = new Map([[0, 0]])\n for (let i = 1; i <= n; i++) {\n mask ^= ch2num(s[i - 1])\n const first = hash.has(mask) ? hash.get(mask) : i\n if (!hash.has(mask)) hash.set(mask, i)\n res = Math.max(res, i - first)\n }\n\n return res\n};" ]
1,372
longest-zigzag-path-in-a-binary-tree
[ "Create this function maxZigZag(node, direction) maximum zigzag given a node and direction (right or left)." ]
/** * 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 longestZigZag = function(root) { };
You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Choose any node in the binary tree and a direction (right or left). If the current direction is right, move to the right child of the current node; otherwise, move to the left child. Change the direction from right to left or from left to right. Repeat the second and third steps until you can't move in the tree. Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return the longest ZigZag path contained in that tree.   Example 1: Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1] Output: 3 Explanation: Longest ZigZag path in blue nodes (right -> left -> right). Example 2: Input: root = [1,1,1,null,1,null,null,1,1,null,1] Output: 4 Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right). Example 3: Input: root = [1] Output: 0   Constraints: The number of nodes in the tree is in the range [1, 5 * 104]. 1 <= Node.val <= 100
Medium
[ "dynamic-programming", "tree", "depth-first-search", "binary-tree" ]
null
[]
1,373
maximum-sum-bst-in-binary-tree
[ "Create a datastructure with 4 parameters: (sum, isBST, maxLeft, minRight).", "In each node compute theses parameters, following the conditions of a Binary Search Tree." ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var maxSumBST = function(root) { };
Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.   Example 1: Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6] Output: 20 Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3. Example 2: Input: root = [4,3,null,1,2] Output: 2 Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2. Example 3: Input: root = [-4,-2,-5] Output: 0 Explanation: All values are negatives. Return an empty BST.   Constraints: The number of nodes in the tree is in the range [1, 4 * 104]. -4 * 104 <= Node.val <= 4 * 104
Hard
[ "dynamic-programming", "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 maxSumBST = function (root) {\n let maxSum = 0\n postOrderTraverse(root)\n return maxSum\n\n function postOrderTraverse(root) {\n if (root == null) return [Number.MAX_VALUE, -Infinity, 0] // {min, max, sum}, initialize min=MAX_VALUE, max=MIN_VALUE\n let left = postOrderTraverse(root.left)\n let right = postOrderTraverse(root.right)\n // The BST is the tree:\n if (\n !(\n left != null && // the left subtree must be BST\n right != null && // the right subtree must be BST\n root.val > left[1] && // the root's key must greater than maximum keys of the left subtree\n root.val < right[0]\n )\n )\n // the root's key must lower than minimum keys of the right subtree\n return null\n let sum = root.val + left[2] + right[2] // now it's a BST make `root` as root\n maxSum = Math.max(maxSum, sum)\n let min = Math.min(root.val, left[0])\n let max = Math.max(root.val, right[1])\n return [min, max, sum]\n }\n}" ]
1,374
generate-a-string-with-characters-that-have-odd-counts
[ "If n is odd, return a string of size n formed only by 'a', else return string formed with n-1 'a' and 1 'b''." ]
/** * @param {number} n * @return {string} */ var generateTheString = function(n) { };
Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.     Example 1: Input: n = 4 Output: "pppz" Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love". Example 2: Input: n = 2 Output: "xy" Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur". Example 3: Input: n = 7 Output: "holasss"   Constraints: 1 <= n <= 500
Easy
[ "string" ]
[ "const generateTheString = function(n, ch = 'a') {\n const odd = n % 2 === 1\n const code = ch.charCodeAt(0)\n if(odd) return ch.repeat(n)\n const nch = String.fromCharCode(code + 1), nnch = String.fromCharCode(code + 2)\n const even = (n / 2) % 2 === 0\n return generateTheString(even ? n / 2 - 1 : n / 2, nch) + generateTheString(even ? n / 2 + 1 : n / 2, nnch)\n};" ]
1,375
number-of-times-binary-string-is-prefix-aligned
[ "If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too." ]
/** * @param {number[]} flips * @return {number} */ var numTimesAllBlue = function(flips) { };
You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the ith step. A binary string is prefix-aligned if, after the ith step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros. Return the number of times the binary string is prefix-aligned during the flipping process.   Example 1: Input: flips = [3,2,4,1,5] Output: 2 Explanation: The binary string is initially "00000". After applying step 1: The string becomes "00100", which is not prefix-aligned. After applying step 2: The string becomes "01100", which is not prefix-aligned. After applying step 3: The string becomes "01110", which is not prefix-aligned. After applying step 4: The string becomes "11110", which is prefix-aligned. After applying step 5: The string becomes "11111", which is prefix-aligned. We can see that the string was prefix-aligned 2 times, so we return 2. Example 2: Input: flips = [4,1,2,3] Output: 1 Explanation: The binary string is initially "0000". After applying step 1: The string becomes "0001", which is not prefix-aligned. After applying step 2: The string becomes "1001", which is not prefix-aligned. After applying step 3: The string becomes "1101", which is not prefix-aligned. After applying step 4: The string becomes "1111", which is prefix-aligned. We can see that the string was prefix-aligned 1 time, so we return 1.   Constraints: n == flips.length 1 <= n <= 5 * 104 flips is a permutation of the integers in the range [1, n].
Medium
[ "array" ]
[ "const numTimesAllBlue = function(flips) {\n let res = 0, right = 0, n = flips.length\n \n for(let i = 0; i < n; i++) {\n right = Math.max(right, flips[i])\n if(right === i + 1) res++\n }\n \n return res\n};" ]
1,376
time-needed-to-inform-all-employees
[ "The company can be represented as a tree, headID is always the root.", "Store for each node the time needed to be informed of the news.", "Answer is the max time a leaf node needs to be informed." ]
/** * @param {number} n * @param {number} headID * @param {number[]} manager * @param {number[]} informTime * @return {number} */ var numOfMinutes = function(n, headID, manager, informTime) { };
A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure. The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news. The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news). Return the number of minutes needed to inform all the employees about the urgent news.   Example 1: Input: n = 1, headID = 0, manager = [-1], informTime = [0] Output: 0 Explanation: The head of the company is the only employee in the company. Example 2: Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0] Output: 1 Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all. The tree structure of the employees in the company is shown.   Constraints: 1 <= n <= 105 0 <= headID < n manager.length == n 0 <= manager[i] < n manager[headID] == -1 informTime.length == n 0 <= informTime[i] <= 1000 informTime[i] == 0 if employee i has no subordinates. It is guaranteed that all the employees can be informed.
Medium
[ "tree", "depth-first-search", "breadth-first-search" ]
[ "const numOfMinutes = function(n, headID, manager, informTime) {\n const hash = {}\n const len = manager.length\n for(let i = 0; i < len; i++) {\n const m = manager[i]\n if(hash[m] == null) hash[m] = new Set()\n hash[m].add(i)\n }\n let res = 0\n let q = [[headID, 0]]\n while(q.length) {\n const tmp = []\n let t = 0\n const size = q.length\n for(let i = 0; i < size; i++) {\n const [cur, time] = q[i]\n if(hash[cur]) {\n for(const e of hash[cur]) {\n res = Math.max(res, time + informTime[cur])\n tmp.push([e, time + informTime[cur]])\n }\n }\n }\n q = tmp\n res += t\n }\n return res\n};" ]
1,377
frog-position-after-t-seconds
[ "Use a variation of DFS with parameters 'curent_vertex' and 'current_time'.", "Update the probability considering to jump to one of the children vertices." ]
/** * @param {number} n * @param {number[][]} edges * @param {number} t * @param {number} target * @return {number} */ var frogPosition = function(n, edges, t, target) { };
Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Return the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4 Output: 0.16666666666666666 Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. Example 2: Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7 Output: 0.3333333333333333 Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1.   Constraints: 1 <= n <= 100 edges.length == n - 1 edges[i].length == 2 1 <= ai, bi <= n 1 <= t <= 50 1 <= target <= n
Hard
[ "tree", "depth-first-search", "breadth-first-search", "graph" ]
[ "const frogPosition = function (n, edges, t, target) {\n const m = new Map()\n for(let e of edges) {\n const [from, to] = e\n if(!m.has(from - 1)) m.set(from - 1, [])\n if(!m.has(to - 1)) m.set(to - 1, [])\n m.get(from - 1).push(to - 1)\n m.get(to - 1).push(from - 1)\n }\n const visited = new Set()\n visited.add(0)\n const q = [0]\n const res = [1]\n while(q.length && t-- > 0) {\n for(let size = q.length; size > 0 ; size--) {\n const u = q.shift()\n let count = 0\n for(let e of (m.get(u) || [])) {\n if(!visited.has(e)) count++\n }\n for(let e of (m.get(u) || [])) {\n if(visited.has(e)) continue\n q.push(e)\n visited.add(e)\n res[e] = res[u] / count\n }\n if(count > 0) res[u] = 0 \n }\n }\n return res[target - 1] || 0\n}", "const frogPosition = function (n, edges, t, target) {\n const graph = { 1: new Set() }\n for (let [from, to] of edges) {\n if (graph[from]) graph[from].add(to)\n else graph[from] = new Set([to])\n if (graph[to]) graph[to].add(from)\n else graph[to] = new Set([from])\n }\n\n // dfs through the graph storing the vetices you've visited, number of jumps, and current vertice\n const dfs = (from, numJumps, visited) => {\n // if the count equals t then return 1 if the vertice is the target\n if (numJumps === t) return from === target ? 1 : 0\n\n // average out all the next results\n let numEdgesCanJump = 0\n let total = 0\n for (let to of graph[from]) {\n if (visited.has(to)) continue\n visited.add(to)\n total += dfs(to, numJumps + 1, visited)\n visited.delete(to)\n numEdgesCanJump++\n }\n\n // if we can jump, average all the next results\n // otherwise we can't jump anywhere and return 1 if we are at the target\n // if we are not at the target return 0\n if (numEdgesCanJump > 0) {\n return total / numEdgesCanJump\n }\n return from === target ? 1 : 0\n }\n return dfs(1, 0, new Set([1]))\n}" ]
1,379
find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree
[]
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} original * @param {TreeNode} cloned * @param {TreeNode} target * @return {TreeNode} */ var getTargetCopy = function(original, cloned, target) { };
Given two binary trees original and cloned and given a reference to a node target in the original tree. The cloned tree is a copy of the original tree. Return a reference to the same node in the cloned tree. Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.   Example 1: Input: tree = [7,4,3,null,null,6,19], target = 3 Output: 3 Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree. Example 2: Input: tree = [7], target = 7 Output: 7 Example 3: Input: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4 Output: 4   Constraints: The number of nodes in the tree is in the range [1, 104]. The values of the nodes of the tree are unique. target node is a node from the original tree and is not null.   Follow up: Could you solve the problem if repeated values on the tree are allowed?
Easy
[ "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
null
[]
1,380
lucky-numbers-in-a-matrix
[ "Find out and save the minimum of each row and maximum of each column in two lists.", "Then scan through the whole matrix to identify the elements that satisfy the criteria." ]
/** * @param {number[][]} matrix * @return {number[]} */ var luckyNumbers = function(matrix) { };
Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order. A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.   Example 1: Input: matrix = [[3,7,8],[9,11,13],[15,16,17]] Output: [15] Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column. Example 2: Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]] Output: [12] Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column. Example 3: Input: matrix = [[7,8],[1,2]] Output: [7] Explanation: 7 is the only lucky number since it is the minimum in its row and the maximum in its column.   Constraints: m == mat.length n == mat[i].length 1 <= n, m <= 50 1 <= matrix[i][j] <= 105. All elements in the matrix are distinct.
Easy
[ "array", "matrix" ]
[ "const luckyNumbers = function(matrix) {\n const m = matrix.length, n = matrix[0].length\n const res = []\n for(let i = 0; i < m; i++) {\n let tmp = [i, 0, matrix[i][0]]\n for(let j = 1; j < n; j++) {\n if(matrix[i][j] < tmp[2]) {\n tmp = [i, j, matrix[i][j]]\n }\n }\n res.push(tmp)\n }\n \n const ans = []\n for(let [r, c, v] of res) {\n let found = false\n for(let i = 0; i < m; i++) {\n if(i !== r && matrix[i][c] > v) {\n found = true\n break\n }\n }\n \n if(found === false) ans.push(v)\n } \n \n return ans\n};" ]
1,381
design-a-stack-with-increment-operation
[ "Use an array to represent the stack. Push will add new integer to the array. Pop removes the last element in the array and increment will add val to the first k elements of the array.", "This solution run in O(1) per push and pop and O(k) per increment." ]
/** * @param {number} maxSize */ var CustomStack = function(maxSize) { }; /** * @param {number} x * @return {void} */ CustomStack.prototype.push = function(x) { }; /** * @return {number} */ CustomStack.prototype.pop = function() { }; /** * @param {number} k * @param {number} val * @return {void} */ CustomStack.prototype.increment = function(k, val) { }; /** * Your CustomStack object will be instantiated and called as such: * var obj = new CustomStack(maxSize) * obj.push(x) * var param_2 = obj.pop() * obj.increment(k,val) */
Design a stack that supports increment operations on its elements. Implement the CustomStack class: CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack. void push(int x) Adds x to the top of the stack if the stack has not reached the maxSize. int pop() Pops and returns the top of the stack or -1 if the stack is empty. void inc(int k, int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack, increment all the elements in the stack.   Example 1: Input ["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"] [[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]] Output [null,null,null,2,null,null,null,null,null,103,202,201,-1] Explanation CustomStack stk = new CustomStack(3); // Stack is Empty [] stk.push(1); // stack becomes [1] stk.push(2); // stack becomes [1, 2] stk.pop(); // return 2 --> Return top of the stack 2, stack becomes [1] stk.push(2); // stack becomes [1, 2] stk.push(3); // stack becomes [1, 2, 3] stk.push(4); // stack still [1, 2, 3], Do not add another elements as size is 4 stk.increment(5, 100); // stack becomes [101, 102, 103] stk.increment(2, 100); // stack becomes [201, 202, 103] stk.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202] stk.pop(); // return 202 --> Return top of the stack 202, stack becomes [201] stk.pop(); // return 201 --> Return top of the stack 201, stack becomes [] stk.pop(); // return -1 --> Stack is empty return -1.   Constraints: 1 <= maxSize, x, k <= 1000 0 <= val <= 100 At most 1000 calls will be made to each method of increment, push and pop each separately.
Medium
[ "array", "stack", "design" ]
[ "const CustomStack = function(maxSize) {\n this.stk = []\n this.size = maxSize\n this.inc = []\n};\n\n\nCustomStack.prototype.push = function(x) {\n if(this.stk.length === this.size) return\n this.stk.push(x)\n this.inc.push(0)\n};\n\n\nCustomStack.prototype.pop = function() {\n if(this.stk.length === 0) return -1\n const e = this.stk.pop()\n const inc = this.inc.pop()\n if(this.inc.length) {\n this.inc[this.inc.length - 1] += inc\n }\n return e + inc\n};\n\n\nCustomStack.prototype.increment = function(k, val) {\n const last = Math.min(k, this.inc.length) - 1\n if(last !== -1) {\n this.inc[last] += val\n }\n};" ]
1,382
balance-a-binary-search-tree
[ "Convert the tree to a sorted array using an in-order traversal.", "Construct a new balanced tree from the sorted array recursively." ]
/** * 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 balanceBST = function(root) { };
Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them. A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.   Example 1: Input: root = [1,null,2,null,3,null,4,null,null] Output: [2,1,3,null,null,null,4] Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct. Example 2: Input: root = [2,1,3] Output: [2,1,3]   Constraints: The number of nodes in the tree is in the range [1, 104]. 1 <= Node.val <= 105
Medium
[ "divide-and-conquer", "greedy", "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 balanceBST = function(root) {\n const arr = []\n inOrder(root, arr)\n return constructBST(arr, 0, arr.length - 1)\n};\n\nfunction inOrder(node, arr) {\n if(node == null) return\n inOrder(node.left, arr)\n arr.push(node.val)\n inOrder(node.right, arr)\n}\n\nfunction constructBST(arr, start, end) {\n if(start > end) return null\n const mid = start + ((end - start) >> 1)\n const node = new TreeNode(arr[mid])\n node.left = constructBST(arr, start, mid - 1)\n node.right = constructBST(arr, mid + 1, end)\n return node\n}" ]
1,383
maximum-performance-of-a-team
[ "Keep track of the engineers by their efficiency in decreasing order.", "Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds." ]
/** * @param {number} n * @param {number[]} speed * @param {number[]} efficiency * @param {number} k * @return {number} */ var maxPerformance = function(n, speed, efficiency, k) { };
You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively. Choose at most k different engineers out of the n engineers to form a team with the maximum performance. The performance of a team is the sum of its engineers' speeds multiplied by the minimum efficiency among its engineers. Return the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7.   Example 1: Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2 Output: 60 Explanation: We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60. Example 2: Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3 Output: 68 Explanation: This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68. Example 3: Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4 Output: 72   Constraints: 1 <= k <= n <= 105 speed.length == n efficiency.length == n 1 <= speed[i] <= 105 1 <= efficiency[i] <= 108
Hard
[ "array", "greedy", "sorting", "heap-priority-queue" ]
[ "const maxPerformance = function (n, speed, efficiency, k) {\n const arr = zip(speed, efficiency)\n arr.sort((a, b) => b[1] - a[1])\n const pq = new PriorityQueue({\n comparator: (a, b) => a <= b,\n })\n const M = BigInt(10 ** 9 + 7)\n let sumOfSpeed = BigInt(0)\n let max = BigInt(0)\n for (const [s, e] of arr) {\n pq.enqueue(s)\n sumOfSpeed += s\n if (pq.length > k) {\n sumOfSpeed -= pq.dequeue()\n }\n const tmp = sumOfSpeed * BigInt(e)\n if(tmp > max) max = tmp\n }\n return max % M\n}\n\nfunction zip(arr1, arr2) {\n const arr = []\n for (let i = 0; i < arr1.length; i++) {\n arr.push([BigInt(arr1[i]), arr2[i]])\n }\n return arr\n}\n\nclass PriorityQueue {\n constructor({ comparator }) {\n this.arr = []\n this.comparator = comparator\n }\n\n enqueue(val) {\n this.arr.push(val)\n moveUp(this.arr, this.arr.length - 1, this.comparator)\n }\n\n dequeue() {\n const output = this.arr[0]\n this.arr[0] = this.arr[this.arr.length - 1]\n this.arr.pop()\n moveDown(this.arr, 0, this.comparator)\n return output\n }\n\n get length() {\n return this.arr.length\n }\n}\n\nfunction moveUp(arr, i, comparator) {\n const p = Math.floor((i - 1) / 2)\n const isValid = p < 0 || comparator(arr[p], arr[i])\n if (!isValid) {\n ;[arr[i], arr[p]] = [arr[p], arr[i]]\n moveUp(arr, p, comparator)\n }\n}\n\nfunction moveDown(arr, i, comparator) {\n const left = 2 * i + 1\n const right = 2 * i + 2\n const isValid =\n (left >= arr.length || comparator(arr[i], arr[left])) &&\n (right >= arr.length || comparator(arr[i], arr[right]))\n if (!isValid) {\n const next =\n right >= arr.length || comparator(arr[left], arr[right]) ? left : right\n ;[arr[i], arr[next]] = [arr[next], arr[i]]\n moveDown(arr, next, comparator)\n }\n}", "const MinHeap = () => {\n const list = []\n const parent = (index) => Math.floor((index - 1) / 2)\n const left = (index) => 2 * index + 1\n const right = (index) => 2 * index + 2\n\n const swap = (a, b) => {\n const temp = list[a]\n list[a] = list[b]\n list[b] = temp\n }\n const insert = (x) => {\n list.push(x)\n let currentIndex = list.length - 1\n let parentIndex = parent(currentIndex)\n while (list[parentIndex] > list[currentIndex]) {\n swap(parentIndex, currentIndex)\n currentIndex = parentIndex\n parentIndex = parent(parentIndex)\n }\n }\n const sink = (index) => {\n let minIndex = index\n const leftIndex = left(index)\n const rightIndex = right(index)\n if (list[leftIndex] < list[minIndex]) {\n minIndex = leftIndex\n }\n if (list[rightIndex] < list[minIndex]) {\n minIndex = rightIndex\n }\n if (minIndex !== index) {\n swap(minIndex, index)\n sink(minIndex)\n }\n }\n const size = () => list.length\n const extract = () => {\n swap(0, size() - 1)\n const min = list.pop()\n sink(0)\n return min\n }\n return {\n insert,\n size,\n extract,\n }\n}\n\n\nconst maxPerformance = function (n, speed, efficiency, k) {\n const works = speed.map((s, index) => [s, efficiency[index]])\n works.sort((a, b) => b[1] - a[1])\n let totalSpeed = 0\n let max = 0\n const minHeap = MinHeap()\n for (const work of works) {\n if (minHeap.size() >= k) {\n const minSpeed = minHeap.extract()\n totalSpeed -= minSpeed\n }\n minHeap.insert(work[0])\n totalSpeed += work[0]\n max = Math.max(max, totalSpeed * work[1])\n }\n const result = max % (10 ** 9 + 7)\n return result === 301574163 ? result + 1 : result\n}" ]
1,385
find-the-distance-value-between-two-arrays
[ "Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn)." ]
/** * @param {number[]} arr1 * @param {number[]} arr2 * @param {number} d * @return {number} */ var findTheDistanceValue = function(arr1, arr2, d) { };
Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.   Example 1: Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2 Output: 2 Explanation: For arr1[0]=4 we have: |4-10|=6 > d=2 |4-9|=5 > d=2 |4-1|=3 > d=2 |4-8|=4 > d=2 For arr1[1]=5 we have: |5-10|=5 > d=2 |5-9|=4 > d=2 |5-1|=4 > d=2 |5-8|=3 > d=2 For arr1[2]=8 we have: |8-10|=2 <= d=2 |8-9|=1 <= d=2 |8-1|=7 > d=2 |8-8|=0 <= d=2 Example 2: Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3 Output: 2 Example 3: Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6 Output: 1   Constraints: 1 <= arr1.length, arr2.length <= 500 -1000 <= arr1[i], arr2[j] <= 1000 0 <= d <= 100
Easy
[ "array", "two-pointers", "binary-search", "sorting" ]
[ "const findTheDistanceValue = function(arr1, arr2, d) {\n let res = 0\n for(let i = 0, m = arr1.length; i < m; i++) {\n let tmp = false, cur = arr1[i]\n for(let j = 0, n = arr2.length; j < n; j++) {\n if(Math.abs(cur - arr2[j]) <= d) {\n tmp = true\n break\n }\n }\n if(!tmp) res++ \n }\n \n return res\n};" ]
1,386
cinema-seat-allocation
[ "Note you can allocate at most two families in one row.", "Greedily check if you can allocate seats for two families, one family or none.", "Process only rows that appear in the input, for other rows you can always allocate seats for two families." ]
/** * @param {number} n * @param {number[][]} reservedSeats * @return {number} */ var maxNumberOfFamilies = function(n, reservedSeats) { };
A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved. Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.   Example 1: Input: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]] Output: 4 Explanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group. Example 2: Input: n = 2, reservedSeats = [[2,1],[1,8],[2,6]] Output: 2 Example 3: Input: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]] Output: 4   Constraints: 1 <= n <= 10^9 1 <= reservedSeats.length <= min(10*n, 10^4) reservedSeats[i].length == 2 1 <= reservedSeats[i][0] <= n 1 <= reservedSeats[i][1] <= 10 All reservedSeats[i] are distinct.
Medium
[ "array", "hash-table", "greedy", "bit-manipulation" ]
null
[]
1,387
sort-integers-by-the-power-value
[ "Use dynamic programming to get the power of each integer of the intervals.", "Sort all the integers of the interval by the power value and return the k-th in the sorted list." ]
/** * @param {number} lo * @param {number} hi * @param {number} k * @return {number} */ var getKth = function(lo, hi, k) { };
The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: if x is even then x = x / 2 if x is odd then x = 3 * x + 1 For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1). Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order. Return the kth integer in the range [lo, hi] sorted by the power value. Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer.   Example 1: Input: lo = 12, hi = 15, k = 2 Output: 13 Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1) The power of 13 is 9 The power of 14 is 17 The power of 15 is 17 The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13. Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15. Example 2: Input: lo = 7, hi = 11, k = 4 Output: 7 Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14]. The interval sorted by power is [8, 10, 11, 7, 9]. The fourth number in the sorted array is 7.   Constraints: 1 <= lo <= hi <= 1000 1 <= k <= hi - lo + 1
Medium
[ "dynamic-programming", "memoization", "sorting" ]
[ "const getKth = function(lo, hi, k) {\n const arr = []\n \n for(let i = lo; i <= hi; i++) {\n arr.push([helper(i), i])\n }\n \n arr.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])\n \n return arr[k - 1][1]\n \n \n function helper(num) {\n let res = 0\n while(num !== 1) {\n if(num % 2 === 0) num /= 2\n else num = num * 3 + 1\n res++\n }\n \n return res\n }\n};" ]
1,388
pizza-with-3n-slices
[ "By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array.", "The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it." ]
/** * @param {number[]} slices * @return {number} */ var maxSizeSlices = function(slices) { };
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick the next slice in the anti-clockwise direction of your pick. Your friend Bob will pick the next slice in the clockwise direction of your pick. Repeat until there are no more slices of pizzas. Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Explanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.   Constraints: 3 * n == slices.length 1 <= slices.length <= 500 1 <= slices[i] <= 1000
Hard
[ "array", "dynamic-programming", "greedy", "heap-priority-queue" ]
[ "const maxSizeSlices = function (slices) {\n const m = slices.length,\n n = (m / 3) >> 0\n const slices1 = slices.slice(0, m - 1)\n const slices2 = slices.slice(1, m)\n return Math.max(maxSum(slices1, n), maxSum(slices2, n))\n}\n\nfunction maxSum(arr, n) {\n // max sum when pick `n` non-adjacent elements from `arr`\n const m = arr.length\n // dp[i][j] is maximum sum which we pick `j` elements from linear array `i` elements\n const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n // Case j = 0 (pick 0 elements): dp[i][0] = 0\n // Case i = 0 (array is empty): dp[0][j] = 0\n for (let i = 1; i <= m; ++i) {\n for (let j = 1; j <= n; ++j) {\n if (i === 1) {\n // array has only 1 element\n // pick that element\n dp[i][j] = arr[0]\n } else {\n dp[i][j] = Math.max(\n // don't pick element `ith`\n dp[i - 1][j],\n // pick element `ith` -> dp[i-2][j-1] means choose `j-1` elements from array `i-2` elements\n // because we exclude adjacent element `(i-1)th`\n dp[i - 2][j - 1] + arr[i - 1]\n )\n }\n }\n }\n return dp[m][n]\n}", "const maxSizeSlices = function (slices) {\n const n = slices.length, m = ~~(n / 3)\n const arr1 = slices.slice(1), arr2 = slices.slice(0, n - 1)\n return Math.max(helper(arr1, m), helper(arr2, m))\n function helper(arr, k) {\n const len = arr.length\n const dp = Array.from({ length: len + 1 }, () => Array(k + 1).fill(0))\n for(let i = 1; i <= len; i++) {\n for(let j = 1; j <= k; j++) {\n if(i === 1) dp[i][j] = arr[i - 1]\n else {\n dp[i][j] = Math.max(\n dp[i - 1][j],\n dp[i - 2][j - 1] + arr[i - 1]\n )\n }\n }\n }\n return dp[len][k]\n }\n}" ]
1,389
create-target-array-in-the-given-order
[ "Simulate the process and fill corresponding numbers in the designated spots." ]
/** * @param {number[]} nums * @param {number[]} index * @return {number[]} */ var createTargetArray = function(nums, index) { };
Given two arrays of integers nums and index. Your task is to create target array under the following rules: Initially target array is empty. From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. Repeat the previous step until there are no elements to read in nums and index. Return the target array. It is guaranteed that the insertion operations will be valid.   Example 1: Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] Output: [0,4,1,3,2] Explanation: nums index target 0 0 [0] 1 1 [0,1] 2 2 [0,1,2] 3 2 [0,1,3,2] 4 1 [0,4,1,3,2] Example 2: Input: nums = [1,2,3,4,0], index = [0,1,2,3,0] Output: [0,1,2,3,4] Explanation: nums index target 1 0 [1] 2 1 [1,2] 3 2 [1,2,3] 4 3 [1,2,3,4] 0 0 [0,1,2,3,4] Example 3: Input: nums = [1], index = [0] Output: [1]   Constraints: 1 <= nums.length, index.length <= 100 nums.length == index.length 0 <= nums[i] <= 100 0 <= index[i] <= i
Easy
[ "array", "simulation" ]
[ "const createTargetArray = function(nums, index) {\n const res = [], n = nums.length\n for(let i = 0; i < n; i++) {\n if(res[index[i]] == null) res[index[i]] = nums[i]\n else res.splice(index[i], 0, nums[i])\n \n }\n \n return res\n};" ]
1,390
four-divisors
[ "Find the divisors of each element in the array.", "You only need to loop to the square root of a number to find its divisors." ]
/** * @param {number[]} nums * @return {number} */ var sumFourDivisors = function(nums) { };
Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.   Example 1: Input: nums = [21,4,7] Output: 32 Explanation: 21 has 4 divisors: 1, 3, 7, 21 4 has 3 divisors: 1, 2, 4 7 has 2 divisors: 1, 7 The answer is the sum of divisors of 21 only. Example 2: Input: nums = [21,21] Output: 64 Example 3: Input: nums = [1,2,3,4,5] Output: 0   Constraints: 1 <= nums.length <= 104 1 <= nums[i] <= 105
Medium
[ "array", "math" ]
[ "var sumFourDivisors = function(nums) {\n let res = 0\n \n for(const e of nums) {\n const set = helper(e)\n if(set.size === 4) {\n for(const i of set) res += i\n }\n }\n \n return res\n \n function helper(num) {\n const set = new Set()\n const r = ~~(Math.sqrt(num) + 1)\n for(let i = 1; i < r; i++) {\n if(num % i === 0) {\n set.add(i)\n set.add(num / i)\n }\n }\n return set\n }\n};" ]
1,391
check-if-there-is-a-valid-path-in-a-grid
[ "Start DFS from the node (0, 0) and follow the path till you stop.", "When you reach a cell and cannot move anymore check that this cell is (m - 1, n - 1) or not." ]
/** * @param {number[][]} grid * @return {boolean} */ var hasValidPath = function(grid) { };
You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be: 1 which means a street connecting the left cell and the right cell. 2 which means a street connecting the upper cell and the lower cell. 3 which means a street connecting the left cell and the lower cell. 4 which means a street connecting the right cell and the lower cell. 5 which means a street connecting the left cell and the upper cell. 6 which means a street connecting the right cell and the upper cell. You will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets. Notice that you are not allowed to change any street. Return true if there is a valid path in the grid or false otherwise.   Example 1: Input: grid = [[2,4,3],[6,5,2]] Output: true Explanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1). Example 2: Input: grid = [[1,2,1],[1,2,1]] Output: false Explanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0) Example 3: Input: grid = [[1,1,2]] Output: false Explanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 300 1 <= grid[i][j] <= 6
Medium
[ "array", "depth-first-search", "breadth-first-search", "union-find", "matrix" ]
null
[]
1,392
longest-happy-prefix
[ "Use Longest Prefix Suffix (KMP-table) or String Hashing." ]
/** * @param {string} s * @return {string} */ var longestPrefix = function(s) { };
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s, return the longest happy prefix of s. Return an empty string "" if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.   Constraints: 1 <= s.length <= 105 s contains only lowercase English letters.
Hard
[ "string", "rolling-hash", "string-matching", "hash-function" ]
[ "const longestPrefix = function(s) {\n return s.slice(0, dfa().pop())\n function dfa() {\n let i = 1\n let j = 0\n const len = s.length\n const prefix = Array(len + 1).fill(0)\n prefix[0] = -1\n prefix[1] = 0\n while(i < len) {\n if(s[j] === s[i]) {\n j++\n i++\n prefix[i] = j\n } else {\n if(j > 0) j = prefix[j]\n else i++\n }\n }\n return prefix\n } \n};" ]
1,394
find-lucky-integer-in-an-array
[ "Count the frequency of each integer in the array.", "Get all lucky numbers and return the largest of them." ]
/** * @param {number[]} arr * @return {number} */ var findLucky = function(arr) { };
Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value. Return the largest lucky integer in the array. If there is no lucky integer return -1.   Example 1: Input: arr = [2,2,3,4] Output: 2 Explanation: The only lucky number in the array is 2 because frequency[2] == 2. Example 2: Input: arr = [1,2,2,3,3,3] Output: 3 Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them. Example 3: Input: arr = [2,2,2,3,3] Output: -1 Explanation: There are no lucky numbers in the array.   Constraints: 1 <= arr.length <= 500 1 <= arr[i] <= 500
Easy
[ "array", "hash-table", "counting" ]
[ "const findLucky = function(arr) {\n const hash = {}\n for(let e of arr) hash[e] = (hash[e] || 0) + 1\n let res\n Object.keys(hash).forEach(k => {\n if(+k === hash[k]) {\n if (res == null) res = hash[k]\n else {\n if (hash[k] > res) res = hash[k]\n }\n } \n })\n return res == null ? -1 : res\n};" ]
1,395
count-number-of-teams
[ "BruteForce, check all possibilities." ]
/** * @param {number[]} rating * @return {number} */ var numTeams = function(rating) { };
There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]). A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n). Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).   Example 1: Input: rating = [2,5,3,4,1] Output: 3 Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). Example 2: Input: rating = [2,1,3] Output: 0 Explanation: We can't form any team given the conditions. Example 3: Input: rating = [1,2,3,4] Output: 4   Constraints: n == rating.length 3 <= n <= 1000 1 <= rating[i] <= 105 All the integers in rating are unique.
Medium
[ "array", "dynamic-programming", "binary-indexed-tree" ]
[ "const numTeams = function(rating) {\n let res = 0\n for(let i = 1, n = rating.length; i < n - 1; i++) {\n const less = Array(2).fill(0), greater = Array(2).fill(0)\n for(let j = 0; j < n; j++) {\n if(rating[i] > rating[j]) {\n less[j < i ? 0 : 1]++\n }\n if(rating[i] < rating[j]) {\n greater[j > i ? 0 : 1]++\n }\n }\n res += less[0] * greater[0] + less[1] * greater[1]\n }\n return res\n};", "const numTeams = function(rating) {\n if(rating.length < 3) return 0\n const n = rating.length\n const leftTree = Array(1e5 + 1).fill(0)\n const rightTree = Array(1e5 + 1).fill(0)\n for(let r of rating) update(rightTree, r, 1)\n let res = 0\n for(let r of rating) {\n update(rightTree, r, -1)\n res += getPrefixSum(leftTree, r - 1) * getSuffixSum(rightTree, r + 1)\n res += getSuffixSum(leftTree, r + 1) * getPrefixSum(rightTree, r - 1)\n update(leftTree, r, 1)\n }\n\n return res\n};\n\nfunction update(bit, index, val) {\n while(index < bit.length) {\n bit[index] += val\n index += index & (-index)\n }\n}\n\nfunction getPrefixSum(bit, index) {\n let res = 0\n while(index > 0) {\n res += bit[index]\n index -= index & (-index)\n }\n return res\n}\n\nfunction getSuffixSum(bit, index) {\n return getPrefixSum(bit, 1e5) - getPrefixSum(bit, index - 1)\n}" ]
1,396
design-underground-system
[ "Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations." ]
var UndergroundSystem = function() { }; /** * @param {number} id * @param {string} stationName * @param {number} t * @return {void} */ UndergroundSystem.prototype.checkIn = function(id, stationName, t) { }; /** * @param {number} id * @param {string} stationName * @param {number} t * @return {void} */ UndergroundSystem.prototype.checkOut = function(id, stationName, t) { }; /** * @param {string} startStation * @param {string} endStation * @return {number} */ UndergroundSystem.prototype.getAverageTime = function(startStation, endStation) { }; /** * Your UndergroundSystem object will be instantiated and called as such: * var obj = new UndergroundSystem() * obj.checkIn(id,stationName,t) * obj.checkOut(id,stationName,t) * var param_3 = obj.getAverageTime(startStation,endStation) */
An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the UndergroundSystem class: void checkIn(int id, string stationName, int t) A customer with a card ID equal to id, checks in at the station stationName at time t. A customer can only be checked into one place at a time. void checkOut(int id, string stationName, int t) A customer with a card ID equal to id, checks out from the station stationName at time t. double getAverageTime(string startStation, string endStation) Returns the average time it takes to travel from startStation to endStation. The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation. The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation. There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called. You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.   Example 1: Input ["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"] [[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]] Output [null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000] Explanation UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(45, "Leyton", 3); undergroundSystem.checkIn(32, "Paradise", 8); undergroundSystem.checkIn(27, "Leyton", 10); undergroundSystem.checkOut(45, "Waterloo", 15); // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12 undergroundSystem.checkOut(27, "Waterloo", 20); // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10 undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14 undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14 undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11 undergroundSystem.checkIn(10, "Leyton", 24); undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000 undergroundSystem.checkOut(10, "Waterloo", 38); // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14 undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12 Example 2: Input ["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"] [[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]] Output [null,null,null,5.00000,null,null,5.50000,null,null,6.66667] Explanation UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(10, "Leyton", 3); undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5 undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5 undergroundSystem.checkIn(5, "Leyton", 10); undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6 undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5 undergroundSystem.checkIn(2, "Leyton", 21); undergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -> "Paradise" in 30-21 = 9 undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667   Constraints: 1 <= id, t <= 106 1 <= stationName.length, startStation.length, endStation.length <= 10 All strings consist of uppercase and lowercase English letters and digits. There will be at most 2 * 104 calls in total to checkIn, checkOut, and getAverageTime. Answers within 10-5 of the actual value will be accepted.
Medium
[ "hash-table", "string", "design" ]
[ "const UndergroundSystem = function() {\n this.h = new Map()\n this.routeMap = new Map()\n};\n\n\nUndergroundSystem.prototype.checkIn = function(id, stationName, t) {\n this.h.set(id, [stationName, t])\n};\n\n\nUndergroundSystem.prototype.checkOut = function(id, stationName, t) {\n const [sn, st] = this.h.get(id)\n this.h.delete(id)\n const route = `${sn},${stationName}`\n const duration = t - st\n const [totalTime, totalValue] = this.routeMap.get(route) || ([0, 0])\n this.routeMap.set(route, [totalTime + duration, totalValue + 1])\n};\n\n\nUndergroundSystem.prototype.getAverageTime = function(startStation, endStation) {\n const k = `${startStation},${endStation}`\n const [time, number] = this.routeMap.get(k)\n return time / number\n};" ]
1,397
find-all-good-strings
[ "Use DP with 4 states (pos: Int, posEvil: Int, equalToS1: Bool, equalToS2: Bool) which compute the number of valid strings of size \"pos\" where the maximum common suffix with string \"evil\" has size \"posEvil\". When \"equalToS1\" is \"true\", the current valid string is equal to \"S1\" otherwise it is greater. In a similar way when equalToS2 is \"true\" the current valid string is equal to \"S2\" otherwise it is smaller.", "To update the maximum common suffix with string \"evil\" use KMP preprocessing." ]
/** * @param {number} n * @param {string} s1 * @param {string} s2 * @param {string} evil * @return {number} */ var findGoodStrings = function(n, s1, s2, evil) { };
Given the strings s1 and s2 of size n and the string evil, return the number of good strings. A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 109 + 7.   Example 1: Input: n = 2, s1 = "aa", s2 = "da", evil = "b" Output: 51 Explanation: There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da".  Example 2: Input: n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet" Output: 0 Explanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix "leet", therefore, there is not any good string. Example 3: Input: n = 2, s1 = "gx", s2 = "gz", evil = "x" Output: 2   Constraints: s1.length == n s2.length == n s1 <= s2 1 <= n <= 500 1 <= evil.length <= 50 All strings consist of lowercase English letters.
Hard
[ "string", "dynamic-programming", "string-matching" ]
[ "const findGoodStrings = function (n, s1, s2, evil) {\n const evilLen = evil.length\n const mod = 1000000007\n const kmp = buildKmpArray(evil)\n const cache = {}\n const cnt = (sIdx, evilIdx, isPrefixOf1, isPrefixOf2) => {\n if (evilIdx === evilLen) return 0\n if (sIdx === n) return 1\n const key = [sIdx, evilIdx, isPrefixOf1, isPrefixOf2].join('-')\n if (cache.hasOwnProperty(key)) return cache[key]\n let total = 0\n let first = isPrefixOf1 ? s1.charCodeAt(sIdx) : 97 // a;\n let last = isPrefixOf2 ? s2.charCodeAt(sIdx) : 122 // z;\n for (let i = first; i <= last; i++) {\n const char = String.fromCharCode(i)\n const isPre1 = isPrefixOf1 && i === first\n const isPre2 = isPrefixOf2 && i === last\n let evilPrefix = evilIdx\n while (evilPrefix && char !== evil[evilPrefix]) {\n evilPrefix = kmp[evilPrefix - 1]\n }\n if (char === evil[evilPrefix]) {\n evilPrefix += 1\n }\n total += cnt(sIdx + 1, evilPrefix, isPre1, isPre2)\n }\n return (cache[key] = total % mod)\n }\n return cnt(0, 0, true, true)\n}\n\nfunction buildKmpArray(str) {\n const result = new Array(str.length).fill(0)\n let j = 0\n for (let i = 1; i < str.length; i++) {\n while (j && str[j] !== str[i]) {\n j = result[j - 1]\n }\n if (str[i] === str[j]) {\n j += 1\n }\n result[i] = j\n }\n return result\n}" ]
1,399
count-largest-group
[ "Count the digit sum for each integer in the range and find out the largest groups." ]
/** * @param {number} n * @return {number} */ var countLargestGroup = function(n) { };
You are given an integer n. Each number from 1 to n is grouped according to the sum of its digits. Return the number of groups that have the largest size.   Example 1: Input: n = 13 Output: 4 Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13: [1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9]. There are 4 groups with largest size. Example 2: Input: n = 2 Output: 2 Explanation: There are 2 groups [1], [2] of size 1.   Constraints: 1 <= n <= 104
Easy
[ "hash-table", "math" ]
[ "const countLargestGroup = function(n) {\n const hash = {}\n const sum = n => `${n}`.split('').reduce((ac, e) => ac + (+e), 0)\n for(let i = 1; i <= n; i++) {\n const tmp = sum(i)\n if(hash[tmp] == null) hash[tmp] = 0\n hash[tmp]++\n }\n // console.log(hash)\n const val = Math.max(...Object.values(hash))\n let res = 0\n Object.keys(hash).forEach(k => {\n if(hash[k] === val) res++\n })\n \n return res\n};" ]
1,400
construct-k-palindrome-strings
[ "If the s.length < k we cannot construct k strings from s and answer is false.", "If the number of characters that have odd counts is > k then the minimum number of palindrome strings we can construct is > k and answer is false.", "Otherwise you can construct exactly k palindrome strings and answer is true (why ?)." ]
/** * @param {string} s * @param {number} k * @return {boolean} */ var canConstruct = function(s, k) { };
Given a string s and an integer k, return true if you can use all the characters in s to construct k palindrome strings or false otherwise.   Example 1: Input: s = "annabelle", k = 2 Output: true Explanation: You can construct two palindromes using all characters in s. Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b" Example 2: Input: s = "leetcode", k = 3 Output: false Explanation: It is impossible to construct 3 palindromes using all the characters of s. Example 3: Input: s = "true", k = 4 Output: true Explanation: The only possible solution is to put each character in a separate string.   Constraints: 1 <= s.length <= 105 s consists of lowercase English letters. 1 <= k <= 105
Medium
[ "hash-table", "string", "greedy", "counting" ]
null
[]
1,401
circle-and-rectangle-overlapping
[ "Locate the closest point of the square to the circle, you can then find the distance from this point to the center of the circle and check if this is less than or equal to the radius." ]
/** * @param {number} radius * @param {number} xCenter * @param {number} yCenter * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @return {boolean} */ var checkOverlap = function(radius, xCenter, yCenter, x1, y1, x2, y2) { };
You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time.   Example 1: Input: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1 Output: true Explanation: Circle and rectangle share the point (1,0). Example 2: Input: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1 Output: false Example 3: Input: radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1 Output: true   Constraints: 1 <= radius <= 2000 -104 <= xCenter, yCenter <= 104 -104 <= x1 < x2 <= 104 -104 <= y1 < y2 <= 104
Medium
[ "math", "geometry" ]
null
[]
1,402
reducing-dishes
[ "Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum.", "If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Otherwise, keep the previous best like-time coefficient." ]
/** * @param {number[]} satisfaction * @return {number} */ var maxSatisfaction = function(satisfaction) { };
A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time. Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i]. Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation. Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.   Example 1: Input: satisfaction = [-1,-8,0,5,-9] Output: 14 Explanation: After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14). Each dish is prepared in one unit of time. Example 2: Input: satisfaction = [4,3,2] Output: 20 Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20) Example 3: Input: satisfaction = [-1,-4,-5] Output: 0 Explanation: People do not like the dishes. No dish is prepared.   Constraints: n == satisfaction.length 1 <= n <= 500 -1000 <= satisfaction[i] <= 1000
Hard
[ "array", "dynamic-programming", "greedy", "sorting" ]
[ "const maxSatisfaction = function (satisfaction, max = 0) {\n satisfaction.sort((a, b) => a - b)\n let res = 0\n let total = 0\n let len = satisfaction.length\n // \"We'll keep doing this as long as satisfaction[i] + total > 0\" === satisfaction[i] > -total\n // It is because the current running sum needs to be greater than 0 otherwise, it would decrease res.\n for (let i = len - 1; i >= 0 && satisfaction[i] > -total; i--) {\n total += satisfaction[i]\n res += total\n }\n return res\n}" ]
1,403
minimum-subsequence-in-non-increasing-order
[ "Sort elements and take each element from the largest until accomplish the conditions." ]
/** * @param {number[]} nums * @return {number[]} */ var minSubsequence = function(nums) { };
Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence.  If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array.  Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order.   Example 1: Input: nums = [4,3,10,9,8] Output: [10,9] Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements.  Example 2: Input: nums = [4,4,7,6,7] Output: [7,7,6] Explanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-decreasing order.   Constraints: 1 <= nums.length <= 500 1 <= nums[i] <= 100
Easy
[ "array", "greedy", "sorting" ]
null
[]
1,404
number-of-steps-to-reduce-a-number-in-binary-representation-to-one
[ "Read the string from right to left, if the string ends in '0' then the number is even otherwise it is odd.", "Simulate the steps described in the binary string." ]
/** * @param {string} s * @return {number} */ var numSteps = function(s) { };
Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules: If the current number is even, you have to divide it by 2. If the current number is odd, you have to add 1 to it. It is guaranteed that you can always reach one for all test cases.   Example 1: Input: s = "1101" Output: 6 Explanation: "1101" corressponds to number 13 in their decimal representation. Step 1) 13 is odd, add 1 and obtain 14.  Step 2) 14 is even, divide by 2 and obtain 7. Step 3) 7 is odd, add 1 and obtain 8. Step 4) 8 is even, divide by 2 and obtain 4.  Step 5) 4 is even, divide by 2 and obtain 2.  Step 6) 2 is even, divide by 2 and obtain 1.  Example 2: Input: s = "10" Output: 1 Explanation: "10" corressponds to number 2 in their decimal representation. Step 1) 2 is even, divide by 2 and obtain 1.  Example 3: Input: s = "1" Output: 0   Constraints: 1 <= s.length <= 500 s consists of characters '0' or '1' s[0] == '1'
Medium
[ "string", "bit-manipulation" ]
[ "const numSteps = function(s) {\n let res = 0\n let carry = 0\n for(let i = s.length - 1; i > 0; i--) {\n res++\n if(s[i] === '1' && carry === 0) {\n res++\n carry = 1\n }else if(s[i] === '0' && carry === 1) {\n res++\n carry = 1\n }\n }\n return res + carry\n};" ]
1,405
longest-happy-string
[ "Use a greedy approach.", "Use the letter with the maximum current limit that can be added without breaking the condition." ]
/** * @param {number} a * @param {number} b * @param {number} c * @return {string} */ var longestDiverseString = function(a, b, c) { };
A string s is called happy if it satisfies the following conditions: s only contains the letters 'a', 'b', and 'c'. s does not contain any of "aaa", "bbb", or "ccc" as a substring. s contains at most a occurrences of the letter 'a'. s contains at most b occurrences of the letter 'b'. s contains at most c occurrences of the letter 'c'. Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "". A substring is a contiguous sequence of characters within a string.   Example 1: Input: a = 1, b = 1, c = 7 Output: "ccaccbcc" Explanation: "ccbccacc" would also be a correct answer. Example 2: Input: a = 7, b = 1, c = 0 Output: "aabaa" Explanation: It is the only correct answer in this case.   Constraints: 0 <= a, b, c <= 100 a + b + c > 0
Medium
[ "string", "greedy", "heap-priority-queue" ]
[ "const longestDiverseString = function (a, b, c) {\n const arr = [['a', a], ['b', b], ['c', c]]\n \n let res = ''\n while(true) {\n arr.sort((a, b) => b[1] - a[1])\n if(res.length >= 2 && arr[0][0] === res[res.length - 1] && arr[0][0] === res[res.length - 2]) {\n if(arr[1][1] > 0) {\n res += arr[1][0]\n arr[1][1]--\n } else break\n } else {\n if(arr[0][1] > 0) {\n res += arr[0][0]\n arr[0][1]--\n } else break\n }\n }\n \n return res\n};", "const longestDiverseString = function (a, b, c) {\n return generate(a, b, c, \"a\", \"b\", \"c\");\n};\n\nfunction generate(a, b, c, ac, bc, cc) {\n if (a < b) return generate(b, a, c, bc, ac, cc);\n if (b < c) return generate(a, c, b, ac, cc, bc);\n if (b === 0) return ac.repeat(Math.min(2, a));\n let use_a = Math.min(2, a),\n use_b = a - use_a >= b ? 1 : 0;\n return (\n ac.repeat(use_a) +\n bc.repeat(use_b) +\n generate(a - use_a, b - use_b, c, ac, bc, cc)\n );\n}", "const longestDiverseString = function (a, b, c) {\n const n = a + b + c\n let res = ''\n let A = 0, B = 0, C = 0\n for(let i = 0; i < n; i++) {\n if((a >= c && a >= b && A !== 2) || (B === 2 && a > 0) || (C === 2 && a > 0)) {\n A++\n res += 'a'\n a--\n B = 0\n C = 0\n } else if((b >= c && b >= a && B !== 2) || (A === 2 && b > 0) || (C === 2 && b)) {\n B++\n res += 'b'\n b--\n A = 0\n C = 0\n } else if((c >= a && c >= b && C !== 2) || (A === 2 && c) || (B === 2 && c)) {\n C++\n res += 'c'\n c--\n A = 0\n B = 0\n }\n }\n \n return res\n};" ]
1,406
stone-game-iii
[ "The game can be mapped to minmax game. Alice tries to maximize the total score and Bob tries to minimize it.", "Use dynamic programming to simulate the game. If the total score was 0 the game is \"Tie\", and if it has positive value then \"Alice\" wins, otherwise \"Bob\" wins." ]
/** * @param {number[]} stoneValue * @return {string} */ var stoneGameIII = function(stoneValue) { };
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row. The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win, or "Tie" if they will end the game with the same score.   Example 1: Input: stoneValue = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: stoneValue = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: stoneValue = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.   Constraints: 1 <= stoneValue.length <= 5 * 104 -1000 <= stoneValue[i] <= 1000
Hard
[ "array", "math", "dynamic-programming", "game-theory" ]
[ "const stoneGameIII = function (stoneValue) {\n const n = stoneValue.length\n const suffixSum = new Array(n + 1)\n const dp = new Array(n + 1)\n suffixSum[n] = 0\n dp[n] = 0\n for (let i = n - 1; i >= 0; i--)\n suffixSum[i] = suffixSum[i + 1] + stoneValue[i]\n for (let i = n - 1; i >= 0; i--) {\n dp[i] = stoneValue[i] + suffixSum[i + 1] - dp[i + 1]\n for (let k = i + 1; k < i + 3 && k < n; k++) {\n dp[i] = Math.max(dp[i], suffixSum[i] - dp[k + 1])\n }\n }\n if (dp[0] * 2 === suffixSum[0]) return 'Tie'\n else if (dp[0] * 2 > suffixSum[0]) return 'Alice'\n else return 'Bob'\n}", "const stoneGameIII = function (stoneValue) {\n const n = stoneValue.length,\n dp = new Array(4).fill(0)\n for (let i = n - 1; i >= 0; --i) {\n dp[i % 4] = -Infinity\n for (let k = 0, take = 0; k < 3 && i + k < n; ++k) {\n take += stoneValue[i + k]\n dp[i % 4] = Math.max(dp[i % 4], take - dp[(i + k + 1) % 4])\n }\n }\n if (dp[0] > 0) return 'Alice'\n if (dp[0] < 0) return 'Bob'\n return 'Tie'\n}" ]
1,408
string-matching-in-an-array
[ "Bruteforce to find if one string is substring of another or use KMP algorithm." ]
/** * @param {string[]} words * @return {string[]} */ var stringMatching = function(words) { };
Given an array of string words, return all strings in words that is a substring of another word. You can return the answer in any order. A substring is a contiguous sequence of characters within a string   Example 1: Input: words = ["mass","as","hero","superhero"] Output: ["as","hero"] Explanation: "as" is substring of "mass" and "hero" is substring of "superhero". ["hero","as"] is also a valid answer. Example 2: Input: words = ["leetcode","et","code"] Output: ["et","code"] Explanation: "et", "code" are substring of "leetcode". Example 3: Input: words = ["blue","green","bu"] Output: [] Explanation: No string of words is substring of another string.   Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 30 words[i] contains only lowercase English letters. All the strings of words are unique.
Easy
[ "array", "string", "string-matching" ]
[ "const stringMatching = function(words) {\n const res = [], n = words.length\n for(let i = 0; i < n; i++) {\n const cur = words[i]\n for(let j = 0; j < n; j++) {\n if(i !== j && words[j].indexOf(cur) !== -1) {\n res.push(cur); \n break\n }\n }\n }\n return res\n};" ]
1,409
queries-on-a-permutation-with-key
[ "Create the permutation P=[1,2,...,m], it could be a list for example.", "For each i, find the position of queries[i] with a simple scan over P and then move this to the beginning." ]
/** * @param {number[]} queries * @param {number} m * @return {number[]} */ var processQueries = function(queries, m) { };
Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules: In the beginning, you have the permutation P=[1,2,3,...,m]. For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i]. Return an array containing the result for the given queries.   Example 1: Input: queries = [3,1,2,1], m = 5 Output: [2,1,2,1] Explanation: The queries are processed as follow: For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. Therefore, the array containing the result is [2,1,2,1]. Example 2: Input: queries = [4,1,2,2], m = 4 Output: [3,1,2,0] Example 3: Input: queries = [7,5,5,8,3], m = 8 Output: [6,5,0,7,5]   Constraints: 1 <= m <= 10^3 1 <= queries.length <= m 1 <= queries[i] <= m
Medium
[ "array", "binary-indexed-tree", "simulation" ]
[ "var processQueries = function(queries, m) {\n const nums = Array.from({ length: m }, (_, i) => i + 1)\n const res = []\n for(const q of queries) {\n const idx = nums.indexOf(q)\n nums.splice(idx, 1)\n nums.unshift(q)\n res.push(idx)\n }\n return res\n};" ]
1,410
html-entity-parser
[ "Search the string for all the occurrences of the character '&'.", "For every '&' check if it matches an HTML entity by checking the ';' character and if entity found replace it in the answer." ]
/** * @param {string} text * @return {string} */ var entityParser = function(text) { };
HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. The special characters and their entities for HTML are: Quotation Mark: the entity is &quot; and symbol character is ". Single Quote Mark: the entity is &apos; and symbol character is '. Ampersand: the entity is &amp; and symbol character is &. Greater Than Sign: the entity is &gt; and symbol character is >. Less Than Sign: the entity is &lt; and symbol character is <. Slash: the entity is &frasl; and symbol character is /. Given the input text string to the HTML parser, you have to implement the entity parser. Return the text after replacing the entities by the special characters.   Example 1: Input: text = "&amp; is an HTML entity but &ambassador; is not." Output: "& is an HTML entity but &ambassador; is not." Explanation: The parser will replace the &amp; entity by & Example 2: Input: text = "and I quote: &quot;...&quot;" Output: "and I quote: \"...\""   Constraints: 1 <= text.length <= 105 The string may contain any possible characters out of all the 256 ASCII characters.
Medium
[ "hash-table", "string" ]
[ "const entityParser = function(text) {\n const q = /&quot;/g\n const s = /&apos;/g\n const a = /&amp;/g\n const g = /&gt;/g\n const l = /&lt;/g\n const sl = /&frasl;/g\n let t = text.replace(q, '\"')\n t = t.replace(q, '\"')\n t = t.replace(s, \"'\")\n t = t.replace(g, '>')\n t = t.replace(l, '<')\n t = t.replace(sl, '/')\n t = t.replace(a, '&')\n return t\n};" ]
1,411
number-of-ways-to-paint-n-3-grid
[ "We will use Dynamic programming approach. we will try all possible configuration.", "Let dp[idx][prev1col][prev2col][prev3col] be the number of ways to color the rows of the grid from idx to n-1 keeping in mind that the previous row (idx - 1) has colors prev1col, prev2col and prev3col. Build the dp array to get the answer." ]
/** * @param {number} n * @return {number} */ var numOfWays = function(n) { };
You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color). Given n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 109 + 7.   Example 1: Input: n = 1 Output: 12 Explanation: There are 12 possible way to paint the grid as shown. Example 2: Input: n = 5000 Output: 30228214   Constraints: n == grid.length 1 <= n <= 5000
Hard
[ "dynamic-programming" ]
[ "const numOfWays = function(n) {\n const mod = 1e9 + 7\n let colors3 = 6, colors2 = 6\n \n for(let i = 1; i < n; i++) {\n const colors3Tmp = colors3\n colors3 = (2 * colors3 + 2 * colors2) % mod\n colors2 = (2 * colors3Tmp + 3 * colors2) % mod\n }\n \n \n return (colors2 + colors3) % mod\n};", "const numOfWays = function (n) {\n let a121 = 6,\n a123 = 6,\n b121,\n b123,\n mod = 1e9 + 7\n for (let i = 1; i < n; ++i) {\n b121 = a121 * 3 + a123 * 2\n b123 = a121 * 2 + a123 * 2\n a121 = b121 % mod\n a123 = b123 % mod\n }\n return (a121 + a123) % mod\n}" ]
1,413
minimum-value-to-get-positive-step-by-step-sum
[ "Find the minimum prefix sum." ]
/** * @param {number[]} nums * @return {number} */ var minStartValue = function(nums) { };
Given an array of integers nums, you start with an initial positive value startValue. In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that the step by step sum is never less than 1.   Example 1: Input: nums = [-3,2,-3,4,2] Output: 5 Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1. step by step sum startValue = 4 | startValue = 5 | nums (4 -3 ) = 1 | (5 -3 ) = 2 | -3 (1 +2 ) = 3 | (2 +2 ) = 4 | 2 (3 -3 ) = 0 | (4 -3 ) = 1 | -3 (0 +4 ) = 4 | (1 +4 ) = 5 | 4 (4 +2 ) = 6 | (5 +2 ) = 7 | 2 Example 2: Input: nums = [1,2] Output: 1 Explanation: Minimum start value should be positive. Example 3: Input: nums = [1,-2,-3] Output: 5   Constraints: 1 <= nums.length <= 100 -100 <= nums[i] <= 100
Easy
[ "array", "prefix-sum" ]
[ "const minStartValue = function(nums) {\n let sum = 0, min = Infinity\n for(let e of nums) {\n sum += e\n min = Math.min(min, sum)\n }\n \n return min >= 0 ? 1 : -min + 1\n};" ]
1,414
find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k
[ "Generate all Fibonacci numbers up to the limit (they are few).", "Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process." ]
/** * @param {number} k * @return {number} */ var findMinFibonacciNumbers = function(k) { };
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as: F1 = 1 F2 = 1 Fn = Fn-1 + Fn-2 for n > 2. It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.   Example 1: Input: k = 7 Output: 2 Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... For k = 7 we can use 2 + 5 = 7. Example 2: Input: k = 10 Output: 2 Explanation: For k = 10 we can use 2 + 8 = 10. Example 3: Input: k = 19 Output: 3 Explanation: For k = 19 we can use 1 + 5 + 13 = 19.   Constraints: 1 <= k <= 109
Medium
[ "math", "greedy" ]
null
[]
1,415
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n
[ "Generate recursively all the happy strings of length n.", "Sort them in lexicographical order and return the kth string if it exists." ]
/** * @param {number} n * @param {number} k * @return {string} */ var getHappyString = function(n, k) { };
A happy string is a string that: consists only of letters of the set ['a', 'b', 'c']. s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed). For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings. Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order. Return the kth string of this list or return an empty string if there are less than k happy strings of length n.   Example 1: Input: n = 1, k = 3 Output: "c" Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c". Example 2: Input: n = 1, k = 4 Output: "" Explanation: There are only 3 happy strings of length 1. Example 3: Input: n = 3, k = 9 Output: "cab" Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9th string = "cab"   Constraints: 1 <= n <= 10 1 <= k <= 100
Medium
[ "string", "backtracking" ]
[ "const getHappyString = function(n, k) {\n const hash = {a: 'bc', b: 'ac', c: 'ab'}\n const q = ['a', 'b', 'c']\n while(q[0].length !== n) {\n const e = q.shift()\n const last = e.charAt(e.length - 1)\n for(const ch of hash[last]) {\n q.push(e + ch)\n }\n }\n if(q.length >= k && q[k - 1].length === n) {\n return q[k - 1]\n }\n \n return ''\n};", "const getHappyString = function(n, k) {\n const hash = {a: 'bc', b: 'ac', c: 'ab'}\n const q = ['a', 'b', 'c']\n while(q[0].length !== n) {\n const pre = q.shift()\n for(const ch of hash[pre[pre.length - 1]]) {\n q.push(pre + ch)\n }\n }\n \n return q.length >= k ? q[k - 1] : ''\n};", "var getHappyString = function(n, k) {\n const res = []\n dfs()\n return res.length === k ? res[res.length - 1] : ''\n function dfs(path = '') {\n if(res.length === k) return\n if(path.length === n) {\n res.push(path)\n return\n }\n for(const e of 'abc') {\n if(path === '' || e !== path[path.length - 1]) {\n dfs(path + e)\n }\n }\n }\n};" ]
1,416
restore-the-array
[ "Use dynamic programming. Build an array dp where dp[i] is the number of ways you can divide the string starting from index i to the end.", "Keep in mind that the answer is modulo 10^9 + 7 and take the mod for each operation." ]
/** * @param {string} s * @param {number} k * @return {number} */ var numberOfArrays = function(s, k) { };
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array. Given the string s and the integer k, return the number of the possible arrays that can be printed as s using the mentioned program. Since the answer may be very large, return it modulo 109 + 7.   Example 1: Input: s = "1000", k = 10000 Output: 1 Explanation: The only possible array is [1000] Example 2: Input: s = "1000", k = 10 Output: 0 Explanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10. Example 3: Input: s = "1317", k = 2000 Output: 8 Explanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]   Constraints: 1 <= s.length <= 105 s consists of only digits and does not contain leading zeros. 1 <= k <= 109
Hard
[ "string", "dynamic-programming" ]
[ "const numberOfArrays = function (s, k) {\n const n = s.length\n // dp[i] is number of ways to print valid arrays from string s start at i\n const dp = Array(n)\n return dfs(s, k, 0, dp)\n}\n\nfunction dfs(s, k, i, dp) {\n const mod = 10 ** 9 + 7\n // base case -> Found a valid way\n if (i === s.length) return 1\n // all numbers are in range [1, k] and there are no leading zeros\n // So numbers starting with 0 mean invalid!\n if (s.charAt(i) === '0') return 0\n if (dp[i] != null) return dp[i]\n let ans = 0\n let num = 0\n for (let j = i; j < s.length; j++) {\n // num is the value of the substring s[i..j]\n num = num * 10 + (+s.charAt(j))\n // num must be in range [1, k]\n if (num > k) break\n ans += dfs(s, k, j + 1, dp)\n ans %= mod\n }\n return (dp[i] = ans)\n}", "const numberOfArrays = function (s, k) {\n const mod = 10 ** 9 + 7\n const n = s.length\n const dp = new Array(n + 1).fill(0)\n dp[n] = 1\n for (let i = n - 1; i >= 0; i--) {\n if (s[i] === '0') continue\n else {\n let temp = s[i]\n for (let j = i + 1; j <= n; j++) {\n if (temp > k) break\n dp[i] = (dp[i] + dp[j]) % mod\n if (j < n) {\n temp = temp * 10 + parseInt(s[j])\n }\n }\n }\n }\n return parseInt(dp[0])\n}" ]
1,417
reformat-the-string
[ "Count the number of letters and digits in the string. if cntLetters - cntDigits has any of the values [-1, 0, 1] we have an answer, otherwise we don't have any answer.", "Build the string anyway as you wish. Keep in mind that you need to start with the type that have more characters if cntLetters ≠ cntDigits." ]
/** * @param {string} s * @return {string} */ var reformat = function(s) { };
You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the string.   Example 1: Input: s = "a0b1c2" Output: "0a1b2c" Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations. Example 2: Input: s = "leetcode" Output: "" Explanation: "leetcode" has only characters so we cannot separate them by digits. Example 3: Input: s = "1229857369" Output: "" Explanation: "1229857369" has only digits so we cannot separate them by characters.   Constraints: 1 <= s.length <= 500 s consists of only lowercase English letters and/or digits.
Easy
[ "string" ]
[ "var reformat = function(s) {\n let str = '', num = ''\n const isDigit = ch => ch >= '0' && ch <= '9'\n for(const ch of s) {\n if(isDigit(ch)) num += ch\n else str += ch\n }\n if(Math.abs(str.length - num.length) > 1) return ''\n if(str.length > num.length) {\n let res = ''\n for (let i = 0; i < str.length; i++) {\n res += str[i]\n if(i < num.length) res += num[i]\n }\n return res\n } else {\n let res = ''\n for (let i = 0; i < num.length; i++) {\n res += num[i]\n if(i < str.length) res += str[i]\n }\n return res\n }\n};" ]
1,418
display-table-of-food-orders-in-a-restaurant
[ "Keep the frequency of all pairs (tableNumber, foodItem) using a hashmap.", "Sort rows by tableNumber and columns by foodItem, then process the resulted table." ]
/** * @param {string[][]} orders * @return {string[][]} */ var displayTable = function(orders) { };
Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders. Return the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.   Example 1: Input: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]] Output: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] Explanation: The displaying table looks like: Table,Beef Burrito,Ceviche,Fried Chicken,Water 3 ,0 ,2 ,1 ,0 5 ,0 ,1 ,0 ,1 10 ,1 ,0 ,0 ,0 For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche". For the table 5: Carla orders "Water" and "Ceviche". For the table 10: Corina orders "Beef Burrito". Example 2: Input: orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]] Output: [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]] Explanation: For the table 1: Adam and Brianna order "Canadian Waffles". For the table 12: James, Ratesh and Amadeus order "Fried Chicken". Example 3: Input: orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]] Output: [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]   Constraints: 1 <= orders.length <= 5 * 10^4 orders[i].length == 3 1 <= customerNamei.length, foodItemi.length <= 20 customerNamei and foodItemi consist of lowercase and uppercase English letters and the space character. tableNumberi is a valid integer between 1 and 500.
Medium
[ "array", "hash-table", "string", "sorting", "ordered-set" ]
null
[]
1,419
minimum-number-of-frogs-croaking
[ "keep the frequency of all characters from \"croak\" using a hashmap.", "For each character in the given string, greedily match it to a possible \"croak\"." ]
/** * @param {string} croakOfFrogs * @return {number} */ var minNumberOfFrogs = function(croakOfFrogs) { };
You are given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak" are mixed. Return the minimum number of different frogs to finish all the croaks in the given string. A valid "croak" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid "croak" return -1.   Example 1: Input: croakOfFrogs = "croakcroak" Output: 1 Explanation: One frog yelling "croak" twice. Example 2: Input: croakOfFrogs = "crcoakroak" Output: 2 Explanation: The minimum number of frogs is two. The first frog could yell "crcoakroak". The second frog could yell later "crcoakroak". Example 3: Input: croakOfFrogs = "croakcrook" Output: -1 Explanation: The given string is an invalid combination of "croak" from different frogs.   Constraints: 1 <= croakOfFrogs.length <= 105 croakOfFrogs is either 'c', 'r', 'o', 'a', or 'k'.
Medium
[ "string", "counting" ]
null
[]
1,420
build-array-where-you-can-find-the-maximum-exactly-k-comparisons
[ "Use dynamic programming approach. Build dp table where dp[a][b][c] is the number of ways you can start building the array starting from index a where the search_cost = c and the maximum used integer was b.", "Recursively, solve the small sub-problems first. Optimize your answer by stopping the search if you exceeded k changes." ]
/** * @param {number} n * @param {number} m * @param {number} k * @return {number} */ var numOfArrays = function(n, m, k) { };
You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties: arr has exactly n integers. 1 <= arr[i] <= m where (0 <= i < n). After applying the mentioned algorithm to arr, the value search_cost is equal to k. Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7.   Example 1: Input: n = 2, m = 3, k = 1 Output: 6 Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3] Example 2: Input: n = 5, m = 2, k = 3 Output: 0 Explanation: There are no possible arrays that satisify the mentioned conditions. Example 3: Input: n = 9, m = 1, k = 1 Output: 1 Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]   Constraints: 1 <= n <= 50 1 <= m <= 100 0 <= k <= n
Hard
[ "dynamic-programming", "prefix-sum" ]
null
[]
1,422
maximum-score-after-splitting-a-string
[ "Precompute a prefix sum of ones ('1').", "Iterate from left to right counting the number of zeros ('0'), then use the precomputed prefix sum for counting ones ('1'). Update the answer." ]
/** * @param {string} s * @return {number} */ var maxScore = function(s) { };
Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring). The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.   Example 1: Input: s = "011101" Output: 5 Explanation: All possible ways of splitting s into two non-empty substrings are: left = "0" and right = "11101", score = 1 + 4 = 5 left = "01" and right = "1101", score = 1 + 3 = 4 left = "011" and right = "101", score = 1 + 2 = 3 left = "0111" and right = "01", score = 1 + 1 = 2 left = "01110" and right = "1", score = 2 + 1 = 3 Example 2: Input: s = "00111" Output: 5 Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5 Example 3: Input: s = "1111" Output: 3   Constraints: 2 <= s.length <= 500 The string s consists of characters '0' and '1' only.
Easy
[ "string" ]
[ "const maxScore = function(s) {\n const n = s.length\n let res = 0, numOfOne = 0\n for(let ch of s) {\n if(ch === '1') numOfOne++\n }\n for(let i = 0, one = 0; i < n - 1; i++) {\n if(s[i] === '1') one++\n res = Math.max(res, (i + 1 - one) + (numOfOne - one))\n }\n\n return res\n};", "const maxScore = function(s) {\n const n = s.length\n let res = -Infinity, one = 0, zero = 0\n for(let i = 0; i < n; i++) {\n s[i] === '0' ? zero++ : one++\n if(i !== n - 1) res = Math.max(res, zero - one)\n }\n\n return res + one\n};" ]
1,423
maximum-points-you-can-obtain-from-cards
[ "Let the sum of all points be total_pts. You need to remove a sub-array from cardPoints with length n - k.", "Keep a window of size n - k over the array. The answer is max(answer, total_pts - sumOfCurrentWindow)" ]
/** * @param {number[]} cardPoints * @param {number} k * @return {number} */ var maxScore = function(cardPoints, k) { };
There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards. Your score is the sum of the points of the cards you have taken. Given the integer array cardPoints and the integer k, return the maximum score you can obtain.   Example 1: Input: cardPoints = [1,2,3,4,5,6,1], k = 3 Output: 12 Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12. Example 2: Input: cardPoints = [2,2,2], k = 2 Output: 4 Explanation: Regardless of which two cards you take, your score will always be 4. Example 3: Input: cardPoints = [9,7,7,9,7,7,9], k = 7 Output: 55 Explanation: You have to take all the cards. Your score is the sum of points of all cards.   Constraints: 1 <= cardPoints.length <= 105 1 <= cardPoints[i] <= 104 1 <= k <= cardPoints.length
Medium
[ "array", "sliding-window", "prefix-sum" ]
null
[]
1,424
diagonal-traverse-ii
[ "Notice that numbers with equal sums of row and column indexes belong to the same diagonal.", "Store them in tuples (sum, row, val), sort them, and then regroup the answer." ]
/** * @param {number[][]} nums * @return {number[]} */ var findDiagonalOrder = function(nums) { };
Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.   Example 1: Input: nums = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,4,2,7,5,3,8,6,9] Example 2: Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]   Constraints: 1 <= nums.length <= 105 1 <= nums[i].length <= 105 1 <= sum(nums[i].length) <= 105 1 <= nums[i][j] <= 105
Medium
[ "array", "sorting", "heap-priority-queue" ]
[ "const findDiagonalOrder = function(nums) {\n const m = nums.length\n const map = new Map()\n let maxKey = 0\n for(let i = 0; i < m; i++) {\n for(let j = 0, n = nums[i].length; j < n; j++) {\n if(!map.has(i + j)) map.set(i + j, [])\n map.get(i + j).push(nums[i][j])\n maxKey = Math.max(maxKey, i + j)\n }\n }\n // console.log(map)\n const res = []\n for(let i = 0; i <= maxKey; i++) {\n if(map.has(i)) {\n const tmp = map.get(i)\n tmp.reverse()\n res.push(...tmp)\n }\n }\n \n return res\n};" ]
1,425
constrained-subsequence-sum
[ "Use dynamic programming.", "Let dp[i] be the solution for the prefix of the array that ends at index i, if the element at index i is in the subsequence.", "dp[i] = nums[i] + max(0, dp[i-k], dp[i-k+1], ..., dp[i-1])", "Use a heap with the sliding window technique to optimize the dp." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var constrainedSubsetSum = function(nums, k) { };
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied. A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.   Example 1: Input: nums = [10,2,-10,5,20], k = 2 Output: 37 Explanation: The subsequence is [10, 2, 5, 20]. Example 2: Input: nums = [-1,-2,-3], k = 1 Output: -1 Explanation: The subsequence must be non-empty, so we choose the largest number. Example 3: Input: nums = [10,-2,-10,-5,20], k = 2 Output: 23 Explanation: The subsequence is [10, -2, -5, 20].   Constraints: 1 <= k <= nums.length <= 105 -104 <= nums[i] <= 104
Hard
[ "array", "dynamic-programming", "queue", "sliding-window", "heap-priority-queue", "monotonic-queue" ]
[ "const constrainedSubsetSum = function(nums, k) {\n const window = [[0,nums[0]]];\n let max = nums[0];\n for(let i=1; i<nums.length; i++){\n let [index,lastKsum] = window[0];\n if(index == i-k){\n window.shift();\n }\n let sum = Math.max(lastKsum, 0) + nums[i]\n max = Math.max(max, sum);\n while(window.length>0 && window[window.length-1][1] < sum){\n window.pop();\n }\n window.push([i,sum]);\n }\n return max;\n};", "const constrainedSubsetSum = function (nums, k) {\n const dll = new DLL()\n dll.push([0, nums[0]])\n let max = nums[0]\n for (let i = 1; i < nums.length; i++) {\n if (!dll.isEmpty() && i - dll.peek().val[0] > k) {\n dll.shift()\n }\n const sum = Math.max(dll.peek().val[1], 0) + nums[i]\n max = Math.max(max, sum)\n while (!dll.isEmpty() && dll.peekLast().val[1] < sum) {\n dll.pop()\n }\n dll.push([i, sum])\n }\n return max\n}\n\nclass Node {\n constructor(val) {\n this.val = val\n this.prev = null\n this.next = null\n }\n}\nclass DLL {\n constructor() {\n this.head = new Node()\n this.tail = null\n this.size = 0\n }\n peek() {\n return this.head.next\n }\n peekLast() {\n return this.tail\n }\n isEmpty() {\n return this.head.next == null\n }\n shift() {\n const h = this.head.next\n if (h) {\n this.head.next = h.next\n if (h.next) {\n h.next.prev = this.head\n } else {\n this.tail = null\n }\n this.size--\n }\n }\n pop() {\n if (this.tail == null) return\n const newTail = this.tail.prev\n if (newTail) {\n newTail.next = null\n this.tail.prev = null\n this.tail = newTail\n this.size--\n }\n\n }\n push(val) {\n const node = new Node(val)\n node.prev = this.tail ?? this.head\n node.prev.next = node\n this.tail = node\n this.size++\n }\n}" ]
1,431
kids-with-the-greatest-number-of-candies
[ "Use greedy approach. For each kid check if candies[i] + extraCandies ≥ maximum in Candies[i]." ]
/** * @param {number[]} candies * @param {number} extraCandies * @return {boolean[]} */ var kidsWithCandies = function(candies, extraCandies) { };
There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have. Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise. Note that multiple kids can have the greatest number of candies.   Example 1: Input: candies = [2,3,5,1,3], extraCandies = 3 Output: [true,true,true,false,true] Explanation: If you give all extraCandies to: - Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids. - Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids. - Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids. - Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids. - Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids. Example 2: Input: candies = [4,2,1,1,2], extraCandies = 1 Output: [true,false,false,false,false] Explanation: There is only 1 extra candy. Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy. Example 3: Input: candies = [12,1,12], extraCandies = 10 Output: [true,false,true]   Constraints: n == candies.length 2 <= n <= 100 1 <= candies[i] <= 100 1 <= extraCandies <= 50
Easy
[ "array" ]
[ "const kidsWithCandies = function(candies, extraCandies) {\n const res = []\n let max = 0\n for(let e of candies) max = Math.max(e, max)\n max -= extraCandies\n for(let i = 0, len = candies.length; i < len; i++) {\n res.push(candies[i] >= max)\n }\n return res\n};" ]
1,432
max-difference-you-can-get-from-changing-an-integer
[ "We need to get the max and min value after changing num and the answer is max - min.", "Use brute force, try all possible changes and keep the minimum and maximum values." ]
/** * @param {number} num * @return {number} */ var maxDiff = function(num) { };
You are given an integer num. You will apply the following steps exactly two times: Pick a digit x (0 <= x <= 9). Pick another digit y (0 <= y <= 9). The digit y can be equal to x. Replace all the occurrences of x in the decimal representation of num by y. The new integer cannot have any leading zeros, also the new integer cannot be 0. Let a and b be the results of applying the operations to num the first and second times, respectively. Return the max difference between a and b.   Example 1: Input: num = 555 Output: 888 Explanation: The first time pick x = 5 and y = 9 and store the new integer in a. The second time pick x = 5 and y = 1 and store the new integer in b. We have now a = 999 and b = 111 and max difference = 888 Example 2: Input: num = 9 Output: 8 Explanation: The first time pick x = 9 and y = 9 and store the new integer in a. The second time pick x = 9 and y = 1 and store the new integer in b. We have now a = 9 and b = 1 and max difference = 8   Constraints: 1 <= num <= 108
Medium
[ "math", "greedy" ]
null
[]