Datasets:

QID
int64
1
2.85k
titleSlug
stringlengths
3
77
Hints
list
Code
stringlengths
80
1.34k
Body
stringlengths
190
4.55k
Difficulty
stringclasses
3 values
Topics
list
Definitions
stringclasses
14 values
Solutions
list
388
longest-absolute-file-path
[]
/** * @param {string} input * @return {number} */ var lengthLongestPath = function(input) { };
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1.ext and subdirectory subsubdir1. subdir2 contains a subdirectory subsubdir2, which contains a file file2.ext. In text form, it looks like this (with ⟶ representing the tab character): dir ⟶ subdir1 ⟶ ⟶ file1.ext ⟶ ⟶ subsubdir1 ⟶ subdir2 ⟶ ⟶ subsubdir2 ⟶ ⟶ ⟶ file2.ext If we were to write this representation in code, it will look like this: "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext". Note that the '\n' and '\t' are the new-line and tab characters. Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s. Using the above example, the absolute path to file2.ext is "dir/subdir2/subsubdir2/file2.ext". Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension, where name and extension consist of letters, digits, and/or spaces. Given a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0. Note that the testcases are generated such that the file system is valid and no file or directory name has length 0.   Example 1: Input: input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" Output: 20 Explanation: We have only one file, and the absolute path is "dir/subdir2/file.ext" of length 20. Example 2: Input: input = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" Output: 32 Explanation: We have two files: "dir/subdir1/file1.ext" of length 21 "dir/subdir2/subsubdir2/file2.ext" of length 32. We return 32 since it is the longest absolute path to a file. Example 3: Input: input = "a" Output: 0 Explanation: We do not have any files, just a single directory named "a".   Constraints: 1 <= input.length <= 104 input may contain lowercase or uppercase English letters, a new line character '\n', a tab character '\t', a dot '.', a space ' ', and digits. All file and directory names have positive length.
Medium
[ "string", "stack", "depth-first-search" ]
[ "const lengthLongestPath = function(input) {\n const stack = []\n return input.split('\\n').reduce((max, p) => {\n const level = p.lastIndexOf('\\t') + 1\n stack[level] = p.length - level + (level ? stack[level - 1] : 0)\n return p.indexOf('.') === -1 ? max : Math.max(max, stack[level] + level)\n }, 0)\n}" ]
389
find-the-difference
[]
/** * @param {string} s * @param {string} t * @return {character} */ var findTheDifference = function(s, t) { };
You are given two strings s and t. String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t.   Example 1: Input: s = "abcd", t = "abcde" Output: "e" Explanation: 'e' is the letter that was added. Example 2: Input: s = "", t = "y" Output: "y"   Constraints: 0 <= s.length <= 1000 t.length == s.length + 1 s and t consist of lowercase English letters.
Easy
[ "hash-table", "string", "bit-manipulation", "sorting" ]
[ "const findTheDifference = function(s, t) {\n let xor = 0\n for(let i = 0, len = s.length; i < len; i++) xor = xor ^ s.charCodeAt(i) ^ t.charCodeAt(i)\n xor = xor ^ t.charCodeAt(t.length - 1)\n return String.fromCharCode(xor)\n};", "const findTheDifference = function(s, t) {\n const arr = s.split(\"\");\n let idx;\n for (let i = 0; i < t.length; i++) {\n idx = arr.indexOf(t[i]);\n if (idx === -1) {\n return t[i];\n } else {\n arr.splice(idx, 1);\n }\n }\n};\n\nconsole.log(findTheDifference(\"abcd\", \"abcde\"));" ]
390
elimination-game
[]
/** * @param {number} n * @return {number} */ var lastRemaining = function(n) { };
You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr: Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers. Keep repeating the steps again, alternating left to right and right to left, until a single number remains. Given the integer n, return the last number that remains in arr.   Example 1: Input: n = 9 Output: 6 Explanation: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] arr = [2, 4, 6, 8] arr = [2, 6] arr = [6] Example 2: Input: n = 1 Output: 1   Constraints: 1 <= n <= 109
Medium
[ "math", "recursion" ]
[ "const lastRemaining = function(n) {\n let left = true\n let remaining = n\n let step = 1\n let head = 1\n while (remaining > 1) {\n if (left || remaining % 2 === 1) {\n head = head + step\n }\n remaining = remaining >> 1\n step = step * 2\n left = !left\n }\n return head\n}" ]
391
perfect-rectangle
[]
/** * @param {number[][]} rectangles * @return {boolean} */ var isRectangleCover = function(rectangles) { };
Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi). Return true if all the rectangles together form an exact cover of a rectangular region.   Example 1: Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]] Output: true Explanation: All 5 rectangles together form an exact cover of a rectangular region. Example 2: Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]] Output: false Explanation: Because there is a gap between the two rectangular regions. Example 3: Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]] Output: false Explanation: Because two of the rectangles overlap with each other.   Constraints: 1 <= rectangles.length <= 2 * 104 rectangles[i].length == 4 -105 <= xi, yi, ai, bi <= 105
Hard
[ "array", "line-sweep" ]
[ "const isRectangleCover = function(rectangles) {\n let tls = new Set()\n let trs = new Set()\n let bls = new Set()\n let brs = new Set()\n let corner = (x, y) => `${x} ${y}`\n for (let [l, b, r, t] of rectangles) {\n let tl = corner(t, l)\n let tr = corner(t, r)\n let bl = corner(b, l)\n let br = corner(b, r)\n if (tls.has(tl) || trs.has(tr) || bls.has(bl) || brs.has(br)) return false\n if (!bls.delete(tl) && !trs.delete(tl)) tls.add(tl)\n if (!brs.delete(tr) && !tls.delete(tr)) trs.add(tr)\n if (!brs.delete(bl) && !tls.delete(bl)) bls.add(bl)\n if (!bls.delete(br) && !trs.delete(br)) brs.add(br)\n }\n return tls.size === 1 && trs.size === 1 && bls.size === 1 && brs.size === 1\n}" ]
392
is-subsequence
[]
/** * @param {string} s * @param {string} t * @return {boolean} */ var isSubsequence = function(s, t) { };
Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).   Example 1: Input: s = "abc", t = "ahbgdc" Output: true Example 2: Input: s = "axc", t = "ahbgdc" Output: false   Constraints: 0 <= s.length <= 100 0 <= t.length <= 104 s and t consist only of lowercase English letters.   Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?
Easy
[ "two-pointers", "string", "dynamic-programming" ]
[ "const isSubsequence = function(s, t) {\n const sl = s.length\n const tl = t.length\n if(sl > tl) return false\n if(sl === 0) return true\n let si = 0\n for(let i = 0; i < tl && si < sl; i++) {\n if(s[si] === t[i]) si++\n }\n return si === sl\n};", "const isSubsequence = function(s, t) {\n let ti = 0\n let tmp = 0\n for (let i = 0; i < s.length; i++) {\n if ((tmp = chk(t, ti, s.charAt(i))) === -1) {\n return false\n } else {\n ti = tmp + 1\n }\n }\n\n return true\n}\n\nfunction chk(str, start, target) {\n let idx = start\n for (let i = start; i < str.length; i++) {\n if (str.charAt(i) === target) {\n return i\n }\n }\n return -1\n}" ]
393
utf-8-validation
[ "Read the data integer by integer. When you read it, process the least significant 8 bits of it.", "Assume the next encoding is 1-byte data. If it is not 1-byte data, read the next integer and assume it is 2-bytes data.", "Similarly, if it is not 2-bytes data, try 3-bytes then 4-bytes. If you read four integers and it still does not match any pattern, return false." ]
/** * @param {number[]} data * @return {boolean} */ var validUtf8 = function(data) { };
Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters). A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: For a 1-byte character, the first bit is a 0, followed by its Unicode code. For an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, followed by n - 1 bytes with the most significant 2 bits being 10. This is how the UTF-8 encoding would work: Number of Bytes | UTF-8 Octet Sequence | (binary) --------------------+----------------------------------------- 1 | 0xxxxxxx 2 | 110xxxxx 10xxxxxx 3 | 1110xxxx 10xxxxxx 10xxxxxx 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx x denotes a bit in the binary form of a byte that may be either 0 or 1. Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.   Example 1: Input: data = [197,130,1] Output: true Explanation: data represents the octet sequence: 11000101 10000010 00000001. It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. Example 2: Input: data = [235,140,4] Output: false Explanation: data represented the octet sequence: 11101011 10001100 00000100. The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. The next byte is a continuation byte which starts with 10 and that's correct. But the second continuation byte does not start with 10, so it is invalid.   Constraints: 1 <= data.length <= 2 * 104 0 <= data[i] <= 255
Medium
[ "array", "bit-manipulation" ]
[ "const validUtf8 = function(data) {\n let count = 0\n for (let c of data) {\n if (count === 0) {\n if (c >> 5 === 0b110) count = 1\n else if (c >> 4 === 0b1110) count = 2\n else if (c >> 3 === 0b11110) count = 3\n else if (c >> 7) return false\n } else {\n if (c >> 6 !== 0b10) return false\n count--\n }\n }\n return count == 0\n}" ]
394
decode-string
[]
/** * @param {string} s * @return {string} */ var decodeString = function(s) { };
Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4]. The test cases are generated so that the length of the output will never exceed 105.   Example 1: Input: s = "3[a]2[bc]" Output: "aaabcbc" Example 2: Input: s = "3[a2[c]]" Output: "accaccacc" Example 3: Input: s = "2[abc]3[cd]ef" Output: "abcabccdcdcdef"   Constraints: 1 <= s.length <= 30 s consists of lowercase English letters, digits, and square brackets '[]'. s is guaranteed to be a valid input. All the integers in s are in the range [1, 300].
Medium
[ "string", "stack", "recursion" ]
[ "const decodeString = function(s) {\n const repeated = [];\n const sbStack = [];\n\n let mul = 0;\n let sb = \"\";\n for (let i = 0; i < s.length; i++) {\n const c = s.charAt(i);\n if (isDigit(c)) {\n if (mul === 0) sbStack.push(sb); // here is the trick\n mul = mul * 10 + +c;\n } else if (c === \"[\") {\n repeated.push(mul);\n mul = 0;\n sb = \"\";\n } else if (isLetter(c)) {\n sb += c;\n } else if (c === \"]\") {\n let top = sbStack.pop();\n let r = repeated.pop();\n while (r-- > 0) top += sb;\n sb = top;\n }\n }\n\n return sb;\n};\n\nfunction isDigit(c) {\n return c.charCodeAt(0) >= 48 && c.charCodeAt(0) <= 57;\n}\n\nfunction isLetter(c) {\n return (\n (c.charCodeAt(0) >= 65 && c.charCodeAt(0) <= 90) ||\n (c.charCodeAt(0) >= 97 && c.charCodeAt(0) <= 122)\n );\n}" ]
395
longest-substring-with-at-least-k-repeating-characters
[]
/** * @param {string} s * @param {number} k * @return {number} */ var longestSubstring = function(s, k) { };
Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k. if no such substring exists, return 0.   Example 1: Input: s = "aaabb", k = 3 Output: 3 Explanation: The longest substring is "aaa", as 'a' is repeated 3 times. Example 2: Input: s = "ababbc", k = 2 Output: 5 Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.   Constraints: 1 <= s.length <= 104 s consists of only lowercase English letters. 1 <= k <= 105
Medium
[ "hash-table", "string", "divide-and-conquer", "sliding-window" ]
[ "const longestSubstring = function (s, k) {\n if (s == null || s.length === 0) return 0\n const chars = new Array(26).fill(0)\n const aCode = 'a'.charCodeAt(0)\n for (let i = 0; i < s.length; i++) chars[s.charCodeAt(i) - aCode] += 1\n let flag = true\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] < k && chars[i] > 0) flag = false\n }\n if (flag === true) {\n return s.length\n }\n let result = 0\n let start = 0\n let cur = 0\n while (cur < s.length) {\n if (chars[s.charCodeAt(cur) - aCode] < k) {\n result = Math.max(result, longestSubstring(s.slice(start, cur), k))\n start = cur + 1\n }\n cur++\n }\n result = Math.max(result, longestSubstring(s.slice(start), k))\n return result\n}" ]
396
rotate-function
[]
/** * @param {number[]} nums * @return {number} */ var maxRotateFunction = function(nums) { };
You are given an integer array nums of length n. Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow: F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1]. Return the maximum value of F(0), F(1), ..., F(n-1). The test cases are generated so that the answer fits in a 32-bit integer.   Example 1: Input: nums = [4,3,2,6] Output: 26 Explanation: F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. Example 2: Input: nums = [100] Output: 0   Constraints: n == nums.length 1 <= n <= 105 -100 <= nums[i] <= 100
Medium
[ "array", "math", "dynamic-programming" ]
[ "const maxRotateFunction = function(A) {\n if(A.length === 0) return 0;\n let sum = 0, iteration = 0, len = A.length;\n for(let i = 0; i < len; i++){\n sum += A[i];\n iteration += (A[i] * i);\n }\n let max = iteration;\n for(let j = 1; j < len; j++){\n // for next iteration lets remove one entry value\n // of each entry and the prev 0 * k\n iteration = iteration - sum + A[j-1]*len;\n max = Math.max(max, iteration);\n }\n return max;\n};" ]
397
integer-replacement
[]
/** * @param {number} n * @return {number} */ var integerReplacement = function(n) { };
Given a positive integer n, you can apply one of the following operations: If n is even, replace n with n / 2. If n is odd, replace n with either n + 1 or n - 1. Return the minimum number of operations needed for n to become 1.   Example 1: Input: n = 8 Output: 3 Explanation: 8 -> 4 -> 2 -> 1 Example 2: Input: n = 7 Output: 4 Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1 Example 3: Input: n = 4 Output: 2   Constraints: 1 <= n <= 231 - 1
Medium
[ "dynamic-programming", "greedy", "bit-manipulation", "memoization" ]
[ "const integerReplacement = function(n, memo = {}) {\n if (n === 1) return 0;\n if (memo[n]) return memo[n];\n memo[n] = n % 2 === 0 ? integerReplacement(n/2, memo) + 1 : Math.min(integerReplacement(n+1, memo), integerReplacement(n-1, memo)) + 1;\n return memo[n]; \n};", "const integerReplacement = function(n) {\n let c = 0;\n while (n !== 1) {\n if ((n & 1) === 0) {\n n >>>= 1;\n } else if (n === 3 || ((n >>> 1) & 1) === 0) {\n --n;\n } else {\n ++n;\n }\n ++c;\n }\n return c; \n};" ]
398
random-pick-index
[]
/** * @param {number[]} nums */ var Solution = function(nums) { }; /** * @param {number} target * @return {number} */ Solution.prototype.pick = function(target) { }; /** * Your Solution object will be instantiated and called as such: * var obj = new Solution(nums) * var param_1 = obj.pick(target) */
Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class: Solution(int[] nums) Initializes the object with the array nums. int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i's, then each index should have an equal probability of returning.   Example 1: Input ["Solution", "pick", "pick", "pick"] [[[1, 2, 3, 3, 3]], [3], [1], [3]] Output [null, 4, 0, 2] Explanation Solution solution = new Solution([1, 2, 3, 3, 3]); solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1. solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.   Constraints: 1 <= nums.length <= 2 * 104 -231 <= nums[i] <= 231 - 1 target is an integer from nums. At most 104 calls will be made to pick.
Medium
[ "hash-table", "math", "reservoir-sampling", "randomized" ]
[ "const Solution = function(nums) {\n this.nums = nums;\n};\n\n\nSolution.prototype.pick = function(target) {\n const res = [];\n for (let i = 0; i < this.nums.length; i++) {\n if (this.nums[i] === target) {\n res.push(i);\n }\n }\n return res[Math.floor(Math.random() * res.length)];\n};" ]
399
evaluate-division
[ "Do you recognize this as a graph problem?" ]
/** * @param {string[][]} equations * @param {number[]} values * @param {string[][]} queries * @return {number[]} */ var calcEquation = function(equations, values, queries) { };
You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable. You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?. Return the answers to all queries. If a single answer cannot be determined, return -1.0. Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction. Note: The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.   Example 1: Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]] Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000] Explanation: Given: a / b = 2.0, b / c = 3.0 queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? return: [6.0, 0.5, -1.0, 1.0, -1.0 ] note: x is undefined => -1.0 Example 2: Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]] Output: [3.75000,0.40000,5.00000,0.20000] Example 3: Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]] Output: [0.50000,2.00000,-1.00000,-1.00000]   Constraints: 1 <= equations.length <= 20 equations[i].length == 2 1 <= Ai.length, Bi.length <= 5 values.length == equations.length 0.0 < values[i] <= 20.0 1 <= queries.length <= 20 queries[i].length == 2 1 <= Cj.length, Dj.length <= 5 Ai, Bi, Cj, Dj consist of lower case English letters and digits.
Medium
[ "array", "depth-first-search", "breadth-first-search", "union-find", "graph", "shortest-path" ]
[ "const calcEquation = function(equations, values, queries) {\n const m = {};\n for (let i = 0; i < values.length; i++) {\n if (!m.hasOwnProperty(equations[i][0])) m[equations[i][0]] = {};\n if (!m.hasOwnProperty(equations[i][1])) m[equations[i][1]] = {};\n m[equations[i][0]][equations[i][1]] = values[i];\n m[equations[i][1]][equations[i][0]] = 1 / values[i];\n }\n const r = [];\n for (let i = 0; i < queries.length; i++) {\n r[i] = dfs(queries[i][0], queries[i][1], 1, m, []);\n }\n return r;\n};\n\nfunction dfs(s, t, r, m, seen) {\n if (!m.hasOwnProperty(s) || !hsetAdd(seen, s)) return -1;\n if (s === t) return r;\n let next = m[s];\n for (let c of Object.keys(next)) {\n let result = dfs(c, t, r * next[c], m, seen);\n if (result !== -1) return result;\n }\n return -1;\n}\n\nfunction hsetAdd(arr, el) {\n if (arr.indexOf(el) === -1) {\n arr.push(el);\n return true;\n } else {\n return false;\n }\n}" ]
400
nth-digit
[]
/** * @param {number} n * @return {number} */ var findNthDigit = function(n) { };
Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].   Example 1: Input: n = 3 Output: 3 Example 2: Input: n = 11 Output: 0 Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.   Constraints: 1 <= n <= 231 - 1
Medium
[ "math", "binary-search" ]
[ "const findNthDigit = function(n) {\n let start = 1\n let len = 1\n let base = 9\n while(n > len * base) {\n n = n - len * base\n len++\n start *= 10\n base *= 10\n }\n let target = start + Math.floor((n - 1) / len)\n let reminder = (n - 1) % len\n return (''+target).charAt(reminder)\n};" ]
401
binary-watch
[ "Simplify by seeking for solutions that involve comparing bit counts.", "Consider calculating all possible times for comparison purposes." ]
/** * @param {number} turnedOn * @return {string[]} */ var readBinaryWatch = function(turnedOn) { };
A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. For example, the below binary watch reads "4:51". Given an integer turnedOn which represents the number of LEDs that are currently on (ignoring the PM), return all possible times the watch could represent. You may return the answer in any order. The hour must not contain a leading zero. For example, "01:00" is not valid. It should be "1:00". The minute must consist of two digits and may contain a leading zero. For example, "10:2" is not valid. It should be "10:02".   Example 1: Input: turnedOn = 1 Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"] Example 2: Input: turnedOn = 9 Output: []   Constraints: 0 <= turnedOn <= 10
Easy
[ "backtracking", "bit-manipulation" ]
[ "const readBinaryWatch = function(num) {\n const output = []\n for (let h = 0; h < 12; h++) {\n for (let m = 0; m < 60; m++) {\n const ones = Number(h * 64 + m)\n .toString(2)\n .split('')\n .filter(d => d === '1').length\n if (ones === num) output.push(m < 10 ? `${h}:0${m}` : `${h}:${m}`)\n }\n }\n return output\n}" ]
402
remove-k-digits
[]
/** * @param {string} num * @param {number} k * @return {string} */ var removeKdigits = function(num, k) { };
Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.   Example 1: Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. Example 2: Input: num = "10200", k = 1 Output: "200" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. Example 3: Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0.   Constraints: 1 <= k <= num.length <= 105 num consists of only digits. num does not have any leading zeros except for the zero itself.
Medium
[ "string", "stack", "greedy", "monotonic-stack" ]
[ "const removeKdigits = function(num, k) {\n const digits = num.length - k;\n const stk = new Array(num.length);\n let top = 0;\n // k keeps track of how many characters we can remove\n // if the previous character in stk is larger than the current one\n // then removing it will get a smaller number\n // but we can only do so when k is larger than 0\n for (let i = 0; i < num.length; i++) {\n let c = num.charAt(i);\n while (top > 0 && stk[top - 1] > c && k > 0) {\n top -= 1;\n k -= 1;\n }\n stk[top++] = c;\n }\n // find the index of first non-zero digit\n let idx = 0;\n while (idx < digits && stk[idx] === \"0\") idx++;\n return idx === digits ? \"0\" : stk.slice(idx, digits + idx).join(\"\");\n};", "const removeKdigits = function(num, k) {\n const n = num.length, stack = []\n if(n === k) return '0'\n let i = 0\n while(i < n) {\n while(k > 0 && stack.length && stack[stack.length - 1] > num[i]) {\n k--\n stack.pop()\n }\n stack.push(num[i++])\n }\n while(k-- > 0) stack.pop()\n while(stack[0] === '0') stack.shift()\n return stack.length ? stack.join('') : '0'\n};", "const removeKdigits = function(num, k) {\n const n = num.length, stack = []\n for(let i = 0; i < n; i++) {\n const ch = num[i]\n while(stack.length && k > 0 && ch < stack[stack.length - 1]) {\n stack.pop()\n k--\n }\n stack.push(ch)\n }\n while(k > 0) {\n stack.pop()\n k--\n }\n while(stack[0] === '0') stack.shift()\n return stack.length ? stack.join('') : '0'\n};" ]
403
frog-jump
[]
/** * @param {number[]} stones * @return {boolean} */ var canCross = function(stones) { };
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction.   Example 1: Input: stones = [0,1,3,5,6,8,12,17] Output: true Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. Example 2: Input: stones = [0,1,2,3,4,8,9,11] Output: false Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.   Constraints: 2 <= stones.length <= 2000 0 <= stones[i] <= 231 - 1 stones[0] == 0 stones is sorted in a strictly increasing order.
Hard
[ "array", "dynamic-programming" ]
[ "const canCross = function(stones) {\n for (let i = 3; i < stones.length; i++) {\n if (stones[i] > stones[i - 1] * 2) {\n return false\n }\n }\n const count = new Set(stones)\n const lastStone = stones[stones.length - 1]\n const position = [0]\n const jump = [0]\n while (position.length > 0) {\n const nextPosition = position.pop()\n const nextDistance = jump.pop()\n for (let i = nextDistance - 1; i <= nextDistance + 1; i++) {\n if (i <= 0) {\n continue\n }\n const nextStone = nextPosition + i\n if (nextStone == lastStone) {\n return true\n } else if (count.has(nextStone)) {\n position.push(nextStone)\n jump.push(i)\n }\n }\n }\n return false\n}" ]
404
sum-of-left-leaves
[]
/** * 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 sumOfLeftLeaves = function(root) { };
Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.   Example 1: Input: root = [3,9,20,null,null,15,7] Output: 24 Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively. Example 2: Input: root = [1] Output: 0   Constraints: The number of nodes in the tree is in the range [1, 1000]. -1000 <= Node.val <= 1000
Easy
[ "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const sumOfLeftLeaves = function(root) {\n if(root == null) return 0\n let res = 0\n function dfs(node, side) {\n if(node === null) return\n if(node.left === null && node.right === null) {\n if(side === 'left') res += node.val\n return\n }\n dfs(node.left, 'left')\n dfs(node.right, 'right')\n }\n dfs(root.left, 'left')\n dfs(root.right, 'right')\n\n return res\n};" ]
405
convert-a-number-to-hexadecimal
[]
/** * @param {number} num * @return {string} */ var toHex = function(num) { };
Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used. All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. Note: You are not allowed to use any built-in library method to directly solve this problem.   Example 1: Input: num = 26 Output: "1a" Example 2: Input: num = -1 Output: "ffffffff"   Constraints: -231 <= num <= 231 - 1
Easy
[ "math", "bit-manipulation" ]
[ "const toHex = function(num) {\n const bin = (num >>> 0).toString(2)\n const arr = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']\n const mod = bin.length % 4\n const r = []\n if(mod !== 0 ){\n r.push(arr[ parseInt(bin.slice(0, mod),2) ])\n }\n \n for(let i = mod; i < bin.length; i = i + 4) {\n r.push(arr[ parseInt(bin.slice(i, i+4),2) ])\n }\n return r.join('')\n};" ]
406
queue-reconstruction-by-height
[ "What can you say about the position of the shortest person? </br>\r\nIf the position of the shortest person is <i>i</i>, how many people would be in front of the shortest person?", "Once you fix the position of the shortest person, what can you say about the position of the second shortest person?" ]
/** * @param {number[][]} people * @return {number[][]} */ var reconstructQueue = function(people) { };
You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi. Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).   Example 1: Input: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] Output: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] Explanation: Person 0 has height 5 with no other people taller or the same height in front. Person 1 has height 7 with no other people taller or the same height in front. Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1. Person 3 has height 6 with one person taller or the same height in front, which is person 1. Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with one person taller or the same height in front, which is person 1. Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue. Example 2: Input: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] Output: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]   Constraints: 1 <= people.length <= 2000 0 <= hi <= 106 0 <= ki < people.length It is guaranteed that the queue can be reconstructed.
Medium
[ "array", "greedy", "binary-indexed-tree", "segment-tree", "sorting" ]
[ "const reconstructQueue = function (people) {\n const h = 0\n const k = 1\n people.sort((a, b) => (a[h] == b[h] ? a[k] - b[k] : b[h] - a[h]))\n let queue = []\n for (let person of people) {\n queue.splice(person[k], 0, person)\n }\n return queue\n}", "const reconstructQueue = function(people) {\n if (!people) return [];\n const peopledct = {};\n let height = [];\n const res = [];\n people.forEach((el, idx) => {\n if (peopledct.hasOwnProperty(el[0])) {\n peopledct[el[0]].push([el[1], idx]);\n } else {\n peopledct[el[0]] = [[el[1], idx]];\n height.push(el[0]);\n }\n });\n height = height.sort((a, b) => b - a);\n\n for (let i = 0; i < height.length; i++) {\n peopledct[height[i]] = peopledct[height[i]].sort((a, b) => a[0] - b[0]);\n for (el of peopledct[height[i]]) {\n res.splice(el[0], 0, people[el[1]]);\n }\n }\n return res;\n};\n\nconsole.log(reconstructQueue([[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]));" ]
407
trapping-rain-water-ii
[]
/** * @param {number[][]} heightMap * @return {number} */ var trapRainWater = function(heightMap) { };
Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.   Example 1: Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] Output: 4 Explanation: After the rain, water is trapped between the blocks. We have two small ponds 1 and 3 units trapped. The total volume of water trapped is 4. Example 2: Input: heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]] Output: 10   Constraints: m == heightMap.length n == heightMap[i].length 1 <= m, n <= 200 0 <= heightMap[i][j] <= 2 * 104
Hard
[ "array", "breadth-first-search", "heap-priority-queue", "matrix" ]
[ "const trapRainWater = function (heightMap) {\n const pq = new PriorityQueue((a, b) => a[2] < b[2])\n const m = heightMap.length, n = heightMap[0].length\n \n const visited = Array.from({ length: m }, () => Array(n).fill(false))\n \n for(let i = 0; i < m; i++) {\n visited[i][0] = visited[i][n - 1] = true\n pq.push([i, 0, heightMap[i][0]])\n pq.push([i, n - 1, heightMap[i][n - 1]])\n }\n for(let j = 1; j < n - 1; j++) {\n visited[0][j] = visited[m - 1][j] = true\n pq.push([0, j, heightMap[0][j]], [m - 1, j, heightMap[m - 1][j]])\n }\n \n let res = 0\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n while(!pq.isEmpty()) {\n const cur = pq.pop()\n const [r, c, h] = cur\n for(let dir of dirs) {\n const newR = r + dir[0], newC = c + dir[1]\n if(newR < 0 || newR >= m || newC < 0 || newC >= n || visited[newR][newC]) continue\n visited[newR][newC] = true\n res += Math.max(0, h - heightMap[newR][newC])\n pq.push([newR, newC, Math.max(h, heightMap[newR][newC])])\n }\n }\n \n return res\n\n}\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}", "const trapRainWater = function (heightMap) {\n const pq = new PriorityQueue((a, b) => a[2] < b[2])\n const visited = []\n for (let i = 0; i < heightMap.length; i++) {\n visited[i] = []\n for (let j = 0; j < heightMap[0].length; j++) {\n if (\n i > 0 &&\n i < heightMap.length - 1 &&\n j > 0 &&\n j < heightMap[0].length - 1\n )\n continue\n pq.push([i, j, heightMap[i][j]])\n visited[i][j] = true\n }\n }\n\n let max = -Infinity,\n count = 0\n while (!pq.isEmpty()) {\n const cur = pq.pop()\n if (cur[2] > max) max = cur[2]\n check(cur[0], cur[1])\n }\n function check(row, col) {\n const step = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ]\n for (let i = 0; i < step.length; i++) {\n let newR = row + step[i][0],\n newC = col + step[i][1]\n if (\n newR < 0 ||\n newR >= heightMap.length ||\n newC < 0 ||\n newC >= heightMap[0].length\n )\n continue\n if (visited[newR][newC]) continue\n visited[newR][newC] = true\n const newVal = heightMap[newR][newC]\n if (newVal < max) {\n count += max - newVal\n check(newR, newC)\n } else {\n pq.push([newR, newC, newVal])\n }\n }\n }\n\n return count\n}\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}", "const trapRainWater = function(heightMap) {\n\n function PriorityQueueMin(){\n let heap=[null]\n function swim(idx){\n if(idx<2)return\n let k=Math.floor(idx/2)\n if(heap[idx][2]-heap[k][2]<0){\n swap(heap,idx,k)\n idx=k\n swim(idx)\n }\n }\n function sink(idx){\n let k=Math.floor(idx*2)\n if(k>=heap.length)return\n if(k<heap.length && heap[k+1] && heap[k][2]-heap[k+1][2]>0) k++\n if(heap[idx][2]-heap[k][2]>0){\n swap(heap,idx,k)\n idx=k\n sink(idx)\n }\n }\n function swap(arr,i,j){\n let temp=arr[i]\n arr[i]=arr[j]\n arr[j]=temp\n }\n this.insert=function (v) {\n heap.push(v)\n swim(heap.length-1)\n }\n this.delMin=function () {\n swap(heap,1,heap.length-1)\n let min=heap.pop()\n sink(1)\n return min\n }\n this.isEmpty=function () {\n return heap.length===1\n }\n }\n \n let pq=new PriorityQueueMin()\n let visited=[]\n for(let i=0;i<heightMap.length;i++){\n visited[i]=[]\n for(let j=0;j<heightMap[0].length;j++){\n if((i>0 && i<heightMap.length-1) && (j>0 && j<heightMap[0].length-1))continue\n pq.insert([i,j,heightMap[i][j]])\n visited[i][j]=true\n }\n }\n \n let max=-Infinity,count=0\n while(!pq.isEmpty()){\n let cur=pq.delMin()\n if(cur[2]>max)max=cur[2]\n check(cur[0],cur[1])\n }\n function check(row,col){\n let step=[[-1,0],[1,0],[0,-1],[0,1]]\n for(let i=0;i<step.length;i++){\n let newR=row+step[i][0],newC=col+step[i][1]\n if((newR<0 || newR>=heightMap.length) || (newC<0 || newC>=heightMap[0].length))continue\n if(visited[newR][newC])continue\n visited[newR][newC]=true\n let newVal=heightMap[newR][newC]\n if(newVal<max){\n count+=max-newVal\n check(newR,newC)\n }else{\n pq.insert([newR,newC,newVal])\n }\n }\n }\n \n return count\n };" ]
409
longest-palindrome
[]
/** * @param {string} s * @return {number} */ var longestPalindrome = function(s) { };
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome here.   Example 1: Input: s = "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. Example 2: Input: s = "a" Output: 1 Explanation: The longest palindrome that can be built is "a", whose length is 1.   Constraints: 1 <= s.length <= 2000 s consists of lowercase and/or uppercase English letters only.
Easy
[ "hash-table", "string", "greedy" ]
[ "const longestPalindrome = function (s) {\n const set = new Set()\n let counter = 0\n for (let i = 0; i < s.length; i++) {\n const currentChar = s[i]\n if (set.has(currentChar)) {\n counter++\n set.delete(currentChar)\n } else {\n set.add(currentChar)\n }\n }\n counter *= 2\n if (set.size > 0) counter++\n return counter\n}", "const longestPalindrome = function(s) {\n const hash = {};\n let c;\n for (let i = 0; i < s.length; i++) {\n c = s.charAt(i);\n if (hash.hasOwnProperty(c)) {\n hash[c] += 1;\n } else {\n hash[c] = 1;\n }\n }\n let res = 0;\n let val;\n for (let k in hash) {\n if (hash.hasOwnProperty(k)) {\n val = hash[k];\n res += Math.floor(val / 2) * 2;\n if (res % 2 === 0 && val % 2 === 1) {\n res += 1;\n }\n }\n }\n\n return res;\n};" ]
410
split-array-largest-sum
[]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var splitArray = function(nums, k) { };
Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized. Return the minimized largest sum of the split. A subarray is a contiguous part of the array.   Example 1: Input: nums = [7,2,5,10,8], k = 2 Output: 18 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18. Example 2: Input: nums = [1,2,3,4,5], k = 2 Output: 9 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9.   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 106 1 <= k <= min(50, nums.length)
Hard
[ "array", "binary-search", "dynamic-programming", "greedy", "prefix-sum" ]
[ "function doable(nums, cuts, max) {\n let acc = 0\n for(let num of nums) {\n if(num > max) return false\n else if(acc + num <= max) acc += num\n else {\n --cuts;\n acc = num;\n if(cuts < 0) return false\n }\n }\n return true\n}\n\n\nfunction splitArray(nums, m) {\n let left = 0\n let right = 0\n for(let num of nums) {\n left = Math.max(left, num)\n right += num\n }\n while(left < right) {\n let mid = Math.floor(left + (right - left) / 2)\n if(doable(nums, m - 1, mid)) right = mid\n else left = mid + 1 \n }\n return left\n}\n\n\n\nconst splitArray = function(nums, m) {\n let l = 0,\n r = 0\n for (let el of nums) {\n if (el > l) l = el\n r += el\n }\n while (l < r) {\n let mid = Math.floor((l + r) / 2)\n if (numOfSubArrLessOrEqualThanM(nums, mid, m)) r = mid\n else l = mid + 1\n }\n return l\n}\n\nfunction numOfSubArrLessOrEqualThanM(nums, target, m) {\n let sum = 0,\n count = 1\n for (let el of nums) {\n sum += el\n if (sum > target) {\n sum = el\n count++\n }\n if (count > m) return false\n }\n return true\n}", "const splitArray = (nums, m) => {\n let max = -Infinity, sum = 0\n for(let num of nums) {\n sum += num\n max = Math.max(max, num)\n }\n if (m === 1) return sum\n let l = max, r = sum\n while(l < r) {\n let mid = l + ((r - l) >> 1)\n if(valid(mid, nums, m)) {\n r = mid\n } else {\n l = mid + 1\n }\n }\n return l\n}\n\nfunction valid(target, nums, m) {\n let cnt = 1, sum = 0\n for(let num of nums) {\n sum += num\n if(sum > target) {\n cnt++\n sum = num\n if(cnt > m) return false\n }\n }\n\n return true\n}" ]
412
fizz-buzz
[]
/** * @param {number} n * @return {string[]} */ var fizzBuzz = function(n) { };
Given an integer n, return a string array answer (1-indexed) where: answer[i] == "FizzBuzz" if i is divisible by 3 and 5. answer[i] == "Fizz" if i is divisible by 3. answer[i] == "Buzz" if i is divisible by 5. answer[i] == i (as a string) if none of the above conditions are true.   Example 1: Input: n = 3 Output: ["1","2","Fizz"] Example 2: Input: n = 5 Output: ["1","2","Fizz","4","Buzz"] Example 3: Input: n = 15 Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]   Constraints: 1 <= n <= 104
Easy
[ "math", "string", "simulation" ]
[ "const fizzBuzz = function(n) {\n const res = [];\n for (let i = 1; i <= n; i++) {\n res.push(single(i));\n }\n\n return res;\n};\n\nfunction single(num) {\n let str = \"\";\n if (num % 3 === 0) {\n str += \"Fizz\";\n }\n if (num % 5 === 0) {\n str += \"Buzz\";\n }\n if (str === \"\") {\n str += num;\n }\n return str;\n}\n\nconsole.log(fizzBuzz(15));" ]
413
arithmetic-slices
[]
/** * @param {number[]} nums * @return {number} */ var numberOfArithmeticSlices = function(nums) { };
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences. Given an integer array nums, return the number of arithmetic subarrays of nums. A subarray is a contiguous subsequence of the array.   Example 1: Input: nums = [1,2,3,4] Output: 3 Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. Example 2: Input: nums = [1] Output: 0   Constraints: 1 <= nums.length <= 5000 -1000 <= nums[i] <= 1000
Medium
[ "array", "dynamic-programming" ]
[ "const numberOfArithmeticSlices = function(A) {\n const arr = [];\n let count = 0;\n for (let i = 1; i < A.length - 1; i++) {\n if (A[i] - A[i - 1] === A[i + 1] - A[i]) {\n count += 1;\n } else {\n arr.push(count);\n count = 0;\n }\n }\n arr.push(count);\n return arr.reduce((ac, el) => ac + calc(el), 0);\n};\n\nfunction calc(num) {\n return (num * (num + 1)) / 2;\n}\n\nconsole.log(numberOfArithmeticSlices([1, 2, 3, 4]));" ]
414
third-maximum-number
[]
/** * @param {number[]} nums * @return {number} */ var thirdMax = function(nums) { };
Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.   Example 1: Input: nums = [3,2,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. Example 2: Input: nums = [1,2] Output: 2 Explanation: The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead. Example 3: Input: nums = [2,2,3,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2 (both 2's are counted together since they have the same value). The third distinct maximum is 1.   Constraints: 1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1   Follow up: Can you find an O(n) solution?
Easy
[ "array", "sorting" ]
[ "const thirdMax = function(nums) {\n let count = 0, max=mid=small=Number.MIN_SAFE_INTEGER;\n for (let i in nums) {\n if (count > 0 && nums[i] === max || count > 1 && nums[i] === mid) continue;\n count++;\n if (nums[i] > max) {\n small = mid;\n mid = max;\n max = nums[i];\n } else if (nums[i] > mid) {\n small = mid;\n mid = nums[i];\n } else if (nums[i] > small) {\n small = nums[i];\n }\n }\n return count < 3 ? max : small;\n};" ]
415
add-strings
[]
/** * @param {string} num1 * @param {string} num2 * @return {string} */ var addStrings = function(num1, num2) { };
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.   Example 1: Input: num1 = "11", num2 = "123" Output: "134" Example 2: Input: num1 = "456", num2 = "77" Output: "533" Example 3: Input: num1 = "0", num2 = "0" Output: "0"   Constraints: 1 <= num1.length, num2.length <= 104 num1 and num2 consist of only digits. num1 and num2 don't have any leading zeros except for the zero itself.
Easy
[ "math", "string", "simulation" ]
[ "const addStrings = function(num1, num2) {\n let sb = \"\";\n let carry = 0;\n for (\n let i = num1.length - 1, j = num2.length - 1;\n i >= 0 || j >= 0 || carry == 1;\n i--, j--\n ) {\n let x = i < 0 ? 0 : +num1.charAt(i);\n let y = j < 0 ? 0 : +num2.charAt(j);\n sb = (+(x + y + carry) % 10) + sb;\n carry = x + y + carry >= 10 ? 1 : 0;\n }\n return sb;\n};" ]
416
partition-equal-subset-sum
[]
/** * @param {number[]} nums * @return {boolean} */ var canPartition = function(nums) { };
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.   Example 1: Input: nums = [1,5,11,5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11]. Example 2: Input: nums = [1,2,3,5] Output: false Explanation: The array cannot be partitioned into equal sum subsets.   Constraints: 1 <= nums.length <= 200 1 <= nums[i] <= 100
Medium
[ "array", "dynamic-programming" ]
[ "const canPartition = function(nums) {\n let sum = 0\n for(let num of nums) {\n sum += num\n }\n \n if(sum & 1 === 1) {\n return false\n }\n \n sum /= 2\n let n = nums.length\n const dp = Array.from(new Array(n+1), () => [])\n for(let i = 0; i < dp.length; i++) {\n dp[i] = new Array(sum+1).fill(false)\n }\n dp[0][0] = true\n for(let i = 1; i < n + 1; i++) {\n dp[i][0] = true\n }\n for(let j = 1; j < sum + 1; j++) {\n dp[0][j] = false\n }\n for(let i = 1; i < n + 1; i++) {\n for(let j = 1; j < sum + 1; j++) {\n if(j >= nums[i - 1]) {\n dp[i][j] = (dp[i -1][j] || dp[i - 1][j - nums[i - 1]])\n }\n }\n }\n return dp[n][sum]\n};", "const canPartition = function(nums) {\n if (nums.length < 2) return false\n\n const total = nums.reduce((a, c) => a + c)\n if (total % 2 !== 0) return false\n\n nums.sort((a, b) => b - a)\n const target = total / 2\n\n if (nums[0] > target) return false\n return findCombination(nums, target, 0)\n}\n\nfunction findCombination(nums, target, start) {\n if (target === 0) {\n return true\n } else {\n for (let i = start; i < nums.length; i++) {\n if (nums[i] <= target) {\n if (findCombination(nums, target - nums[i], i + 1)) {\n return true\n }\n }\n }\n return false\n }\n}", "function helper(nums, target, pos) {\n for (let i = pos; i <= nums.length; i++) {\n if (i != pos && nums[i] == nums[i - 1]) continue\n if (nums[i] === target) return true\n if (nums[i] > target) break\n if (helper(nums, target - nums[i], i + 1)) return true\n }\n return false\n}\nconst canPartition = function(nums) {\n const sum = nums.reduce((sum, n) => (sum += n), 0) / 2\n if (sum % 1 != 0) {\n return false\n }\n\n return helper(nums, sum, 0)\n}", "const canPartition = function (nums) {\n const sumA = nums.reduce((acc, curr) => acc + curr, 0)\n if (sumA % 2) return false\n let row = 1n << BigInt(sumA / 2)\n for (const weight of nums) row = row | (row >> BigInt(weight))\n \n return row & 1n\n}" ]
417
pacific-atlantic-water-flow
[]
/** * @param {number[][]} heights * @return {number[][]} */ var pacificAtlantic = function(heights) { };
There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c). The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.   Example 1: Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] Explanation: The following cells can flow to the Pacific and Atlantic oceans, as shown below: [0,4]: [0,4] -> Pacific Ocean   [0,4] -> Atlantic Ocean [1,3]: [1,3] -> [0,3] -> Pacific Ocean   [1,3] -> [1,4] -> Atlantic Ocean [1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean   [1,4] -> Atlantic Ocean [2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean   [2,2] -> [2,3] -> [2,4] -> Atlantic Ocean [3,0]: [3,0] -> Pacific Ocean   [3,0] -> [4,0] -> Atlantic Ocean [3,1]: [3,1] -> [3,0] -> Pacific Ocean   [3,1] -> [4,1] -> Atlantic Ocean [4,0]: [4,0] -> Pacific Ocean [4,0] -> Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. Example 2: Input: heights = [[1]] Output: [[0,0]] Explanation: The water can flow from the only cell to the Pacific and Atlantic oceans.   Constraints: m == heights.length n == heights[r].length 1 <= m, n <= 200 0 <= heights[r][c] <= 105
Medium
[ "array", "depth-first-search", "breadth-first-search", "matrix" ]
[ "const pacificAtlantic = function(matrix) {\n const res = []\n if (!matrix || matrix.length === 0 || matrix[0].length === 0) return res\n const rows = matrix.length\n const cols = matrix[0].length\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n const pacific = Array.from({ length: rows }, () => new Array(cols).fill(false))\n const atlantic = Array.from({ length: rows }, () => new Array(cols).fill(false))\n for (let y = 0; y < rows; y++) {\n helper(0, y, pacific, -1, matrix, cols, rows, dirs)\n helper(cols - 1, y, atlantic, -1, matrix, cols, rows, dirs)\n }\n for (let x = 0; x < cols; x++) {\n helper(x, 0, pacific, -1, matrix, cols, rows, dirs)\n helper(x, rows - 1, atlantic, -1, matrix, cols, rows, dirs)\n }\n\n for (let y = 0; y < rows; y++) {\n for (let x = 0; x < cols; x++) {\n if (pacific[y][x] && atlantic[y][x]) {\n res.push([y, x])\n }\n }\n }\n return res\n}\n\nfunction helper(x, y, visited, height, matrix, cols, rows, dirs) {\n if (x < 0 || x >= cols || y < 0 || y >= rows || visited[y][x] || matrix[y][x] < height) return\n visited[y][x] = true\n for (let dir of dirs)\n helper(x + dir[0], y + dir[1], visited, matrix[y][x], matrix, cols, rows, dirs)\n}" ]
419
battleships-in-a-board
[]
/** * @param {character[][]} board * @return {number} */ var countBattleships = function(board) { };
Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board. Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).   Example 1: Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]] Output: 2 Example 2: Input: board = [["."]] Output: 0   Constraints: m == board.length n == board[i].length 1 <= m, n <= 200 board[i][j] is either '.' or 'X'.   Follow up: Could you do it in one-pass, using only O(1) extra memory and without modifying the values board?
Medium
[ "array", "depth-first-search", "matrix" ]
null
[]
420
strong-password-checker
[]
/** * @param {string} password * @return {number} */ var strongPasswordChecker = function(password) { };
A password is considered strong if the below conditions are all met: It has at least 6 characters and at most 20 characters. It contains at least one lowercase letter, at least one uppercase letter, and at least one digit. It does not contain three repeating characters in a row (i.e., "Baaabb0" is weak, but "Baaba0" is strong). Given a string password, return the minimum number of steps required to make password strong. if password is already strong, return 0. In one step, you can: Insert one character to password, Delete one character from password, or Replace one character of password with another character.   Example 1: Input: password = "a" Output: 5 Example 2: Input: password = "aA1" Output: 3 Example 3: Input: password = "1337C0d3" Output: 0   Constraints: 1 <= password.length <= 50 password consists of letters, digits, dot '.' or exclamation mark '!'.
Hard
[ "string", "greedy", "heap-priority-queue" ]
[ "const strongPasswordChecker = function(s) {\n let n = s.length,\n toAdd = Math.max(0, 6 - n),\n toDel = Math.max(n - 20, 0),\n repeat = Array.from({ length: 3 }, _ => []),\n lower = 1,\n upper = 1,\n digit = 1,\n add = 0,\n del = 0,\n rep = 0,\n k = 0;\n\n for (let i = 0; i <= n; i++) {\n if (s[i] != s[k]) {\n let len = i - k;\n if (len >= 3) repeat[len % 3].push(len);\n k = i;\n }\n if (i == n) break;\n if (/\\d/.test(s[i])) digit = 0;\n if (/[a-z]/.test(s[i])) lower = 0;\n if (/[A-Z]/.test(s[i])) upper = 0;\n }\n\n repeat.map((arr, mod) => {\n for (let len of arr) {\n if (toAdd - add > 0) {\n len -= 2;\n add++;\n }\n\n if (toDel - del > 0) {\n del += mod + 1;\n len -= mod + 1;\n }\n rep += (len / 3) | 0;\n }\n });\n toDel - del > 0\n ? (rep = Math.max(0, rep - Math.floor((toDel - del) / 3)))\n : (rep += del - toDel);\n return toDel + Math.max(digit + lower + upper, rep + toAdd);\n};" ]
421
maximum-xor-of-two-numbers-in-an-array
[]
/** * @param {number[]} nums * @return {number} */ var findMaximumXOR = function(nums) { };
Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.   Example 1: Input: nums = [3,10,5,25,2,8] Output: 28 Explanation: The maximum result is 5 XOR 25 = 28. Example 2: Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70] Output: 127   Constraints: 1 <= nums.length <= 2 * 105 0 <= nums[i] <= 231 - 1
Medium
[ "array", "hash-table", "bit-manipulation", "trie" ]
[ "const findMaximumXOR = function(nums) {\n let res = 0, mask = 0\n for(let i = 31; i >= 0; i--) {\n mask = mask | (1 << i)\n const set = new Set()\n for(let e of nums) set.add(e & mask)\n const tmp = res | (1 << i)\n for(let e of set) {\n if(set.has(e ^ tmp)) {\n res = tmp\n break\n }\n }\n }\n return res\n};", "const findMaximumXOR = function(nums) {\n let maxResult = 0\n let mask = 0\n \n for (let i = 31; i >= 0; i--) {\n //The mask will grow like 100..000 , 110..000, 111..000, then 1111...111\n //for each iteration, we only care about the left parts\n mask = mask | (1 << i)\n\n let set = new Set()\n for (let num of nums) {\n \n let leftPartOfNum = num & mask\n set.add(leftPartOfNum)\n }\n\n // if i = 1 and before this iteration, the maxResult we have now is 1100,\n // my wish is the maxResult will grow to 1110, so I will try to find a candidate\n // which can give me the greedyTry;\n let greedyTry = maxResult | (1 << i)\n\n for (let leftPartOfNum of set) {\n //This is the most tricky part, coming from a fact that if a ^ b = c, then a ^ c = b;\n // now we have the 'c', which is greedyTry, and we have the 'a', which is leftPartOfNum\n // If we hope the formula a ^ b = c to be valid, then we need the b,\n // and to get b, we need a ^ c, if a ^ c exisited in our set, then we're good to go\n let anotherNum = leftPartOfNum ^ greedyTry\n if (set.has(anotherNum)) {\n maxResult = greedyTry\n break\n }\n }\n\n // If unfortunately, we didn't get the greedyTry, we still have our max,\n // So after this iteration, the max will stay at 1100.\n }\n return maxResult\n}", "const findMaximumXOR = function (nums) {\n if (nums == null || nums.length == 0) {\n return 0\n }\n const root = new Trie()\n for (let num of nums) {\n let curNode = root\n for (let i = 31; i >= 0; i--) {\n let curBit = (num >>> i) & 1\n if (curNode.children[curBit] == null) {\n curNode.children[curBit] = new Trie()\n }\n curNode = curNode.children[curBit]\n }\n }\n let max = Number.MIN_VALUE\n for (let num of nums) {\n let curNode = root\n let curSum = 0\n for (let i = 31; i >= 0; i--) {\n let curBit = (num >>> i) & 1\n if (curNode.children[curBit ^ 1] != null) {\n curSum += 1 << i\n curNode = curNode.children[curBit ^ 1]\n } else {\n curNode = curNode.children[curBit]\n }\n }\n max = Math.max(curSum, max)\n }\n return max\n}\n\nclass Trie {\n constructor() {\n this.children = {}\n }\n}" ]
423
reconstruct-original-digits-from-english
[]
/** * @param {string} s * @return {string} */ var originalDigits = function(s) { };
Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.   Example 1: Input: s = "owoztneoer" Output: "012" Example 2: Input: s = "fviefuro" Output: "45"   Constraints: 1 <= s.length <= 105 s[i] is one of the characters ["e","g","f","i","h","o","n","s","r","u","t","w","v","x","z"]. s is guaranteed to be valid.
Medium
[ "hash-table", "math", "string" ]
[ "const originalDigits = function(s) {\n const count = new Array(10).fill(0);\n for (let i = 0; i < s.length; i++) {\n let c = s.charAt(i);\n if (c === \"z\") count[0]++;\n if (c === \"w\") count[2]++;\n if (c === \"x\") count[6]++;\n if (c === \"s\") count[7]++; //7-6\n if (c === \"g\") count[8]++;\n if (c === \"u\") count[4]++;\n if (c === \"f\") count[5]++; //5-4\n if (c === \"h\") count[3]++; //3-8\n if (c === \"i\") count[9]++; //9-8-5-6\n if (c === \"o\") count[1]++; //1-0-2-4\n }\n count[7] -= count[6];\n count[5] -= count[4];\n count[3] -= count[8];\n count[9] = count[9] - count[8] - count[5] - count[6];\n count[1] = count[1] - count[0] - count[2] - count[4];\n let ans = \"\";\n for (let i = 0; i <= 9; i++) {\n ans += `${i}`.repeat(count[i]);\n }\n return ans;\n};" ]
424
longest-repeating-character-replacement
[]
/** * @param {string} s * @param {number} k * @return {number} */ var characterReplacement = function(s, k) { };
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations.   Example 1: Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa. Example 2: Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4. There may exists other ways to achive this answer too.   Constraints: 1 <= s.length <= 105 s consists of only uppercase English letters. 0 <= k <= s.length
Medium
[ "hash-table", "string", "sliding-window" ]
[ "const characterReplacement = function(s, k) {\n const len = s.length;\n const count = Array(26).fill(0);\n let start = 0,\n maxCount = 0,\n maxLength = 0;\n const ca = \"A\".charCodeAt(0);\n for (let end = 0; end < len; end++) {\n maxCount = Math.max(maxCount, ++count[s.charCodeAt(end) - ca]);\n if (end - start + 1 - maxCount > k) {\n count[s.charCodeAt(start) - ca]--;\n start++;\n }\n maxLength = Math.max(maxLength, end - start + 1);\n }\n return maxLength;\n};\n\nconsole.log(characterReplacement(\"ABAB\", 2));\nconsole.log(characterReplacement(\"AABABBA\", 1));", "const characterReplacement = function (s, k) {\n const freq = Array(26).fill(0),\n n = s.length,\n { max } = Math,\n A = 'A'.charCodeAt(0)\n let res = 0,\n l = 0,\n r = 0,\n maxFreq = 0\n while (r < n) {\n maxFreq = max(maxFreq, ++freq[s.charCodeAt(r) - A])\n if (r - l + 1 - maxFreq > k) {\n freq[s.charCodeAt(l) - A]--\n l++\n }\n res = max(res, r - l + 1)\n r++\n }\n\n return res\n}" ]
427
construct-quad-tree
[]
/** * // Definition for a QuadTree node. * function Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) { * this.val = val; * this.isLeaf = isLeaf; * this.topLeft = topLeft; * this.topRight = topRight; * this.bottomLeft = bottomLeft; * this.bottomRight = bottomRight; * }; */ /** * @param {number[][]} grid * @return {Node} */ var construct = function(grid) { };
Given a n * n matrix grid of 0's and 1's only. We want to represent grid with a Quad-Tree. Return the root of the Quad-Tree representing grid. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: val: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the val to True or False when isLeaf is False, and both are accepted in the answer. isLeaf: True if the node is a leaf node on the tree or False if the node has four children. class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; } We can construct a Quad-Tree from a two-dimensional area using the following steps: If the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop. If the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo. Recurse for each of the children with the proper sub-grid. If you want to know more about the Quad-Tree, you can refer to the wiki. Quad-Tree format: You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val]. If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.   Example 1: Input: grid = [[0,1],[1,0]] Output: [[0,1],[1,0],[1,1],[1,1],[1,0]] Explanation: The explanation of this example is shown below: Notice that 0 represents False and 1 represents True in the photo representing the Quad-Tree. Example 2: Input: grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]] Output: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]] Explanation: All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below:   Constraints: n == grid.length == grid[i].length n == 2x where 0 <= x <= 6
Medium
[ "array", "divide-and-conquer", "tree", "matrix" ]
/** * // Definition for a QuadTree node. * function Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) { * this.val = val; * this.isLeaf = isLeaf; * this.topLeft = topLeft; * this.topRight = topRight; * this.bottomLeft = bottomLeft; * this.bottomRight = bottomRight; * }; */
[ "const construct = function(grid) {\n const tree = m => {\n const node = new Node()\n const isAllOne = m.every(r => r.every(v => v === 1))\n const isAllZero = m.every(r => r.every(v => v === 0))\n if (isAllOne) {\n node.val = true\n node.isLeaf = true\n } else if (isAllZero) {\n node.val = false\n node.isLeaf = true\n } else {\n const len = m.length\n let left = m.map(r => r.slice(0, len / 2))\n let right = m.map(r => r.slice(len / 2))\n node.topLeft = tree(left.slice(0, len / 2))\n node.topRight = tree(right.slice(0, len / 2))\n node.bottomLeft = tree(left.slice(len / 2))\n node.bottomRight = tree(right.slice(len / 2))\n node.isLeaf = false\n node.val = true\n }\n return node\n }\n return tree(grid)\n}" ]
429
n-ary-tree-level-order-traversal
[]
/** * // Definition for a Node. * function Node(val,children) { * this.val = val; * this.children = children; * }; */ /** * @param {Node|null} root * @return {number[][]} */ var levelOrder = function(root) { };
Given an n-ary tree, return the level order traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).   Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [[1],[3,2,4],[5,6]] Example 2: Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]   Constraints: The height of the n-ary tree is less than or equal to 1000 The total number of nodes is between [0, 104]
Medium
[ "tree", "breadth-first-search" ]
/** * // Definition for a Node. * function Node(val,children) { * this.val = val; * this.children = children; * }; */
[ "const levelOrder = function(root) {\n const res = []\n if(root == null) return res\n helper(root, 0, res)\n return res\n};\n\nfunction helper(node, index, res) {\n if(node == null) return\n if(res[index] == null) res[index] = []\n res[index].push(node.val)\n for(let i = 0, len = node.children.length; i < len; i++) {\n helper(node.children[i], index + 1, res)\n }\n}", "const levelOrder = function(root) {\n const res = []\n if(root == null) return res\n const q = []\n q.push(root)\n while(q.length) {\n const size = q.length\n const cur = []\n for(let i = 0; i < size; i++) {\n const node = q.shift()\n cur.push(node.val)\n q.push(...node.children)\n }\n res.push(cur)\n }\n return res\n};" ]
430
flatten-a-multilevel-doubly-linked-list
[]
/** * // Definition for a Node. * function Node(val,prev,next,child) { * this.val = val; * this.prev = prev; * this.next = next; * this.child = child; * }; */ /** * @param {Node} head * @return {Node} */ var flatten = function(head) { };
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null.   Example 1: Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] Output: [1,2,3,7,8,11,12,9,10,4,5,6] Explanation: The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: Example 2: Input: head = [1,2,null,3] Output: [1,3,2] Explanation: The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: Example 3: Input: head = [] Output: [] Explanation: There could be empty list in the input.   Constraints: The number of Nodes will not exceed 1000. 1 <= Node.val <= 105   How the multilevel linked list is represented in test cases: We use the multilevel linked list from Example 1 above: 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL The serialization of each level is as follows: [1,2,3,4,5,6,null] [7,8,9,10,null] [11,12,null] To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes: [1, 2, 3, 4, 5, 6, null] | [null, null, 7, 8, 9, 10, null] | [ null, 11, 12, null] Merging the serialization of each level and removing trailing nulls we obtain: [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Medium
[ "linked-list", "depth-first-search", "doubly-linked-list" ]
/** * // Definition for a Node. * function Node(val,prev,next,child) { * this.val = val; * this.prev = prev; * this.next = next; * this.child = child; * }; */
[ "const flatten = function (head) {\n const handle = (node, next = null) => {\n if (!node) return null;\n handle(node.next, next);\n const child = handle(node.child, node.next);\n if (!node.next && next) {\n node.next = next;\n next.prev = node;\n }\n if (child) {\n node.next = child;\n node.child = null;\n child.prev = node;\n }\n return node;\n };\n return handle(head);\n};" ]
432
all-oone-data-structure
[]
var AllOne = function() { }; /** * @param {string} key * @return {void} */ AllOne.prototype.inc = function(key) { }; /** * @param {string} key * @return {void} */ AllOne.prototype.dec = function(key) { }; /** * @return {string} */ AllOne.prototype.getMaxKey = function() { }; /** * @return {string} */ AllOne.prototype.getMinKey = function() { }; /** * Your AllOne object will be instantiated and called as such: * var obj = new AllOne() * obj.inc(key) * obj.dec(key) * var param_3 = obj.getMaxKey() * var param_4 = obj.getMinKey() */
Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: AllOne() Initializes the object of the data structure. inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure, insert it with count 1. dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement. getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string "". getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string "". Note that each function must run in O(1) average time complexity.   Example 1: Input ["AllOne", "inc", "inc", "getMaxKey", "getMinKey", "inc", "getMaxKey", "getMinKey"] [[], ["hello"], ["hello"], [], [], ["leet"], [], []] Output [null, null, null, "hello", "hello", null, "hello", "leet"] Explanation AllOne allOne = new AllOne(); allOne.inc("hello"); allOne.inc("hello"); allOne.getMaxKey(); // return "hello" allOne.getMinKey(); // return "hello" allOne.inc("leet"); allOne.getMaxKey(); // return "hello" allOne.getMinKey(); // return "leet"   Constraints: 1 <= key.length <= 10 key consists of lowercase English letters. It is guaranteed that for each call to dec, key is existing in the data structure. At most 5 * 104 calls will be made to inc, dec, getMaxKey, and getMinKey.
Hard
[ "hash-table", "linked-list", "design", "doubly-linked-list" ]
[ "const AllOne = function() {\n this.map = new Map()\n}\n\n\nAllOne.prototype.inc = function(key) {\n let curCount\n if (this.map.has(key)) {\n curCount = this.map.get(key) + 1\n } else {\n curCount = 1\n }\n this.map.set(key, curCount)\n}\n\n\nAllOne.prototype.dec = function(key) {\n if (this.map.has(key)) {\n if (this.map.get(key) > 1) {\n this.map.set(key, this.map.get(key) - 1)\n } else this.map.delete(key)\n } else {\n return\n }\n}\n\n\nAllOne.prototype.getMaxKey = function() {\n let max = -Infinity,\n maxStr = ''\n for (let k of this.map) {\n if (k[1] > max) {\n max = k[1]\n maxStr = k[0]\n }\n }\n return maxStr\n}\n\n\nAllOne.prototype.getMinKey = function() {\n let min = Infinity,\n minStr = ''\n for (let k of this.map) {\n if (k[1] < min) {\n min = k[1]\n minStr = k[0]\n }\n }\n return minStr\n}" ]
433
minimum-genetic-mutation
[]
/** * @param {string} startGene * @param {string} endGene * @param {string[]} bank * @return {number} */ var minMutation = function(startGene, endGene, bank) { };
A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'. Suppose we need to investigate a mutation from a gene string startGene to a gene string endGene where one mutation is defined as one single character changed in the gene string. For example, "AACCGGTT" --> "AACCGGTA" is one mutation. There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string. Given the two gene strings startGene and endGene and the gene bank bank, return the minimum number of mutations needed to mutate from startGene to endGene. If there is no such a mutation, return -1. Note that the starting point is assumed to be valid, so it might not be included in the bank.   Example 1: Input: startGene = "AACCGGTT", endGene = "AACCGGTA", bank = ["AACCGGTA"] Output: 1 Example 2: Input: startGene = "AACCGGTT", endGene = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"] Output: 2   Constraints: 0 <= bank.length <= 10 startGene.length == endGene.length == bank[i].length == 8 startGene, endGene, and bank[i] consist of only the characters ['A', 'C', 'G', 'T'].
Medium
[ "hash-table", "string", "breadth-first-search" ]
[ "const minMutation = function(start, end, bank) {\n const obj = { res: Number.MAX_VALUE }\n dfs(start, end, bank, 0, obj, new Set())\n return obj.res === Number.MAX_VALUE ? -1 : obj.res\n}\n\nfunction dfs(s, e, bank, num, obj, visited) {\n if(s === e) {\n obj.res = Math.min(obj.res, num)\n return\n }\n for(let el of bank) {\n let diff = 0\n for(let i = 0, len = s.length; i < len; i++) {\n if(s[i] !== el[i]) {\n diff++\n if(diff > 1) break\n }\n }\n if(diff === 1 && !visited.has(el)) {\n visited.add(el)\n dfs(el, e, bank, num + 1, obj, visited)\n visited.delete(el)\n }\n }\n} ", "const minMutation = function(start, end, bank) {\n const bankSet = new Set(bank)\n if (!bankSet.has(end)) return -1\n const queue = [[start, 0]]\n const dna = ['A', 'C', 'G', 'T']\n while (queue.length) {\n let [node, count] = queue.shift()\n if (node === end) return count\n for (let i = 0; i < node.length; i++) {\n for (let j = 0; j < dna.length; j++) {\n const d = node.slice(0, i) + dna[j] + node.slice(i + 1)\n if (bankSet.has(d)) {\n queue.push([d, count + 1])\n bankSet.delete(d)\n }\n }\n }\n }\n return -1\n}" ]
434
number-of-segments-in-a-string
[]
/** * @param {string} s * @return {number} */ var countSegments = function(s) { };
Given a string s, return the number of segments in the string. A segment is defined to be a contiguous sequence of non-space characters.   Example 1: Input: s = "Hello, my name is John" Output: 5 Explanation: The five segments are ["Hello,", "my", "name", "is", "John"] Example 2: Input: s = "Hello" Output: 1   Constraints: 0 <= s.length <= 300 s consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#$%^&*()_+-=',.:". The only space character in s is ' '.
Easy
[ "string" ]
[ "const countSegments = function(s) {\n if(s.trim() === '') return 0\n return s.trim().split(' ').filter(el => el !== '').length\n};" ]
435
non-overlapping-intervals
[]
/** * @param {number[][]} intervals * @return {number} */ var eraseOverlapIntervals = function(intervals) { };
Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.   Example 1: Input: intervals = [[1,2],[2,3],[3,4],[1,3]] Output: 1 Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping. Example 2: Input: intervals = [[1,2],[1,2],[1,2]] Output: 2 Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping. Example 3: Input: intervals = [[1,2],[2,3]] Output: 0 Explanation: You don't need to remove any of the intervals since they're already non-overlapping.   Constraints: 1 <= intervals.length <= 105 intervals[i].length == 2 -5 * 104 <= starti < endi <= 5 * 104
Medium
[ "array", "dynamic-programming", "greedy", "sorting" ]
[ "const eraseOverlapIntervals = function(intervals) {\n if(intervals == null || intervals.length === 0) return 0\n intervals.sort((a, b) => a[1] - b[1])\n let res = 1, end = intervals[0][1]\n const len = intervals.length\n for(let i = 1; i < len; i++) {\n if(intervals[i][0] >= end) {\n end = intervals[i][1]\n res++\n }\n }\n \n return len - res\n};", "const eraseOverlapIntervals = function(intervals) {\n intervals.sort((a, b) => a.end - b.end)\n let count = 0\n let end = Number.MIN_SAFE_INTEGER\n const len = intervals.length\n for(let el of intervals) {\n if(el.start >= end) {\n end = el.end\n count++\n }\n }\n return len - count\n};" ]
436
find-right-interval
[]
/** * @param {number[][]} intervals * @return {number[]} */ var findRightInterval = function(intervals) { };
You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique. The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j. Return an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i.   Example 1: Input: intervals = [[1,2]] Output: [-1] Explanation: There is only one interval in the collection, so it outputs -1. Example 2: Input: intervals = [[3,4],[2,3],[1,2]] Output: [-1,0,1] Explanation: There is no right interval for [3,4]. The right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3. The right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2. Example 3: Input: intervals = [[1,4],[2,3],[3,4]] Output: [-1,2,-1] Explanation: There is no right interval for [1,4] and [3,4]. The right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3.   Constraints: 1 <= intervals.length <= 2 * 104 intervals[i].length == 2 -106 <= starti <= endi <= 106 The start point of each interval is unique.
Medium
[ "array", "binary-search", "sorting" ]
[ "const findRightInterval = function(intervals) {\n const res = []\n const arrary = intervals\n .map((interval, idx) => ({ interval, idx }))\n .sort((obj1, obj2) => obj1.interval[0] - obj2.interval[0])\n for (let interval of intervals) {\n const val = interval[interval.length - 1]\n let left = 0,\n right = intervals.length\n while (left < right) {\n const mid = Math.floor((left + right) / 2)\n if (arrary[mid].interval[0] >= val) {\n right = mid\n } else {\n left = mid + 1\n }\n }\n if (left >= intervals.length) {\n res.push(-1)\n } else {\n res.push(arrary[left].idx)\n }\n }\n return res\n}" ]
437
path-sum-iii
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} targetSum * @return {number} */ var pathSum = function(root, targetSum) { };
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).   Example 1: Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 Output: 3 Explanation: The paths that sum to 8 are shown. Example 2: Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: 3   Constraints: The number of nodes in the tree is in the range [0, 1000]. -109 <= Node.val <= 109 -1000 <= targetSum <= 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) * } */
[ "function pathSum(root, sum) {\n const preSums = new Map([[0, 1]]);\n let count = 0;\n visit(root, 0);\n return count;\n \n function visit(node, preSum) {\n if (!node) return;\n preSum += node.val;\n count += preSums.get(preSum - sum) || 0;\n preSums.set(preSum, (preSums.get(preSum) || 0) + 1);\n visit(node.left, preSum);\n visit(node.right, preSum);\n preSums.set(preSum, preSums.get(preSum) - 1);\n }\n}" ]
438
find-all-anagrams-in-a-string
[]
/** * @param {string} s * @param {string} p * @return {number[]} */ var findAnagrams = function(s, p) { };
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.   Example 1: Input: s = "cbaebabacd", p = "abc" Output: [0,6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". Example 2: Input: s = "abab", p = "ab" Output: [0,1,2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab".   Constraints: 1 <= s.length, p.length <= 3 * 104 s and p consist of lowercase English letters.
Medium
[ "hash-table", "string", "sliding-window" ]
[ "const findAnagrams = function (s, p) {\n const slen = s.length;\n const plen = p.length;\n if (plen > slen) return [];\n const aCode = \"a\".charCodeAt(0);\n const count = new Array(26).fill(0);\n for (let i = 0; i < plen; i++) count[p.charCodeAt(i) - aCode] += 1;\n const res = [];\n for (let i = 0; i < slen; i++) {\n count[s.charCodeAt(i) - aCode] -= 1;\n if (i >= plen - 1) {\n if (i - plen >= 0) count[s.charCodeAt(i - plen) - aCode] += 1;\n if (allZero(count)) res.push(i - plen + 1);\n }\n }\n return res;\n};\nfunction allZero(count) {\n for (let el of count) {\n if (el !== 0) return false;\n }\n return true;\n}" ]
440
k-th-smallest-in-lexicographical-order
[]
/** * @param {number} n * @param {number} k * @return {number} */ var findKthNumber = function(n, k) { };
Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n].   Example 1: Input: n = 13, k = 2 Output: 10 Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. Example 2: Input: n = 1, k = 1 Output: 1   Constraints: 1 <= k <= n <= 109
Hard
[ "trie" ]
[ "const findKthNumber = function (n, k) {\n let cur = 1\n k = k - 1\n while(k > 0) {\n const num = calc(cur)\n if(num <= k) {\n cur++\n k -= num\n } else {\n k--\n cur *= 10\n }\n }\n return cur\n \n function calc(cur) {\n let total = 0\n let nxt = cur + 1\n while(cur <= n) {\n total += Math.min(n - cur + 1, nxt - cur)\n nxt *= 10\n cur *= 10\n }\n \n return total\n }\n}", "const findKthNumber = function (n, k) {\n let curr = 1\n k = k - 1\n while (k > 0) {\n let steps = calSteps(n, curr, curr + 1)\n if (steps <= k) {\n curr += 1\n k -= steps\n } else {\n curr *= 10\n k -= 1\n }\n }\n return curr\n\n function calSteps(n, n1, n2) {\n let steps = 0\n while (n1 <= n) {\n steps += Math.min(n + 1, n2) - n1\n n1 *= 10\n n2 *= 10\n }\n return steps\n }\n}" ]
441
arranging-coins
[]
/** * @param {number} n * @return {number} */ var arrangeCoins = function(n) { };
You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n, return the number of complete rows of the staircase you will build.   Example 1: Input: n = 5 Output: 2 Explanation: Because the 3rd row is incomplete, we return 2. Example 2: Input: n = 8 Output: 3 Explanation: Because the 4th row is incomplete, we return 3.   Constraints: 1 <= n <= 231 - 1
Easy
[ "math", "binary-search" ]
[ "const arrangeCoins = function(n) {\n if (n === 0) {\n return 0\n }\n let num = 1\n let sum = 1\n while(n >= sum + num + 1) {\n num += 1\n sum += num\n }\n\n return num\n};", "const arrangeCoins = function(n) {\n return (-1 + Math.sqrt(1+4*2*n)) >> 1\n};" ]
442
find-all-duplicates-in-an-array
[]
/** * @param {number[]} nums * @return {number[]} */ var findDuplicates = function(nums) { };
Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice. You must write an algorithm that runs in O(n) time and uses only constant extra space.   Example 1: Input: nums = [4,3,2,7,8,2,3,1] Output: [2,3] Example 2: Input: nums = [1,1,2] Output: [1] Example 3: Input: nums = [1] Output: []   Constraints: n == nums.length 1 <= n <= 105 1 <= nums[i] <= n Each element in nums appears once or twice.
Medium
[ "array", "hash-table" ]
[ "const findDuplicates = function(nums) {\n if (nums === null || nums.length <= 1) {\n return [];\n }\n\n let dup = [];\n for (let i = 0, n = nums.length; i < n; i++) {\n let next = Math.abs(nums[i]);\n nums[next - 1] < 0 ? dup.push(next) : (nums[next - 1] = -nums[next - 1]);\n }\n\n return dup;\n};\n\nconsole.log(findDuplicates([4, 3, 2, 7, 8, 2, 3, 1]));\nconsole.log(findDuplicates([10, 2, 5, 10, 9, 1, 1, 4, 3, 7]));", "const findDuplicates = function(nums) {\n const res = []\n for(let i = 0, len = nums.length; i < len; i++) {\n const idx = Math.abs(nums[i]) - 1\n if(nums[idx] < 0) res.push(idx + 1)\n nums[idx] = -nums[idx]\n }\n return res;\n};" ]
443
string-compression
[ "How do you know if you are at the end of a consecutive group of characters?" ]
/** * @param {character[]} chars * @return {number} */ var compress = function(chars) { };
Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: If the group's length is 1, append the character to s. Otherwise, append the character followed by the group's length. The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars. After you are done modifying the input array, return the new length of the array. You must write an algorithm that uses only constant extra space.   Example 1: Input: chars = ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3". Example 2: Input: chars = ["a"] Output: Return 1, and the first character of the input array should be: ["a"] Explanation: The only group is "a", which remains uncompressed since it's a single character. Example 3: Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"] Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".   Constraints: 1 <= chars.length <= 2000 chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.
Medium
[ "two-pointers", "string" ]
[ "const compress = function(chars) {\n let indexAns = 0\n let index = 0\n while(index < chars.length) {\n let currentChar = chars[index]\n let count = 0\n while(index < chars.length && chars[index] === currentChar) {\n index++\n count++\n }\n chars[indexAns++] = currentChar\n if(count !== 1) {\n for(let el of (''+count).split('')) {\n chars[indexAns++] = el\n }\n }\n }\n return indexAns\n};" ]
445
add-two-numbers-ii
[]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var addTwoNumbers = function(l1, l2) { };
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself.   Example 1: Input: l1 = [7,2,4,3], l2 = [5,6,4] Output: [7,8,0,7] Example 2: Input: l1 = [2,4,3], l2 = [5,6,4] Output: [8,0,7] Example 3: Input: l1 = [0], l2 = [0] Output: [0]   Constraints: The number of nodes in each linked list is in the range [1, 100]. 0 <= Node.val <= 9 It is guaranteed that the list represents a number that does not have leading zeros.   Follow up: Could you solve it without reversing the input lists?
Medium
[ "linked-list", "math", "stack" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "const addTwoNumbers = function(head1, head2) {\n const r1 = reverse(head1), r2 = reverse(head2)\n let l1 = r1, l2 = r2, inc = 0\n let dummy = new ListNode()\n let pre = dummy\n while(l1 || l2) {\n let val = inc\n if(l1) {\n val += l1.val\n l1 = l1.next\n }\n if(l2) {\n val += l2.val\n l2 = l2.next\n }\n if(val > 9) inc = 1\n else inc = 0\n const cur = new ListNode(val % 10)\n pre.next = cur\n pre = cur\n }\n if (inc) {\n pre.next = new ListNode(1)\n }\n return reverse(dummy.next) \n};\n\nfunction reverse(head) {\n const dummy = new ListNode()\n dummy.next = head\n let len = 0, cur = head\n while(cur) {\n len++\n cur = cur.next\n }\n let p = dummy, tail = head, tmp = null\n for(let i = 0; i < len - 1; i++) {\n tmp = p.next\n p.next = tail.next\n tail.next = tail.next.next\n p.next.next = tmp\n }\n return dummy.next\n}", "const addTwoNumbers = function(l1, l2) {\n const s1 = [];\n const s2 = [];\n while (l1 !== null) {\n s1.push(l1.val);\n l1 = l1.next;\n }\n while (l2 !== null) {\n s2.push(l2.val);\n l2 = l2.next;\n }\n\n let list = new ListNode(0);\n let sum = 0;\n while (s1.length > 0 || s2.length > 0) {\n if (s1.length > 0) {\n sum += s1.pop();\n }\n if (s2.length > 0) {\n sum += s2.pop();\n }\n list.val = sum % 10;\n const head = new ListNode(Math.floor(sum / 10));\n head.next = list;\n list = head;\n sum = Math.floor(sum / 10);\n }\n\n return list.val === 0 ? list.next : list;\n};", "const addTwoNumbers = function(l1, l2) {\n const s1 = [], s2 = []\n let h1 = l1, h2 = l2\n while(h1) {\n s1.push(h1.val)\n h1 = h1.next\n }\n while(h2) {\n s2.push(h2.val)\n h2 = h2.next\n }\n let inc = false\n let tail = null\n while(s1.length || s2.length) {\n let tmp = 0\n if(s1.length) tmp += s1.pop()\n if(s2.length) tmp += s2.pop()\n if(inc) tmp++\n if(tmp > 9) {\n inc = true\n } else {\n inc = false\n }\n tmp = tmp % 10\n const cur = new ListNode(tmp)\n if(tail) cur.next = tail\n tail = cur\n }\n \n if(inc) {\n const head = new ListNode(1)\n head.next = tail\n return head\n }\n return tail\n \n};" ]
446
arithmetic-slices-ii-subsequence
[]
/** * @param {number[]} nums * @return {number} */ var numberOfArithmeticSlices = function(nums) { };
Given an integer array nums, return the number of all the arithmetic subsequences of nums. A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences. For example, [1, 1, 2, 5, 7] is not an arithmetic sequence. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10]. The test cases are generated so that the answer fits in 32-bit integer.   Example 1: Input: nums = [2,4,6,8,10] Output: 7 Explanation: All arithmetic subsequence slices are: [2,4,6] [4,6,8] [6,8,10] [2,4,6,8] [4,6,8,10] [2,4,6,8,10] [2,6,10] Example 2: Input: nums = [7,7,7,7,7] Output: 16 Explanation: Any subsequence of this array is arithmetic.   Constraints: 1  <= nums.length <= 1000 -231 <= nums[i] <= 231 - 1
Hard
[ "array", "dynamic-programming" ]
[ "const numberOfArithmeticSlices = function(A) {\n if (!A || A.length < 3) return 0;\n let res = 0;\n const dp = Array(A.length);\n for (let i = 0; i < A.length; i++) {\n dp[i] = new Map();\n for (let j = 0; j < i; j++) {\n const diff = A[i] - A[j];\n const prevCount = dp[j].get(diff) || 0;\n res += prevCount;\n const currCount = (dp[i].get(diff) || 0) + 1;\n dp[i].set(diff, prevCount + currCount);\n }\n }\n return res;\n};" ]
447
number-of-boomerangs
[]
/** * @param {number[][]} points * @return {number} */ var numberOfBoomerangs = function(points) { };
You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Return the number of boomerangs.   Example 1: Input: points = [[0,0],[1,0],[2,0]] Output: 2 Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]. Example 2: Input: points = [[1,1],[2,2],[3,3]] Output: 2 Example 3: Input: points = [[1,1]] Output: 0   Constraints: n == points.length 1 <= n <= 500 points[i].length == 2 -104 <= xi, yi <= 104 All the points are unique.
Medium
[ "array", "hash-table", "math" ]
[ "const numberOfBoomerangs = function(points) {\n const m = new Map()\n const len = points.length\n let res = 0\n for(let i = 0; i < len; i++) {\n for(let j = 0; j < len; j++) {\n if(i === j) continue\n const d = dis(points[i], points[j])\n if(!m.has(d)) m.set(d, 0)\n m.set(d, m.get(d) + 1)\n }\n for(let v of m.values()) {\n res += v * (v - 1)\n }\n m.clear()\n }\n return res\n};\n\nfunction dis(a, b) {\n return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2\n}" ]
448
find-all-numbers-disappeared-in-an-array
[ "This is a really easy problem if you decide to use additional memory. For those trying to write an initial solution using additional memory, think <b>counters!</b>", "However, the trick really is to not use any additional space than what is already available to use. Sometimes, multiple passes over the input array help find the solution. However, there's an interesting piece of information in this problem that makes it easy to re-use the input array itself for the solution.", "The problem specifies that the numbers in the array will be in the range [1, n] where n is the number of elements in the array. Can we use this information and modify the array in-place somehow to find what we need?" ]
/** * @param {number[]} nums * @return {number[]} */ var findDisappearedNumbers = function(nums) { };
Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.   Example 1: Input: nums = [4,3,2,7,8,2,3,1] Output: [5,6] Example 2: Input: nums = [1,1] Output: [2]   Constraints: n == nums.length 1 <= n <= 105 1 <= nums[i] <= n   Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Easy
[ "array", "hash-table" ]
[ "const findDisappearedNumbers = function(nums) {\n const res = [];\n nums.forEach((el, idx) => {\n res[el - 1] = 1;\n });\n const arr = [];\n for (let i = 0; i < nums.length; i++) {\n if (res[i] == null) {\n arr.push(i + 1);\n }\n }\n return arr;\n};", "const findDisappearedNumbers = function(nums) {\n for(let i = 0, len = nums.length; i < len; i++) {\n const idx = Math.abs(nums[i]) - 1\n nums[idx] = - Math.abs(nums[idx])\n }\n const res = []\n nums.forEach((e, i) => {\n if(e > 0) res.push(i + 1)\n })\n return res\n};" ]
449
serialize-and-deserialize-bst
[]
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * Encodes a tree to a single string. * * @param {TreeNode} root * @return {string} */ var serialize = function(root) { }; /** * Decodes your encoded data to tree. * * @param {string} data * @return {TreeNode} */ var deserialize = function(data) { }; /** * Your functions will be called as such: * deserialize(serialize(root)); */
Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure. The encoded string should be as compact as possible.   Example 1: Input: root = [2,1,3] Output: [2,1,3] Example 2: Input: root = [] Output: []   Constraints: The number of nodes in the tree is in the range [0, 104]. 0 <= Node.val <= 104 The input tree is guaranteed to be a binary search tree.
Medium
[ "string", "tree", "depth-first-search", "breadth-first-search", "design", "binary-search-tree", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */
[ "const splitter = \",\";\n\nconst serialize = function(root) {\n const sb = [];\n buildString(root, sb);\n sb.pop();\n return sb.join(\"\");\n};\nfunction buildString(node, sb) {\n if (node == null) return;\n sb.push(node.val);\n sb.push(splitter);\n buildString(node.left, sb);\n buildString(node.right, sb);\n}\n\nconst deserialize = function(data) {\n if (data.length === 0) return null;\n const pos = [0];\n return buildTree(\n data.split(splitter),\n pos,\n Number.MIN_SAFE_INTEGER,\n Number.MAX_SAFE_INTEGER\n );\n};\nfunction buildTree(nodes, pos, min, max) {\n if (pos[0] === nodes.length) return null;\n let val = +nodes[pos[0]];\n if (val < min || val > max) return null;\n const cur = new TreeNode(val);\n pos[0] += 1;\n cur.left = buildTree(nodes, pos, min, val);\n cur.right = buildTree(nodes, pos, val, max);\n return cur;\n}" ]
450
delete-node-in-a-bst
[]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} key * @return {TreeNode} */ var deleteNode = function(root, key) { };
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node.   Example 1: Input: root = [5,3,6,2,4,null,7], key = 3 Output: [5,4,6,2,null,null,7] Explanation: Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the above BST. Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted. Example 2: Input: root = [5,3,6,2,4,null,7], key = 0 Output: [5,3,6,2,4,null,7] Explanation: The tree does not contain a node with value = 0. Example 3: Input: root = [], key = 0 Output: []   Constraints: The number of nodes in the tree is in the range [0, 104]. -105 <= Node.val <= 105 Each node has a unique value. root is a valid binary search tree. -105 <= key <= 105   Follow up: Could you solve it with time complexity O(height of tree)?
Medium
[ "tree", "binary-search-tree", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const deleteNode = function(root, key) {\n if(root == null) return null\n if(key < root.val) {\n root.left = deleteNode(root.left, key)\n } else if(key > root.val) {\n root.right = deleteNode(root.right, key)\n } else {\n if(root.left == null) {\n return root.right\n } else if(root.right == null) {\n return root.left\n } else {\n let smallestRight = root.right\n while(smallestRight.left !== null) smallestRight = smallestRight.left\n smallestRight.left = root.left\n return root.right\n }\n }\n \n return root\n};", "const deleteNode = function(root, key) {\n if(root == null) return root\n\n if(root.val < key) root.right = deleteNode(root.right, key)\n else if(root.val > key) root.left = deleteNode(root.left, key)\n else {\n if(root.left == null && root.right === null) root = null\n else if(root.left == null) root = root.right\n else if(root.right == null) root = root.left\n else {\n const min = findMin(root.right)\n root.val = min.val\n root.right = deleteNode(root.right, root.val)\n }\n }\n\n return root\n};\n\nfunction findMin(node) {\n let cur = node\n while(cur.left) {\n cur = cur.left\n }\n return cur\n}" ]
451
sort-characters-by-frequency
[]
/** * @param {string} s * @return {string} */ var frequencySort = function(s) { };
Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers, return any of them.   Example 1: Input: s = "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: s = "cccaaa" Output: "aaaccc" Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: s = "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters.   Constraints: 1 <= s.length <= 5 * 105 s consists of uppercase and lowercase English letters and digits.
Medium
[ "hash-table", "string", "sorting", "heap-priority-queue", "bucket-sort", "counting" ]
[ "const frequencySort = function(s) {\n const charMap = {};\n for (let i = 0; i < s.length; i++) {\n const index = s.charAt(i);\n charMap[index] = (charMap[index] || 0) + 1;\n }\n return Object.entries(charMap)\n .sort((a, b) => {\n return b[1] - a[1];\n })\n .map(x => {\n return x[0].repeat(x[1]);\n })\n .join(\"\");\n};" ]
452
minimum-number-of-arrows-to-burst-balloons
[]
/** * @param {number[][]} points * @return {number} */ var findMinArrowShots = function(points) { };
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons. Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points, return the minimum number of arrows that must be shot to burst all balloons.   Example 1: Input: points = [[10,16],[2,8],[1,6],[7,12]] Output: 2 Explanation: The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. Example 2: Input: points = [[1,2],[3,4],[5,6],[7,8]] Output: 4 Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows. Example 3: Input: points = [[1,2],[2,3],[3,4],[4,5]] Output: 2 Explanation: The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].   Constraints: 1 <= points.length <= 105 points[i].length == 2 -231 <= xstart < xend <= 231 - 1
Medium
[ "array", "greedy", "sorting" ]
[ "const findMinArrowShots = function(points) {\n const sorted = points.sort((a, b) => a[0] - b[0])\n let ans = 0\n let lastX = null\n for (let i = 0; i < sorted.length; i += 1) {\n if (lastX && sorted[i][0] <= lastX) {\n lastX = Math.min(sorted[i][1], lastX)\n } else {\n ans += 1\n lastX = sorted[i][1]\n }\n }\n return ans\n}", "const findMinArrowShots = function(points) {\n if(points == null || points.length === 0) return 0\n points.sort((a, b) => a[1] - b[1])\n let end = points[0][1], res = 1\n for(let i = 1, len = points.length; i < len; i++) {\n if(points[i][0] > end) {\n end = points[i][1]\n res++\n }\n }\n return res\n};" ]
453
minimum-moves-to-equal-array-elements
[]
/** * @param {number[]} nums * @return {number} */ var minMoves = function(nums) { };
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment n - 1 elements of the array by 1.   Example 1: Input: nums = [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] Example 2: Input: nums = [1,1,1] Output: 0   Constraints: n == nums.length 1 <= nums.length <= 105 -109 <= nums[i] <= 109 The answer is guaranteed to fit in a 32-bit integer.
Medium
[ "array", "math" ]
[ "const minMoves = function(nums) {\n let min = Number.MAX_SAFE_INTEGER;\n let sum = 0;\n for (let i = 0; i < nums.length; i++) {\n min = Math.min(min, nums[i]);\n sum += nums[i];\n }\n return sum - min * nums.length;\n};" ]
454
4sum-ii
[]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @param {number[]} nums3 * @param {number[]} nums4 * @return {number} */ var fourSumCount = function(nums1, nums2, nums3, nums4) { };
Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that: 0 <= i, j, k, l < n nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0   Example 1: Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] Output: 2 Explanation: The two tuples are: 1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 Example 2: Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] Output: 1   Constraints: n == nums1.length n == nums2.length n == nums3.length n == nums4.length 1 <= n <= 200 -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
Medium
[ "array", "hash-table" ]
[ "const fourSumCount = function(A, B, C, D) {\n const map = new Map()\n let res = 0\n for (let i = 0, clen = C.length; i < clen; i++) {\n for (let j = 0, dlen = D.length; j < dlen; j++) {\n map.set(\n C[i] + D[j],\n typeof map.get(C[i] + D[j]) == 'undefined'\n ? 1\n : map.get(C[i] + D[j]) + 1\n )\n }\n }\n for (let i = 0, alen = A.length; i < alen; i++) {\n for (let j = 0, blen = B.length; j < blen; j++) {\n res +=\n typeof map.get((A[i] + B[j]) * -1) == 'undefined'\n ? 0\n : map.get((A[i] + B[j]) * -1)\n }\n }\n return res\n}" ]
455
assign-cookies
[]
/** * @param {number[]} g * @param {number[]} s * @return {number} */ var findContentChildren = function(g, s) { };
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.   Example 1: Input: g = [1,2,3], s = [1,1] Output: 1 Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. Example 2: Input: g = [1,2], s = [1,2,3] Output: 2 Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2.   Constraints: 1 <= g.length <= 3 * 104 0 <= s.length <= 3 * 104 1 <= g[i], s[j] <= 231 - 1
Easy
[ "array", "two-pointers", "greedy", "sorting" ]
[ "const findContentChildren = function(g, s) {\n s.sort((a, b) => a - b);\n g.sort((a, b) => a - b);\n\n let i = 0;\n for (let j = 0; i < g.length && j < s.length; j++) {\n if (g[i] <= s[j]) i++;\n }\n return i;\n};" ]
456
132-pattern
[]
/** * @param {number[]} nums * @return {boolean} */ var find132pattern = function(nums) { };
Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. Return true if there is a 132 pattern in nums, otherwise, return false.   Example 1: Input: nums = [1,2,3,4] Output: false Explanation: There is no 132 pattern in the sequence. Example 2: Input: nums = [3,1,4,2] Output: true Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. Example 3: Input: nums = [-1,3,2,0] Output: true Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].   Constraints: n == nums.length 1 <= n <= 2 * 105 -109 <= nums[i] <= 109
Medium
[ "array", "binary-search", "stack", "monotonic-stack", "ordered-set" ]
[ "const find132pattern = function(nums) {\n let [stack, s3] = [[], -Infinity]\n for (let i = nums.length - 1; i >= 0; i--) {\n if (nums[i] < s3) {\n return true\n }\n while (stack[stack.length - 1] < nums[i]) {\n s3 = stack.pop()\n }\n stack.push(nums[i])\n }\n return false\n}", "const find132pattern = function(nums) {\n let idx = nums.length\n let s3 = Number.NEGATIVE_INFINITY\n for(let len = nums.length, i = len - 1; i >= 0; i--) {\n if(nums[i] < s3) return true\n while(idx < nums.length && nums[i] > nums[idx]) {\n s3 = nums[idx++]\n }\n nums[--idx] = nums[i] \n }\n return false\n}" ]
457
circular-array-loop
[]
/** * @param {number[]} nums * @return {boolean} */ var circularArrayLoop = function(nums) { };
You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i: If nums[i] is positive, move nums[i] steps forward, and If nums[i] is negative, move nums[i] steps backward. Since the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element. A cycle in the array consists of a sequence of indices seq of length k where: Following the movement rules above results in the repeating index sequence seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ... Every nums[seq[j]] is either all positive or all negative. k > 1 Return true if there is a cycle in nums, or false otherwise.   Example 1: Input: nums = [2,-1,1,2,2] Output: true Explanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --> 2 --> 3 --> 0 --> ..., and all of its nodes are white (jumping in the same direction). Example 2: Input: nums = [-1,-2,-3,-4,-5,6] Output: false Explanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. The only cycle is of size 1, so we return false. Example 3: Input: nums = [1,-1,5,1,4] Output: true Explanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --> 1 --> 0 --> ..., and while it is of size > 1, it has a node jumping forward and a node jumping backward, so it is not a cycle. We can see the cycle 3 --> 4 --> 3 --> ..., and all of its nodes are white (jumping in the same direction).   Constraints: 1 <= nums.length <= 5000 -1000 <= nums[i] <= 1000 nums[i] != 0   Follow up: Could you solve it in O(n) time complexity and O(1) extra space complexity?
Medium
[ "array", "hash-table", "two-pointers" ]
[ "const circularArrayLoop = function(nums) {\n let n = nums.length;\n for (let i = 0; i < n; i++) {\n if (nums[i] == 0) {\n continue;\n }\n let j = i,\n k = getNextIndex(i, nums);\n while (nums[k] * nums[i] > 0 && nums[getNextIndex(k, nums)] * nums[i] > 0) {\n if (j === k) {\n // check for loop with only one element\n if (j === getNextIndex(j, nums)) {\n break;\n }\n return true;\n }\n j = getNextIndex(j, nums);\n k = getNextIndex(getNextIndex(k, nums), nums);\n }\n // loop not found, set all element along the way to 0\n j = i;\n let val = nums[i];\n while (nums[j] * val > 0) {\n let next = getNextIndex(j, nums);\n nums[j] = 0;\n j = next;\n }\n }\n return false;\n};\n\nfunction getNextIndex(i, nums) {\n const n = nums.length;\n return i + nums[i] >= 0 ? (i + nums[i]) % n : n + ((i + nums[i]) % n);\n}" ]
458
poor-pigs
[ "What if you only have one shot? Eg. 4 buckets, 15 mins to die, and 15 mins to test.", "How many states can we generate with x pigs and T tests?", "Find minimum <code>x</code> such that <code>(T+1)^x >= N</code>" ]
/** * @param {number} buckets * @param {number} minutesToDie * @param {number} minutesToTest * @return {number} */ var poorPigs = function(buckets, minutesToDie, minutesToTest) { };
There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous. You can feed the pigs according to these steps: Choose some live pigs to feed. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs. Wait for minutesToDie minutes. You may not feed any other pigs during this time. After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive. Repeat this process until you run out of time. Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.   Example 1: Input: buckets = 4, minutesToDie = 15, minutesToTest = 15 Output: 2 Explanation: We can determine the poisonous bucket as follows: At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3. At time 15, there are 4 possible outcomes: - If only the first pig dies, then bucket 1 must be poisonous. - If only the second pig dies, then bucket 3 must be poisonous. - If both pigs die, then bucket 2 must be poisonous. - If neither pig dies, then bucket 4 must be poisonous. Example 2: Input: buckets = 4, minutesToDie = 15, minutesToTest = 30 Output: 2 Explanation: We can determine the poisonous bucket as follows: At time 0, feed the first pig bucket 1, and feed the second pig bucket 2. At time 15, there are 2 possible outcomes: - If either pig dies, then the poisonous bucket is the one it was fed. - If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4. At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.   Constraints: 1 <= buckets <= 1000 1 <= minutesToDie <= minutesToTest <= 100
Hard
[ "math", "dynamic-programming", "combinatorics" ]
[ "const poorPigs = function(buckets, minutesToDie, minutesToTest) {\n const index = Math.ceil(minutesToTest / minutesToDie) + 1\n return Math.ceil(Math.log(buckets) / Math.log(index))\n}", "const poorPigs = function(buckets, minutesToDie, minutesToTest) {\n let pigs = 0\n while ((minutesToTest / minutesToDie + 1) ** pigs < buckets) {\n pigs++\n }\n return pigs\n}" ]
459
repeated-substring-pattern
[]
/** * @param {string} s * @return {boolean} */ var repeatedSubstringPattern = function(s) { };
Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.   Example 1: Input: s = "abab" Output: true Explanation: It is the substring "ab" twice. Example 2: Input: s = "aba" Output: false Example 3: Input: s = "abcabcabcabc" Output: true Explanation: It is the substring "abc" four times or the substring "abcabc" twice.   Constraints: 1 <= s.length <= 104 s consists of lowercase English letters.
Easy
[ "string", "string-matching" ]
[ "const repeatedSubstringPattern = function(s) {\n const len = s.length\n let tmp = ''\n for(let i = 1; i <= len; i++) {\n tmp = s.substr(0, i)\n if (tmp.length === len) {\n return false\n }\n if (s === genStr(tmp, len)) {\n return true\n }\n }\n return false\n};\nfunction genStr(sub, limit) {\n let str = sub\n while(str.length < limit) {\n str += sub\n }\n return str\n}", "const repeatedSubstringPattern = function (s) {\n const l = s.length\n const arr = DFA(s)\n return arr[l] && arr[l] % (l - arr[l]) === 0\n function DFA(s) {\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}", "const repeatedSubstringPattern = function(s) {\n let i = 1, j = 0, n = s.length;\n const dp = Array(n + 1).fill(0);\n while( i < s.length ){\n if( s[i] === s[j] ) dp[++i] = ++j;\n else if( j === 0 ) i++;\n else j = dp[j];\n }\n return dp[n] && (dp[n] % (n - dp[n]) === 0); \n};" ]
460
lfu-cache
[]
/** * @param {number} capacity */ var LFUCache = function(capacity) { }; /** * @param {number} key * @return {number} */ LFUCache.prototype.get = function(key) { }; /** * @param {number} key * @param {number} value * @return {void} */ LFUCache.prototype.put = function(key, value) { }; /** * Your LFUCache object will be instantiated and called as such: * var obj = new LFUCache(capacity) * var param_1 = obj.get(key) * obj.put(key,value) */
Design and implement a data structure for a Least Frequently Used (LFU) cache. Implement the LFUCache class: LFUCache(int capacity) Initializes the object with the capacity of the data structure. int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1. void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated. To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key. When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it. The functions get and put must each run in O(1) average time complexity.   Example 1: Input ["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]] Output [null, null, null, 1, null, -1, 3, null, -1, 3, 4] Explanation // cnt(x) = the use counter for key x // cache=[] will show the last used order for tiebreakers (leftmost element is most recent) LFUCache lfu = new LFUCache(2); lfu.put(1, 1); // cache=[1,_], cnt(1)=1 lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1 lfu.get(1); // return 1 // cache=[1,2], cnt(2)=1, cnt(1)=2 lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.   // cache=[3,1], cnt(3)=1, cnt(1)=2 lfu.get(2); // return -1 (not found) lfu.get(3); // return 3 // cache=[3,1], cnt(3)=2, cnt(1)=2 lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1. // cache=[4,3], cnt(4)=1, cnt(3)=2 lfu.get(1); // return -1 (not found) lfu.get(3); // return 3 // cache=[3,4], cnt(4)=1, cnt(3)=3 lfu.get(4); // return 4 // cache=[4,3], cnt(4)=2, cnt(3)=3   Constraints: 1 <= capacity <= 104 0 <= key <= 105 0 <= value <= 109 At most 2 * 105 calls will be made to get and put.    
Hard
[ "hash-table", "linked-list", "design", "doubly-linked-list" ]
[ "const LFUCache = function(capacity) {\n this.min = -1;\n this.capacity = capacity;\n this.keyToVal = {};\n this.keyToCount = {};\n this.countToLRUKeys = {};\n};\n\n\nLFUCache.prototype.get = function(key) {\n if (!this.keyToVal.hasOwnProperty(key)) return -1;\n let count = this.keyToCount[key];\n let idx = this.countToLRUKeys[count].indexOf(key);\n if (idx !== -1) this.countToLRUKeys[count].splice(idx, 1);\n if (count === this.min && this.countToLRUKeys[count].length === 0) this.min++;\n putCount(key, count + 1, this.keyToCount, this.countToLRUKeys);\n return this.keyToVal[key];\n};\n\n\nLFUCache.prototype.put = function(key, value) {\n if (this.capacity <= 0) return;\n\n if (this.keyToVal.hasOwnProperty(key)) {\n this.keyToVal[key] = value; // update key's value\n this.get(key); // update key's count\n return;\n }\n\n if (Object.keys(this.keyToVal).length >= this.capacity) {\n evict(\n this.countToLRUKeys[this.min][0],\n this.min,\n this.keyToVal,\n this.countToLRUKeys\n ); // evict LRU from this min count bucket\n }\n\n this.min = 1;\n putCount(key, this.min, this.keyToCount, this.countToLRUKeys); // adding new key and count\n this.keyToVal[key] = value; // adding new key and value\n};\nfunction evict(key, min, keyToVal, countToLRUKeys) {\n let idx = countToLRUKeys[min].indexOf(key);\n if (idx !== -1) countToLRUKeys[min].splice(idx, 1);\n delete keyToVal[key];\n}\nfunction putCount(key, count, keyToCount, countToLRUKeys) {\n keyToCount[key] = count;\n if (countToLRUKeys.hasOwnProperty(count)) {\n countToLRUKeys[count].push(key);\n } else {\n countToLRUKeys[count] = [key];\n }\n}" ]
461
hamming-distance
[]
/** * @param {number} x * @param {number} y * @return {number} */ var hammingDistance = function(x, y) { };
The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them.   Example 1: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different. Example 2: Input: x = 3, y = 1 Output: 1   Constraints: 0 <= x, y <= 231 - 1
Easy
[ "bit-manipulation" ]
[ "const hammingDistance = function (x, y) {\n let d = 0\n let h = x ^ y\n while (h > 0) {\n d++\n h &= h - 1\n }\n return d\n}", "const hammingDistance = function (x, y) {\n let n = x ^ y\n n = n - ((n >> 1) & 0x55555555)\n n = (n & 0x33333333) + ((n >> 2) & 0x33333333)\n return (((n + (n >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24\n}", "const hammingDistance = function (x, y) {\n let n = x ^ y\n let tmp = n - ((n >> 1) & 033333333333) - ((n >> 2) & 011111111111);\n return ((tmp + (tmp >> 3)) & 030707070707) % 63;\n}\n\n// https://tech.liuchao.me/2016/11/count-bits-of-integer/" ]
462
minimum-moves-to-equal-array-elements-ii
[]
/** * @param {number[]} nums * @return {number} */ var minMoves2 = function(nums) { };
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1. Test cases are designed so that the answer will fit in a 32-bit integer.   Example 1: Input: nums = [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2] Example 2: Input: nums = [1,10,2,9] Output: 16   Constraints: n == nums.length 1 <= nums.length <= 105 -109 <= nums[i] <= 109
Medium
[ "array", "math", "sorting" ]
[ "const minMoves2 = function(nums) {\n nums.sort((a, b) => a - b);\n let i = 0,\n j = nums.length - 1;\n let res = 0;\n while (i < j) {\n res += nums[j] - nums[i];\n i++;\n j--;\n }\n return res;\n};" ]
463
island-perimeter
[]
/** * @param {number[][]} grid * @return {number} */ var islandPerimeter = function(grid) { };
You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.   Example 1: Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]] Output: 16 Explanation: The perimeter is the 16 yellow stripes in the image above. Example 2: Input: grid = [[1]] Output: 4 Example 3: Input: grid = [[1,0]] Output: 4   Constraints: row == grid.length col == grid[i].length 1 <= row, col <= 100 grid[i][j] is 0 or 1. There is exactly one island in grid.
Easy
[ "array", "depth-first-search", "breadth-first-search", "matrix" ]
[ "const islandPerimeter = function(grid) {\n let len = 0;\n for (let r = 0; r < grid.length; r++) {\n for (let c = 0; c < grid[0].length; c++) {\n if (grid[r][c] === 1) {\n len += cell(grid, r, c);\n }\n }\n }\n return len;\n};\n\nfunction cell(grid, r, c) {\n let len = 0;\n // top\n if (r === 0 || grid[r - 1][c] !== 1) {\n len += 1;\n }\n // left\n if (c === 0 || grid[r][c - 1] !== 1) {\n len += 1;\n }\n // right\n if (grid[r][c + 1] !== 1) {\n len += 1;\n }\n // bottom\n if (grid[r + 1] == null || grid[r + 1][c] !== 1) {\n len += 1;\n }\n return len;\n}\n\nconsole.log(\n islandPerimeter([[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]])\n);", "const islandPerimeter = function(grid) {\n const m = grid.length\n const n = grid[0].length\n const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n let r = 0\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j] === 1) r += h(i, j)\n }\n }\n \n return r\n \n function h(i, j) {\n let res = 0\n for(let d of dirs) {\n const nr = i + d[0]\n const nc = j + d[1]\n if(nr < 0 || nc < 0 || nr >= m || nc >= n || grid[nr][nc] === 0) res++\n }\n return res\n }\n};" ]
464
can-i-win
[]
/** * @param {number} maxChoosableInteger * @param {number} desiredTotal * @return {boolean} */ var canIWin = function(maxChoosableInteger, desiredTotal) { };
In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins. What if we change the game so that players cannot re-use integers? For example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total >= 100. Given two integers maxChoosableInteger and desiredTotal, return true if the first player to move can force a win, otherwise, return false. Assume both players play optimally.   Example 1: Input: maxChoosableInteger = 10, desiredTotal = 11 Output: false Explanation: No matter which integer the first player choose, the first player will lose. The first player can choose an integer from 1 up to 10. If the first player choose 1, the second player can only choose integers from 2 up to 10. The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal. Same with other integers chosen by the first player, the second player will always win. Example 2: Input: maxChoosableInteger = 10, desiredTotal = 0 Output: true Example 3: Input: maxChoosableInteger = 10, desiredTotal = 1 Output: true   Constraints: 1 <= maxChoosableInteger <= 20 0 <= desiredTotal <= 300
Medium
[ "math", "dynamic-programming", "bit-manipulation", "memoization", "game-theory", "bitmask" ]
[ "const canIWin = function(maxChoosableInteger, desiredTotal) {\n if (desiredTotal <= 0) return true\n if ((maxChoosableInteger * (1 + maxChoosableInteger)) / 2 < desiredTotal)\n return false\n const dp = new Array(1 << maxChoosableInteger).fill(0)\n return dfs(dp, 0, maxChoosableInteger, desiredTotal)\n\n function dfs(dp, chs, max, target) {\n if (target <= 0) return false\n if (dp[chs] != 0) return dp[chs] === 1\n let win = false\n for (let i = 0; i < max; i++) {\n if ((chs & (1 << i)) === 0) {\n //not used\n win = win || !dfs(dp, chs ^ (1 << i), max, target - i - 1)\n }\n }\n dp[chs] = win ? 1 : -1\n return win\n }\n}" ]
466
count-the-repetitions
[]
/** * @param {string} s1 * @param {number} n1 * @param {string} s2 * @param {number} n2 * @return {number} */ var getMaxRepetitions = function(s1, n1, s2, n2) { };
We define str = [s, n] as the string str which consists of the string s concatenated n times. For example, str == ["abc", 3] =="abcabcabc". We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, s1 = "abc" can be obtained from s2 = "abdbec" based on our definition by removing the bolded underlined characters. You are given two strings s1 and s2 and two integers n1 and n2. You have the two strings str1 = [s1, n1] and str2 = [s2, n2]. Return the maximum integer m such that str = [str2, m] can be obtained from str1.   Example 1: Input: s1 = "acb", n1 = 4, s2 = "ab", n2 = 2 Output: 2 Example 2: Input: s1 = "acb", n1 = 1, s2 = "acb", n2 = 1 Output: 1   Constraints: 1 <= s1.length, s2.length <= 100 s1 and s2 consist of lowercase English letters. 1 <= n1, n2 <= 106
Hard
[ "string", "dynamic-programming" ]
[ "const getMaxRepetitions = function(s1, n1, s2, n2) {\n let j = 0,\n i,\n count = 0,\n perCycle = 0,\n firstEnd = -1,\n lastEnd = -1,\n nonMatch = 0\n for (i = 0; i < s1.length * n1; i++) {\n if (s2[j] === s1[i % s1.length]) {\n j++\n nonMatch = 0\n } else if (++nonMatch >= s1.length) break\n if (j === s2.length) {\n count++\n perCycle++\n j = 0\n if (lastEnd !== -1) continue\n else if (firstEnd === -1) {\n firstEnd = i\n perCycle = 0\n } else if ((i - firstEnd) % s1.length === 0) {\n let cycleLen = i - firstEnd\n let remainLen = s1.length * n1 - i - 1\n let cycles = Math.floor(remainLen / cycleLen)\n count += cycles * perCycle\n i += cycles * cycleLen\n }\n }\n }\n return Math.floor(count / n2)\n}" ]
467
unique-substrings-in-wraparound-string
[ "One possible solution might be to consider allocating an array size of 26 for each character in the alphabet. (Credits to @r2ysxu)" ]
/** * @param {string} s * @return {number} */ var findSubstringInWraproundString = function(s) { };
We define the string base to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so base will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". Given a string s, return the number of unique non-empty substrings of s are present in base.   Example 1: Input: s = "a" Output: 1 Explanation: Only the substring "a" of s is in base. Example 2: Input: s = "cac" Output: 2 Explanation: There are two substrings ("a", "c") of s in base. Example 3: Input: s = "zab" Output: 6 Explanation: There are six substrings ("z", "a", "b", "za", "ab", and "zab") of s in base.   Constraints: 1 <= s.length <= 105 s consists of lowercase English letters.
Medium
[ "string", "dynamic-programming" ]
[ "const findSubstringInWraproundString = function(p) {\n // count[i] is the maximum unique substring end with ith letter.\n // 0 - 'a', 1 - 'b', ..., 25 - 'z'.\n const count = new Array(26).fill(0);\n\n // store longest contiguous substring ends at current position.\n let maxLengthCur = 0; \n\n for (let i = 0; i < p.length; i++) {\n if (i > 0\n && (p.charCodeAt(i) - p.charCodeAt(i - 1) === 1 \n || (p.charCodeAt(i - 1) - p.charCodeAt(i) === 25))) {\n maxLengthCur++;\n }\n else {\n maxLengthCur = 1;\n }\n\n let index = p.charCodeAt(i) - ('a').charCodeAt(0);\n count[index] = Math.max(count[index], maxLengthCur);\n }\n\n // Sum to get result\n let sum = 0;\n for (let i = 0; i < 26; i++) {\n sum += count[i];\n }\n return sum;\n};" ]
468
validate-ip-address
[]
/** * @param {string} queryIP * @return {string} */ var validIPAddress = function(queryIP) { };
Given a string queryIP, return "IPv4" if IP is a valid IPv4 address, "IPv6" if IP is a valid IPv6 address or "Neither" if IP is not a correct IP of any type. A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi cannot contain leading zeros. For example, "192.168.1.1" and "192.168.1.0" are valid IPv4 addresses while "192.168.01.1", "192.168.1.00", and "192.168@1.1" are invalid IPv4 addresses. A valid IPv6 address is an IP in the form "x1:x2:x3:x4:x5:x6:x7:x8" where: 1 <= xi.length <= 4 xi is a hexadecimal string which may contain digits, lowercase English letter ('a' to 'f') and upper-case English letters ('A' to 'F'). Leading zeros are allowed in xi. For example, "2001:0db8:85a3:0000:0000:8a2e:0370:7334" and "2001:db8:85a3:0:0:8A2E:0370:7334" are valid IPv6 addresses, while "2001:0db8:85a3::8A2E:037j:7334" and "02001:0db8:85a3:0000:0000:8a2e:0370:7334" are invalid IPv6 addresses.   Example 1: Input: queryIP = "172.16.254.1" Output: "IPv4" Explanation: This is a valid IPv4 address, return "IPv4". Example 2: Input: queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334" Output: "IPv6" Explanation: This is a valid IPv6 address, return "IPv6". Example 3: Input: queryIP = "256.256.256.256" Output: "Neither" Explanation: This is neither a IPv4 address nor a IPv6 address.   Constraints: queryIP consists only of English letters, digits and the characters '.' and ':'.
Medium
[ "string" ]
[ "const validIPAddress = function (IP) {\n if (IP.indexOf('.') > 0) return validIPv4(IP) ? 'IPv4' : 'Neither'\n else return validIPv6(IP) ? 'IPv6' : 'Neither'\n}\n\nconst validIPv4 = function (IP) {\n const strs = IP.split('.')\n if (strs.length !== 4) return false\n for (let str of strs) {\n if (str.length === 0) return false\n if (str.match(/[^0-9]/)) return false\n if (str.length > 1 && str.charAt(0) === '0') return false\n if (+str > 255) return false\n }\n return true\n}\n\nconst validIPv6 = function (IP) {\n const strs = IP.split(':')\n if (strs.length !== 8) return false\n for (let str of strs) {\n if (str.length === 0) return false\n if (str.length > 4) return false\n if (str.match(/[^0-9a-fA-F]/g)) return false\n }\n return true\n}", "const validIPAddress = function(IP) {\n const ipv4 = /^((\\d|[1-9]\\d|1\\d\\d|2([0-4]\\d|5[0-5]))\\.){4}$/\n const ipv6 = /^([\\da-f]{1,4}:){8}$/i\n return ipv4.test(IP + '.') ? 'IPv4' : ipv6.test(IP + ':') ? 'IPv6' : 'Neither'\n}", "const validIPAddress = function(IP) {\n if (IP.indexOf('.') != -1) {\n const arr = IP.split('.')\n if (arr.length !== 4) return 'Neither'\n for (let i = 0; i < arr.length; i++) {\n const numVal = parseInt(arr[i])\n if (\n numVal < 0 ||\n numVal >= 256 ||\n arr[i].length !== ('' + numVal).length\n ) {\n return 'Neither'\n }\n }\n return 'IPv4'\n } else if (IP.indexOf(':') != -1) {\n const arr = IP.split(':')\n if (arr.length !== 8) return 'Neither'\n for (let i = 0; i < arr.length; i++) {\n if (arr[i].length > 4 || arr[i].length === 0) return 'Neither'\n const re = /[^0-9A-F]/i\n if (re.test(arr[i])) return 'Neither'\n }\n return 'IPv6'\n } else {\n return 'Neither'\n }\n}" ]
470
implement-rand10-using-rand7
[]
/** * The rand7() API is already defined for you. * var rand7 = function() {} * @return {number} a random integer in the range 1 to 7 */ var rand10 = function() { };
Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API. Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().   Example 1: Input: n = 1 Output: [2] Example 2: Input: n = 2 Output: [2,8] Example 3: Input: n = 3 Output: [3,8,10]   Constraints: 1 <= n <= 105   Follow up: What is the expected value for the number of calls to rand7() function? Could you minimize the number of calls to rand7()?
Medium
[ "math", "rejection-sampling", "randomized", "probability-and-statistics" ]
[ "const rand10 = function() {\n let result = 40\n while (result >= 40) {\n result = 7 * (rand7() - 1) + (rand7() - 1)\n }\n return (result % 10) + 1\n}", "const rand10 = function() {\n let tmp = 40\n while(tmp >= 40) tmp = 7 * (rand7() - 1) + (rand7() - 1)\n \n return tmp % 10 + 1\n};" ]
472
concatenated-words
[]
/** * @param {string[]} words * @return {string[]} */ var findAllConcatenatedWordsInADict = function(words) { };
Given an array of strings words (without duplicates), return all the concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array.   Example 1: Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] Output: ["catsdogcats","dogcatsdog","ratcatdogcat"] Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat". Example 2: Input: words = ["cat","dog","catdog"] Output: ["catdog"]   Constraints: 1 <= words.length <= 104 1 <= words[i].length <= 30 words[i] consists of only lowercase English letters. All the strings of words are unique. 1 <= sum(words[i].length) <= 105
Hard
[ "array", "string", "dynamic-programming", "depth-first-search", "trie" ]
[ "const findAllConcatenatedWordsInADict = function (words) {\n const pre = new Set()\n words.sort((a, b) => a.length - b.length)\n const res = []\n for(let i = 0; i < words.length; i++) {\n if(valid(words[i], pre)) {\n res.push(words[i])\n }\n pre.add(words[i])\n }\n\n return res\n\n function valid(str, set) {\n if(set.size === 0) return false\n const dp = Array(str.length + 1).fill(false)\n dp[0] = true\n for(let i = 1; i <= str.length; i++) {\n for(let j = 0; j < i; j++) {\n if(!dp[j]) continue\n if(set.has(str.slice(j, i))) {\n dp[i] = true\n break\n }\n }\n }\n \n return dp[str.length]\n }\n}", "const findAllConcatenatedWordsInADict = function (words) {\n const set = new Set(words)\n const res = []\n const map = new Map()\n for (let w of words) {\n if (w.length < 2) continue\n if (dfs(w, set, map, 0)) res.push(w)\n }\n return res\n\n function dfs(word, set, map, pos) {\n if (pos > 0 && map.get(word)) return map.get(word)\n if (pos > 0 && set.has(word)) {\n map.set(word, true)\n return map.get(word)\n }\n for (let i = 1; i < word.length; i++) {\n const left = word.slice(0, i)\n const right = word.slice(i)\n if (set.has(right) && dfs(left, set, map, pos + 1)) {\n map.set(word, true)\n return map.get(word)\n }\n }\n\n map.set(word, false)\n return false\n }\n}", "const findAllConcatenatedWordsInADict = function (words) {\n const set = new Set(words)\n const res = []\n const map = new Map()\n\n for(let word of words) {\n if(dfs(word, 0)) res.push(word)\n }\n return res\n function dfs(word, idx) {\n if(map.has(word)) return map.get(word)\n if(idx > 0 && set.has(word)) return true\n let tmp = false\n for(let i = 1; i < word.length; i++) {\n const prefix = word.slice(0, i), suffix = word.slice(i)\n if(set.has(prefix) && set.has(suffix)) {\n tmp = true\n break\n }\n if(set.has(prefix) && dfs(suffix, idx + 1)) {\n tmp = true\n break\n }\n }\n \n map.set(word, tmp)\n return tmp\n }\n}", "const findAllConcatenatedWordsInADict = function(words) {\n let res = []\n if (words === null || words.length == 0) return res\n let set = new Set(words)\n for (let word of words) {\n set.delete(word)\n if (dfs(word, set, '')) res.push(word)\n set.add(word)\n }\n return res\n}\n\nfunction dfs(word, set, prev) {\n if (prev != '') set.add(prev)\n if (set.has(word)) return true\n for (let i = 1; i <= word.length; i++) {\n const prefix = word.substring(0, i)\n if (set.has(prefix) && dfs(word.substring(i), set, prev + prefix)) {\n return true\n }\n }\n return false\n}" ]
473
matchsticks-to-square
[ "Treat the matchsticks as an array. Can we split the array into 4 equal parts?", "Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options!", "For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this.", "We don't really need to keep track of which matchsticks belong to a particular side during recursion. We just need to keep track of the <b>length</b> of each of the 4 sides.", "When all matchsticks have been used we simply need to see the length of all 4 sides. If they're equal, we have a square on our hands!" ]
/** * @param {number[]} matchsticks * @return {boolean} */ var makesquare = function(matchsticks) { };
You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. Return true if you can make this square and false otherwise.   Example 1: Input: matchsticks = [1,1,2,2,2] Output: true Explanation: You can form a square with length 2, one side of the square came two sticks with length 1. Example 2: Input: matchsticks = [3,3,3,3,4] Output: false Explanation: You cannot find a way to form a square with all the matchsticks.   Constraints: 1 <= matchsticks.length <= 15 1 <= matchsticks[i] <= 108
Medium
[ "array", "dynamic-programming", "backtracking", "bit-manipulation", "bitmask" ]
[ "const makesquare = function(nums) {\n if (nums == null || nums.length < 4) return false\n const sum = nums.reduce((ac, el) => ac + el, 0)\n if (sum % 4 !== 0) return false\n nums.sort((a, b) => b - a)\n return dfs(nums, new Array(4).fill(0), 0, sum / 4)\n}\n\nfunction dfs(nums, arr, idx, target) {\n if (idx === nums.length) {\n return true\n }\n for (let i = 0; i < 4; i++) {\n if (arr[i] + nums[idx] > target || (i > 0 && arr[i] === arr[i - 1]))\n continue\n arr[i] += nums[idx]\n if (dfs(nums, arr, idx + 1, target)) return true\n arr[i] -= nums[idx]\n }\n return false\n}", "const makesquare = function(nums) {\n if (nums.length == 0) return false\n const edge = nums.reduce((accum, val) => accum + val) / 4\n nums.sort((val1, val2) => val2 - val1)\n if (edge !== Math.floor(edge)) return false\n const findEdge = function(target) {\n if (target <= 0) return target === 0\n let newNums = []\n while (nums.length) {\n let item = nums.shift()\n if (findEdge(target - item)) {\n nums = newNums.concat(nums)\n return true\n }\n newNums.push(item)\n }\n nums = newNums\n return false\n }\n let count = 4\n while (count) {\n if (!findEdge(edge)) return false\n count--\n }\n return true\n}" ]
474
ones-and-zeroes
[]
/** * @param {string[]} strs * @param {number} m * @param {number} n * @return {number} */ var findMaxForm = function(strs, m, n) { };
You are given an array of binary strings strs and two integers m and n. Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset. A set x is a subset of a set y if all elements of x are also elements of y.   Example 1: Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3 Output: 4 Explanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4. Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}. {"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3. Example 2: Input: strs = ["10","0","1"], m = 1, n = 1 Output: 2 Explanation: The largest subset is {"0", "1"}, so the answer is 2.   Constraints: 1 <= strs.length <= 600 1 <= strs[i].length <= 100 strs[i] consists only of digits '0' and '1'. 1 <= m, n <= 100
Medium
[ "array", "string", "dynamic-programming" ]
[ "const findMaxForm = function(strs, m, n) {\n const memo = Array.from(new Array(m + 1), () => new Array(n + 1).fill(0))\n let numZeroes\n let numOnes\n\n for (let s of strs) {\n numZeroes = numOnes = 0\n // count number of zeroes and ones in current string\n for (let c of s) {\n if (c === '0') numZeroes++\n else if (c === '1') numOnes++\n }\n // memo[i][j] = the max number of strings that can be formed with i 0's and j 1's\n // from the first few strings up to the current string s\n // Catch: have to go from bottom right to top left\n // Why? If a cell in the memo is updated(because s is selected),\n // we should be adding 1 to memo[i][j] from the previous iteration (when we were not considering s)\n // If we go from top left to bottom right, we would be using results from this iteration => overcounting\n for (let i = m; i >= numZeroes; i--) {\n for (let j = n; j >= numOnes; j--) {\n memo[i][j] = Math.max(memo[i][j], memo[i - numZeroes][j - numOnes] + 1)\n }\n }\n }\n return memo[m][n]\n}" ]
475
heaters
[]
/** * @param {number[]} houses * @param {number[]} heaters * @return {number} */ var findRadius = function(houses, heaters) { };
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range.  Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses. Notice that all the heaters follow your radius standard, and the warm radius will the same.   Example 1: Input: houses = [1,2,3], heaters = [2] Output: 1 Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. Example 2: Input: houses = [1,2,3,4], heaters = [1,4] Output: 1 Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed. Example 3: Input: houses = [1,5], heaters = [2] Output: 3   Constraints: 1 <= houses.length, heaters.length <= 3 * 104 1 <= houses[i], heaters[i] <= 109
Medium
[ "array", "two-pointers", "binary-search", "sorting" ]
[ "const findRadius = function(houses, heaters) {\n heaters.sort((a, b) => a - b)\n return Math.max(...houses.map(h => findMinDistance(h, heaters)))\n}\n\nconst findMinDistance = (house, heaters) => {\n let left = 0\n let right = heaters.length - 1\n while (left <= right) {\n const mid = left + ((right - left) >> 1)\n if (heaters[mid] <= house && house <= heaters[mid + 1]) {\n return Math.min(house - heaters[mid], heaters[mid + 1] - house)\n } else if (heaters[mid] <= house) {\n left = mid + 1\n } else {\n right = mid - 1\n }\n }\n if (left === 0) return heaters[0] - house\n if (left === heaters.length) return house - heaters[heaters.length - 1]\n}", "const findRadius = function(houses, heaters) {\n let res = 0\n let k = 0\n houses = houses.sort((a, b) => a - b)\n heaters = heaters.sort((a, b) => a - b)\n for (let i = 0; i < houses.length; i++) {\n const curr = houses[i]\n while (\n k < heaters.length &&\n Math.abs(heaters[k + 1] - curr) <= Math.abs(heaters[k] - curr)\n ) {\n k++\n }\n res = Math.max(res, Math.abs(heaters[k] - curr))\n }\n return res\n}", "const findRadius = function(houses, heaters) {\n heaters.sort((a, b) => a - b)\n houses.sort((a, b) => a - b)\n let res = 0, i = 0\n for(let h of houses) {\n while(i < heaters.length - 1 && heaters[i] + heaters[i + 1] <= h * 2) i++\n res = Math.max(res, Math.abs(heaters[i] - h))\n }\n return res\n}" ]
476
number-complement
[]
/** * @param {number} num * @return {number} */ var findComplement = function(num) { };
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. Given an integer num, return its complement.   Example 1: Input: num = 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. Example 2: Input: num = 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.   Constraints: 1 <= num < 231   Note: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/
Easy
[ "bit-manipulation" ]
[ "const findComplement = function(num) {\n const toBin = num => (num >>> 0).toString(2)\n const flip = str => {\n let res = ''\n for(let c of str) res += (c === '1' ? '0' : '1')\n return res\n }\n return parseInt(flip(toBin(num)), 2)\n};" ]
477
total-hamming-distance
[]
/** * @param {number[]} nums * @return {number} */ var totalHammingDistance = function(nums) { };
The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.   Example 1: Input: nums = [4,14,2] Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). The answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. Example 2: Input: nums = [4,14,4] Output: 4   Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 109 The answer for the given input will fit in a 32-bit integer.
Medium
[ "array", "math", "bit-manipulation" ]
[ "const totalHammingDistance = function(nums) {\n let total = 0,\n n = nums.length;\n for (let j = 0; j < 32; j++) {\n let bitCount = 0;\n for (let i = 0; i < n; i++) bitCount += (nums[i] >> j) & 1;\n total += bitCount * (n - bitCount);\n }\n return total;\n};" ]
478
generate-random-point-in-a-circle
[]
/** * @param {number} radius * @param {number} x_center * @param {number} y_center */ var Solution = function(radius, x_center, y_center) { }; /** * @return {number[]} */ Solution.prototype.randPoint = function() { }; /** * Your Solution object will be instantiated and called as such: * var obj = new Solution(radius, x_center, y_center) * var param_1 = obj.randPoint() */
Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle. Implement the Solution class: Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center). randPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y].   Example 1: Input ["Solution", "randPoint", "randPoint", "randPoint"] [[1.0, 0.0, 0.0], [], [], []] Output [null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]] Explanation Solution solution = new Solution(1.0, 0.0, 0.0); solution.randPoint(); // return [-0.02493, -0.38077] solution.randPoint(); // return [0.82314, 0.38945] solution.randPoint(); // return [0.36572, 0.17248]   Constraints: 0 < radius <= 108 -107 <= x_center, y_center <= 107 At most 3 * 104 calls will be made to randPoint.
Medium
[ "math", "geometry", "rejection-sampling", "randomized" ]
[ "const Solution = function(radius, x_center, y_center) {\n this.radius = radius\n this.x_center = x_center\n this.y_center = y_center\n}\n\n\nSolution.prototype.randPoint = function() {\n let len = Math.sqrt(Math.random()) * this.radius\n let deg = Math.random() * 2 * Math.PI\n let x = this.x_center + len * Math.cos(deg)\n let y = this.y_center + len * Math.sin(deg)\n return [x, y]\n}" ]
479
largest-palindrome-product
[]
/** * @param {number} n * @return {number} */ var largestPalindrome = function(n) { };
Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.   Example 1: Input: n = 2 Output: 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 Example 2: Input: n = 1 Output: 9   Constraints: 1 <= n <= 8
Hard
[ "math" ]
[ "function largestPalindrome(n) {\n if(n === 1) return 9\n let max = BigInt(10 ** n - 1), min = max / 10n + 1n\n for(let h = max; h >= min; h--) {\n let left = h, right = 0n\n for(let i = h; i !== 0n; ) {\n right = right * 10n + i % 10n\n i = i / 10n\n left *= 10n\n }\n let pal = left + right\n for(let i = max; i >= min; i--) {\n let j = pal / i\n if(j > i) break\n if(pal % i === 0n) return pal % 1337n\n }\n }\n}", "const largestPalindrome = function (n) {\n if (n === 1) return 9\n for (let i = 2, limit = 9 * 10 ** (n - 1); i < limit; i++) {\n let left = 10 ** n - i\n let right = +('' + left).split('').reverse().join('')\n if (i ** 2 - 4 * right < 0) continue\n const tmp = (i ** 2 - 4 * right) ** 0.5\n if (tmp === Math.floor(tmp)) {\n return (\n (BigInt(right) + 10n ** BigInt(n) * (10n ** BigInt(n) - BigInt(i))) %\n 1337n\n )\n }\n }\n}", "const largestPalindrome = function(n) {\n if (n === 1) {\n return 9\n } else if (n === 8) {\n return 475\n }\n let max = Math.pow(10, n)\n let min = Math.pow(10, n - 1)\n let ret = 0\n\n for (let i = max - 1; i > 0; i--) {\n ret = i * max + getReverse(i)\n for (let factor = ~~Math.sqrt(ret); factor < max; factor++) {\n if (ret % factor == 0 && ret / factor < max) {\n return ret % 1337\n }\n }\n }\n return -1\n}\n\nfunction getReverse(n) {\n let result = 0\n let num = n\n while (num > 0) {\n result = result * 10 + (num % 10)\n num = ~~(num / 10)\n }\n return result\n}" ]
480
sliding-window-median
[ "The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we extend this idea to every sliding window that we come across in the array?", "Is there a better way to do what we are doing in the above hint? Don't you think there is duplication of calculation being done there? Is there some sort of optimization that we can do to achieve the same result? This approach is merely a modification of the basic approach except that it simply reduces duplication of calculations once done.", "The third line of thought is also based on this same idea but achieving the result in a different way. We obviously need the window to be sorted for us to be able to find the median. Is there a data-structure out there that we can use (in one or more quantities) to obtain the median element extremely fast, say O(1) time while having the ability to perform the other operations fairly efficiently as well?" ]
/** * @param {number[]} nums * @param {number} k * @return {number[]} */ var medianSlidingWindow = function(nums, k) { };
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. For examples, if arr = [2,3,4], the median is 3. For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5. You are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted.   Example 1: Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000] Explanation: Window position Median --------------- ----- [1 3 -1] -3 5 3 6 7 1 1 [3 -1 -3] 5 3 6 7 -1 1 3 [-1 -3 5] 3 6 7 -1 1 3 -1 [-3 5 3] 6 7 3 1 3 -1 -3 [5 3 6] 7 5 1 3 -1 -3 5 [3 6 7] 6 Example 2: Input: nums = [1,2,3,4,2,3,1,4,2], k = 3 Output: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]   Constraints: 1 <= k <= nums.length <= 105 -231 <= nums[i] <= 231 - 1
Hard
[ "array", "hash-table", "sliding-window", "heap-priority-queue" ]
[ "const medianSlidingWindow = function(nums, k) {\n const window = nums.slice(0, k).sort((x, y) => x - y)\n const resultLen = nums.length - k + 1\n nums.push(0)\n\n function insert(arr, val) {\n let i = 0\n while (i < arr.length && arr[i] < val) {\n i++\n }\n arr.splice(i, 0, val)\n }\n\n const medians = []\n const rightIdx = (k / 2) >>> 0\n const leftIdx = k + ~rightIdx\n for (let i = 0; i < resultLen; i++) {\n medians.push((window[leftIdx] + window[rightIdx]) / 2)\n window.splice(window.indexOf(nums[i]), 1)\n insert(window, nums[k + i])\n }\n return medians\n}", "const medianSlidingWindow = function(nums, k) {\n let pq = []\n for (let i = 0; i < k; i++) {\n insert(nums[i])\n }\n let res = []\n res.push(findMid())\n for (let i = k; i < nums.length; i++) {\n remove(nums[i - k])\n insert(nums[i])\n res.push(findMid())\n }\n return res\n function findMid() {\n let mid = (pq.length - 1) / 2\n return (pq[Math.ceil(mid)] + pq[Math.floor(mid)]) / 2\n }\n function insert(n) {\n if (pq.length === 0 || pq[pq.length - 1] <= n) {\n pq.push(n)\n } else {\n let idx = bsEnd(pq, n)\n pq.splice(idx, 0, n)\n }\n }\n function bsEnd(arr, n) {\n let lo = 0,\n hi = arr.length - 1\n while (lo < hi) {\n let mid = Math.floor((lo + hi) / 2)\n if (arr[mid] < n) lo = mid + 1\n else hi = mid\n }\n return hi\n }\n function remove(n) {\n let idx = bsEnd(pq, n)\n pq.splice(idx, 1)\n }\n}" ]
481
magical-string
[]
/** * @param {number} n * @return {number} */ var magicalString = function(n) { };
A magical string s consists of only '1' and '2' and obeys the following rules: The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself. The first few elements of s is s = "1221121221221121122……". If we group the consecutive 1's and 2's in s, it will be "1 22 11 2 1 22 1 22 11 2 11 22 ......" and the occurrences of 1's or 2's in each group are "1 2 2 1 1 2 1 2 2 1 2 2 ......". You can see that the occurrence sequence is s itself. Given an integer n, return the number of 1's in the first n number in the magical string s.   Example 1: Input: n = 6 Output: 3 Explanation: The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3. Example 2: Input: n = 1 Output: 1   Constraints: 1 <= n <= 105
Medium
[ "two-pointers", "string" ]
[ "const magicalString = function(n) {\n const queue = []\n let one = true\n let count1 = 0\n while (n-- > 0) {\n queue.shift()\n let c = one ? 1 : 2\n one = !one\n queue.push(c)\n count1 += 2 - c\n if (queue[0] === 2 && n-- > 0) {\n queue.push(c)\n count1 += 2 - c\n }\n }\n return count1\n}" ]
482
license-key-formatting
[]
/** * @param {string} s * @param {number} k * @return {string} */ var licenseKeyFormatting = function(s, k) { };
You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k. We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key.   Example 1: Input: s = "5F3Z-2e-9-w", k = 4 Output: "5F3Z-2E9W" Explanation: The string s has been split into two parts, each part has 4 characters. Note that the two extra dashes are not needed and can be removed. Example 2: Input: s = "2-5g-3-J", k = 2 Output: "2-5G-3J" Explanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.   Constraints: 1 <= s.length <= 105 s consists of English letters, digits, and dashes '-'. 1 <= k <= 104
Easy
[ "string" ]
[ "const licenseKeyFormatting = function(S, K) {\n if (S == null || S === \"\") return \"\";\n const newStr = S.replace(/-/g, \"\").toUpperCase();\n const arr = newStr.split(\"\");\n for (let i = arr.length - 1 - K; i >= 0; i -= K) {\n arr[i] = arr[i] + \"-\";\n }\n return arr.join(\"\");\n};" ]
483
smallest-good-base
[]
/** * @param {string} n * @return {string} */ var smallestGoodBase = function(n) { };
Given an integer n represented as a string, return the smallest good base of n. We call k >= 2 a good base of n, if all digits of n base k are 1's.   Example 1: Input: n = "13" Output: "3" Explanation: 13 base 3 is 111. Example 2: Input: n = "4681" Output: "8" Explanation: 4681 base 8 is 11111. Example 3: Input: n = "1000000000000000000" Output: "999999999999999999" Explanation: 1000000000000000000 base 999999999999999999 is 11.   Constraints: n is an integer in the range [3, 1018]. n does not contain any leading zeros.
Hard
[ "math", "binary-search" ]
[ "const smallestGoodBase = function(n) {\n const N = BigInt(n),\n bigint2 = BigInt(2),\n bigint1 = BigInt(1),\n bigint0 = BigInt(0)\n let maxLen = countLength(N, bigint2)\n for (let length = maxLen; length > 0; length--) {\n let [found, base] = findMatchInHalf(length)\n if (found) return '' + base\n }\n return '' + (N - 1)\n function findMatchInHalf(length, smaller = bigint2, bigger = N) {\n if (smaller > bigger) return [false]\n if (smaller === bigger) {\n return [valueOf1s(smaller, length) === N, smaller]\n }\n let mid = (smaller + bigger) / bigint2\n let val = valueOf1s(mid, length)\n if (val === N) return [true, mid]\n if (val > N) return findMatchInHalf(length, smaller, mid - bigint1)\n return findMatchInHalf(length, mid + bigint1, bigger)\n }\n function valueOf1s(base, lengthOf1s) {\n let t = bigint1\n for (let i = 1; i < lengthOf1s; i++) {\n t *= base\n t += bigint1\n }\n return t\n }\n function countLength(N, base) {\n let t = N,\n len = 0\n while (t > bigint0) {\n t /= base\n len++\n }\n return len\n }\n}" ]
485
max-consecutive-ones
[ "You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window.\r\n\r\nHow do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size." ]
/** * @param {number[]} nums * @return {number} */ var findMaxConsecutiveOnes = function(nums) { };
Given a binary array nums, return the maximum number of consecutive 1's in the array.   Example 1: Input: nums = [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Example 2: Input: nums = [1,0,1,1,0,1] Output: 2   Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.
Easy
[ "array" ]
[ "const findMaxConsecutiveOnes = function(nums) {\n let sum = 0,\n max = 0;\n\n for (let i = 0; i < nums.length; i++) {\n let temp = sum;\n sum += nums[i];\n if (temp === sum || i === nums.length - 1) {\n max = Math.max(sum, max);\n sum = 0;\n }\n }\n\n return max;\n};" ]
486
predict-the-winner
[]
/** * @param {number[]} nums * @return {boolean} */ var predictTheWinner = function(nums) { };
You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array. Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally.   Example 1: Input: nums = [1,5,2] Output: false Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return false. Example 2: Input: nums = [1,5,233,7] Output: true Explanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233. Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.   Constraints: 1 <= nums.length <= 20 0 <= nums[i] <= 107
Medium
[ "array", "math", "dynamic-programming", "recursion", "game-theory" ]
[ "const PredictTheWinner = function(nums) {\n // The dp[i][j] saves how much more scores that the first-in-action player will get from i to j than the second player.\n const dp = [];\n for (let i = 0; i <= nums.length; i++) {\n dp.push(Array(nums.length).fill(0));\n }\n for (let s = nums.length - 1; s >= 0; s--) {\n dp[s][s] = nums[s];\n for (let e = s + 1; e < nums.length; e++) {\n let a = nums[s] - dp[s + 1][e];\n let b = nums[e] - dp[s][e - 1];\n dp[s][e] = Math.max(a, b);\n }\n }\n return dp[0][nums.length - 1] >= 0;\n};\n\nconsole.log(PredictTheWinner([1, 5, 233, 7]));\nconsole.log(PredictTheWinner([3, 5, 3]));" ]
488
zuma-game
[]
/** * @param {string} board * @param {string} hand * @return {number} */ var findMinStep = function(board, hand) { };
You are playing a variation of the game Zuma. In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R', yellow 'Y', blue 'B', green 'G', or white 'W'. You also have several colored balls in your hand. Your goal is to clear all of the balls from the board. On each turn: Pick any ball from your hand and insert it in between two balls in the row or on either end of the row. If there is a group of three or more consecutive balls of the same color, remove the group of balls from the board. If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left. If there are no more balls on the board, then you win the game. Repeat this process until you either win or do not have any more balls in your hand. Given a string board, representing the row of balls on the board, and a string hand, representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1.   Example 1: Input: board = "WRRBBW", hand = "RB" Output: -1 Explanation: It is impossible to clear all the balls. The best you can do is: - Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW. - Insert 'B' so the board becomes WBBBW. WBBBW -> WW. There are still balls remaining on the board, and you are out of balls to insert. Example 2: Input: board = "WWRRBBWW", hand = "WRBRW" Output: 2 Explanation: To make the board empty: - Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW. - Insert 'B' so the board becomes WWBBBWW. WWBBBWW -> WWWW -> empty. 2 balls from your hand were needed to clear the board. Example 3: Input: board = "G", hand = "GGGGG" Output: 2 Explanation: To make the board empty: - Insert 'G' so the board becomes GG. - Insert 'G' so the board becomes GGG. GGG -> empty. 2 balls from your hand were needed to clear the board.   Constraints: 1 <= board.length <= 16 1 <= hand.length <= 5 board and hand consist of the characters 'R', 'Y', 'B', 'G', and 'W'. The initial row of balls on the board will not have any groups of three or more consecutive balls of the same color.
Hard
[ "string", "dynamic-programming", "stack", "breadth-first-search", "memoization" ]
[ "const findMinStep = function(board, hand) {\n const map = {}\n for (let c of hand) map[c] = (map[c] || 0) + 1\n const res = helper(board, map)\n return res === Number.MAX_VALUE ? -1 : res\n}\n\nfunction helper(s, m) {\n const str = reduce(s)\n if (str.length === 0) return 0\n let res = Number.MAX_VALUE\n let i = 0\n while (i < str.length) {\n const beg = i\n while (i < str.length && str[i] === str[beg]) {\n i++\n }\n if (m[str[beg]] >= 3 - (i - beg)) {\n const dval = 3 - i + beg\n m[str[beg]] -= dval\n const tmp = helper(s.slice(0, beg) + s.slice(i), m)\n m[str[beg]] += dval\n if (tmp !== Number.MAX_VALUE) res = res < tmp + dval ? res : tmp + dval\n }\n }\n return res\n}\nfunction reduce(str) {\n let res = ''\n let i = 0\n while (i < str.length) {\n const beg = i\n while (i < str.length && str[beg] === str[i]) {\n i++\n }\n if (i - beg >= 3) {\n return reduce(str.slice(0, beg) + str.slice(i))\n }\n }\n return str\n}" ]
491
non-decreasing-subsequences
[]
/** * @param {number[]} nums * @return {number[][]} */ var findSubsequences = function(nums) { };
Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.   Example 1: Input: nums = [4,6,7,7] Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]] Example 2: Input: nums = [4,4,3,2,1] Output: [[4,4]]   Constraints: 1 <= nums.length <= 15 -100 <= nums[i] <= 100
Medium
[ "array", "hash-table", "backtracking", "bit-manipulation" ]
[ "function findSubsequences(nums) {\n const res = []\n helper([], 0, nums, res)\n return res\n}\n\nfunction helper(list, index, nums, res) {\n if (list.length > 1) {\n res.push(Array.prototype.slice.call(list, 0))\n }\n const used = []\n for (let i = index; i < nums.length; i++) {\n if (used.indexOf(nums[i]) !== -1) {\n continue\n }\n if (list.length === 0 || nums[i] >= list[list.length - 1]) {\n used.push(nums[i])\n list.push(nums[i])\n helper(list, i + 1, nums, res)\n list.pop()\n }\n }\n}" ]
492
construct-the-rectangle
[ "The W is always less than or equal to the square root of the area, so we start searching at sqrt(area) till we find the result." ]
/** * @param {number} area * @return {number[]} */ var constructRectangle = function(area) { };
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: The area of the rectangular web page you designed must equal to the given target area. The width W should not be larger than the length L, which means L >= W. The difference between length L and width W should be as small as possible. Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.   Example 1: Input: area = 4 Output: [2,2] Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2. Example 2: Input: area = 37 Output: [37,1] Example 3: Input: area = 122122 Output: [427,286]   Constraints: 1 <= area <= 107
Easy
[ "math" ]
[ "const constructRectangle = function(area) {\n let w = Math.sqrt(area) >> 0;\n while (area % w != 0) w--;\n return [(area / w) >> 0, w];\n};" ]
493
reverse-pairs
[ "Use the merge-sort technique.", "Divide the array into two parts and sort them.", "For each integer in the first part, count the number of integers that satisfy the condition from the second part. Use the pointer to help you in the counting process." ]
/** * @param {number[]} nums * @return {number} */ var reversePairs = function(nums) { };
Given an integer array nums, return the number of reverse pairs in the array. A reverse pair is a pair (i, j) where: 0 <= i < j < nums.length and nums[i] > 2 * nums[j].   Example 1: Input: nums = [1,3,2,3,1] Output: 2 Explanation: The reverse pairs are: (1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1 (3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1 Example 2: Input: nums = [2,4,3,5,1] Output: 3 Explanation: The reverse pairs are: (1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1 (2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1 (3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1   Constraints: 1 <= nums.length <= 5 * 104 -231 <= nums[i] <= 231 - 1
Hard
[ "array", "binary-search", "divide-and-conquer", "binary-indexed-tree", "segment-tree", "merge-sort", "ordered-set" ]
[ "const reversePairs = function(nums) {\n return mergeSort(nums, [], 0, nums.length-1);\n};\n\nfunction mergeSort(arr, temp, left, right){\n let mid = Math.floor((left+right)/2), count = 0;\n if(left<right){\n count+= mergeSort(arr, temp, left, mid);\n count+= mergeSort(arr, temp, mid+1, right);\n count+= merge(arr, temp, left, mid+1, right);\n }\n return count;\n}\n\nfunction merge(a, temp, left, mid, right){\n let i = left, j = mid, k = left, count=0;\n for(let y=left; y<mid; y++){\n while(j<=right && (a[y]>2*a[j])){\n j++;\n }\n count+= (j-(mid));\n }\n i=left;\n j=mid;\n while(i<=(mid-1) && j<=right){\n if (a[i]>(a[j])) {\n temp[k++] = a[j++];\n } else {\n temp[k++] = a[i++];\n }\n }\n while(i<=(mid-1)){\n temp[k++] = a[i++];\n }\n while(j<=right){\n temp[k++] = a[j++];\n }\n for(let x=left; x<=right; x++){\n a[x] = temp[x];\n }\n return count;\n}", "const reversePairs = function(nums) {\n return mergeSort(nums, 0, nums.length - 1);\n};\n\nfunction mergeSort(nums, s, e) {\n if (s >= e) return 0;\n let mid = s + Math.floor((e - s) / 2);\n let cnt = mergeSort(nums, s, mid) + mergeSort(nums, mid + 1, e);\n for (let i = s, j = mid + 1; i <= mid; i++) {\n while (j <= e && nums[i] / 2.0 > nums[j]) j++;\n cnt += j - (mid + 1);\n }\n sortSubArr(nums, s, e + 1);\n return cnt;\n}\n\nfunction sortSubArr(arr, s, e) {\n const tmp = arr.slice(s, e);\n tmp.sort((a, b) => a - b);\n arr.splice(s, e - s, ...tmp);\n}", "function merge(A, start, mid, end) {\n let n1 = mid - start + 1\n let n2 = end - mid\n const L = new Array(n1).fill(0)\n const R = new Array(n2).fill(0)\n\n for (let i = 0; i < n1; i++) L[i] = A[start + i]\n for (let j = 0; j < n2; j++) R[j] = A[mid + 1 + j]\n let i = 0,\n j = 0\n for (let k = start; k <= end; k++) {\n if (j >= n2 || (i < n1 && L[i] <= R[j])) A[k] = L[i++]\n else A[k] = R[j++]\n }\n}\n\nfunction mergesort_and_count(A, start, end) {\n if (start < end) {\n let mid = start + ((end - start) >> 1)\n let count =\n mergesort_and_count(A, start, mid) + mergesort_and_count(A, mid + 1, end)\n let j = mid + 1\n for (let i = start; i <= mid; i++) {\n while (j <= end && A[i] > A[j] * 2) j++\n count += j - (mid + 1)\n }\n merge(A, start, mid, end)\n return count\n } else return 0\n}\n\nfunction reversePairs(nums) {\n return mergesort_and_count(nums, 0, nums.length - 1)\n}" ]
494
target-sum
[]
/** * @param {number[]} nums * @param {number} target * @return {number} */ var findTargetSumWays = function(nums, target) { };
You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers. For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1". Return the number of different expressions that you can build, which evaluates to target.   Example 1: Input: nums = [1,1,1,1,1], target = 3 Output: 5 Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3. -1 + 1 + 1 + 1 + 1 = 3 +1 - 1 + 1 + 1 + 1 = 3 +1 + 1 - 1 + 1 + 1 = 3 +1 + 1 + 1 - 1 + 1 = 3 +1 + 1 + 1 + 1 - 1 = 3 Example 2: Input: nums = [1], target = 1 Output: 1   Constraints: 1 <= nums.length <= 20 0 <= nums[i] <= 1000 0 <= sum(nums[i]) <= 1000 -1000 <= target <= 1000
Medium
[ "array", "dynamic-programming", "backtracking" ]
[ "const findTargetSumWays = function(nums, target) {\n const sum = nums.reduce((a, b) => a+b);\n if(Math.abs(target) > sum) {\n return 0;\n }\n if((target + sum) % 2) {\n return 0;\n }\n const newTarget = (target + sum) / 2;\n let dp = new Array(newTarget+1).fill(0);\n dp[0] = 1;\n for(let i = 0; i < nums.length; i++) {\n for(let j = newTarget; j >= nums[i]; j--) {\n dp[j] += dp[j - nums[i]];\n }\n }\n return dp[newTarget];\n};", "const findTargetSumWays = function(nums, s) {\n const sum = nums.reduce((p, n) => p + n, 0);\n return sum < s || (s + sum) % 2 > 0 ? 0 : subsetSum(nums, (s + sum) >>> 1);\n};\n\nfunction subsetSum(nums, s) {\n const dp = Array(s + 1).fill(0);\n dp[0] = 1;\n for (let n of nums) {\n for (let i = s; i >= n; i--) dp[i] += dp[i - n];\n }\n return dp[s];\n}" ]
495
teemo-attacking
[]
/** * @param {number[]} timeSeries * @param {number} duration * @return {number} */ var findPoisonedDuration = function(timeSeries, duration) { };
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack. You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration. Return the total number of seconds that Ashe is poisoned.   Example 1: Input: timeSeries = [1,4], duration = 2 Output: 4 Explanation: Teemo's attacks on Ashe go as follows: - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. - At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5. Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total. Example 2: Input: timeSeries = [1,2], duration = 2 Output: 3 Explanation: Teemo's attacks on Ashe go as follows: - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. - At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3. Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.   Constraints: 1 <= timeSeries.length <= 104 0 <= timeSeries[i], duration <= 107 timeSeries is sorted in non-decreasing order.
Easy
[ "array", "simulation" ]
[ "const findPoisonedDuration = function(timeSeries, duration) {\n if (timeSeries == null || timeSeries.length === 0) return 0\n let res = 0\n for (let i = 1, len = timeSeries.length; i < len; i++) {\n const tmp =\n timeSeries[i - 1] + duration > timeSeries[i]\n ? timeSeries[i] - timeSeries[i - 1]\n : duration\n res += tmp\n }\n return res + duration\n}" ]
496
next-greater-element-i
[]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var nextGreaterElement = function(nums1, nums2) { };
The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1. Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.   Example 1: Input: nums1 = [4,1,2], nums2 = [1,3,4,2] Output: [-1,3,-1] Explanation: The next greater element for each value of nums1 is as follows: - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. - 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. Example 2: Input: nums1 = [2,4], nums2 = [1,2,3,4] Output: [3,-1] Explanation: The next greater element for each value of nums1 is as follows: - 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. - 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.   Constraints: 1 <= nums1.length <= nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 104 All integers in nums1 and nums2 are unique. All the integers of nums1 also appear in nums2.   Follow up: Could you find an O(nums1.length + nums2.length) solution?
Easy
[ "array", "hash-table", "stack", "monotonic-stack" ]
[ "const nextGreaterElement = function(nums1, nums2) {\n const map = new Map()\n const stk = []\n \n for(let i = 0, n = nums2.length; i < n; i++) {\n const e = nums2[i]\n while(stk.length && stk.at(-1) < e) {\n const tmp = stk.pop()\n map.set(tmp, e)\n }\n stk.push(e)\n }\n \n const res = []\n for(const e of nums1) {\n if(map.has(e)) {\n res.push(map.get(e))\n } else {\n res.push(-1)\n }\n }\n \n return res\n};", "const nextGreaterElement = function(findNums, nums) {\n const map = {};\n const stack = [];\n for (let num of nums) {\n while (stack.length && stack[stack.length - 1] < num) {\n let tmp = stack.pop();\n map[tmp] = num;\n }\n stack.push(num);\n }\n for (let i = 0; i < findNums.length; i++) {\n findNums[i] = map[findNums[i]] == null ? -1 : map[findNums[i]];\n }\n\n return findNums;\n};\n\nconsole.log(nextGreaterElement([4, 1, 2], [1, 3, 4, 2]));\nconsole.log(nextGreaterElement([2, 4], [1, 2, 3, 4]));\nconsole.log(nextGreaterElement([1, 2, 3], [9, 8, 7, 3, 2, 1, 6]));" ]
497
random-point-in-non-overlapping-rectangles
[]
/** * @param {number[][]} rects */ var Solution = function(rects) { }; /** * @return {number[]} */ Solution.prototype.pick = function() { }; /** * Your Solution object will be instantiated and called as such: * var obj = new Solution(rects) * var param_1 = obj.pick() */
You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle. Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned. Note that an integer point is a point that has integer coordinates. Implement the Solution class: Solution(int[][] rects) Initializes the object with the given rectangles rects. int[] pick() Returns a random integer point [u, v] inside the space covered by one of the given rectangles.   Example 1: Input ["Solution", "pick", "pick", "pick", "pick", "pick"] [[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []] Output [null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]] Explanation Solution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]); solution.pick(); // return [1, -2] solution.pick(); // return [1, -1] solution.pick(); // return [-1, -2] solution.pick(); // return [-2, -2] solution.pick(); // return [0, 0]   Constraints: 1 <= rects.length <= 100 rects[i].length == 4 -109 <= ai < xi <= 109 -109 <= bi < yi <= 109 xi - ai <= 2000 yi - bi <= 2000 All the rectangles do not overlap. At most 104 calls will be made to pick.
Medium
[ "array", "math", "binary-search", "reservoir-sampling", "prefix-sum", "ordered-set", "randomized" ]
[ "const Solution = function(rects) {\n this.rects = rects\n this.areas = rects.map(([x1, y1, x2, y2]) => (x2 - x1 + 1) * (y2 - y1 + 1))\n}\n\n\nSolution.prototype.pick = function() {\n const { rects, areas } = this\n let areaSum = 0\n let selected\n for (let i = 0; i < rects.length; i++) {\n const area = areas[i]\n areaSum += area\n const p = area / areaSum\n if (Math.random() < p) {\n selected = rects[i]\n }\n }\n const [x1, y1, x2, y2] = selected\n return [\n ((Math.random() * (x2 - x1 + 1)) | 0) + x1,\n ((Math.random() * (y2 - y1 + 1)) | 0) + y1\n ]\n}", "const Solution = function(rects) {\n const xywhs = []\n const acc_sums = [0]\n let sum = 0\n for (const [x, y, x2, y2] of rects) {\n const w = x2 - x + 1\n const h = y2 - y + 1\n xywhs.push({ x, y, w, h })\n sum += w * h\n acc_sums.push(sum)\n }\n this.xywhs = xywhs\n this.acc_sums = acc_sums\n}\n\n\nSolution.prototype.pick = function() {\n const picked = Math.floor(\n Math.random() * this.acc_sums[this.acc_sums.length - 1]\n )\n let i = 0\n for (; i < this.acc_sums.length - 2; i++) {\n if (picked >= this.acc_sums[i] && picked < this.acc_sums[i + 1]) {\n break\n }\n }\n const { x, y, w, h } = this.xywhs[i]\n return [x + Math.floor(Math.random() * w), y + Math.floor(Math.random() * h)]\n}" ]
498
diagonal-traverse
[]
/** * @param {number[][]} mat * @return {number[]} */ var findDiagonalOrder = function(mat) { };
Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.   Example 1: Input: mat = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,4,7,5,3,6,8,9] Example 2: Input: mat = [[1,2],[3,4]] Output: [1,2,3,4]   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 104 1 <= m * n <= 104 -105 <= mat[i][j] <= 105
Medium
[ "array", "matrix", "simulation" ]
[ "const findDiagonalOrder = function(matrix) {\n if (!matrix.length || !matrix[0].length) {\n return []\n }\n const m = matrix.length\n const n = matrix[0].length\n const output = []\n for (let sum = 0; sum <= m + n - 2; sum++) {\n for (\n let i = Math.min(m - 1, sum);\n sum % 2 === 0 && isValid(i, sum - i, m, n);\n i--\n ) {\n const j = sum - i\n output.push(matrix[i][j])\n }\n for (\n let j = Math.min(n - 1, sum);\n sum % 2 === 1 && isValid(sum - j, j, m, n);\n j--\n ) {\n const i = sum - j\n output.push(matrix[i][j])\n }\n }\n return output\n}\n\nfunction isValid(i, j, m, n) {\n if (i < 0 || i >= m || j < 0 || j >= n) {\n return false\n }\n return true\n}", "const findDiagonalOrder = function(matrix) {\n if (matrix.length == 0) return []\n let r = 0,\n c = 0,\n m = matrix.length,\n n = matrix[0].length,\n arr = new Array(m * n)\n for (let i = 0; i < arr.length; i++) {\n arr[i] = matrix[r][c]\n if ((r + c) % 2 === 0) {\n // moving up\n if (c === n - 1) {\n r++\n } else if (r === 0) {\n c++\n } else {\n r--\n c++\n }\n } else {\n // moving down\n if (r === m - 1) {\n c++\n } else if (c === 0) {\n r++\n } else {\n r++\n c--\n }\n }\n }\n return arr\n}" ]
500
keyboard-row
[]
/** * @param {string[]} words * @return {string[]} */ var findWords = function(words) { };
Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below. In the American keyboard: the first row consists of the characters "qwertyuiop", the second row consists of the characters "asdfghjkl", and the third row consists of the characters "zxcvbnm".   Example 1: Input: words = ["Hello","Alaska","Dad","Peace"] Output: ["Alaska","Dad"] Example 2: Input: words = ["omk"] Output: [] Example 3: Input: words = ["adsdf","sfd"] Output: ["adsdf","sfd"]   Constraints: 1 <= words.length <= 20 1 <= words[i].length <= 100 words[i] consists of English letters (both lowercase and uppercase). 
Easy
[ "array", "hash-table", "string" ]
[ "const findWords = function(words) {\n const regex = /^[qwertyuiop]*$|^[asdfghjkl]*$|^[zxcvbnm]*$/;\n return words.filter(\n s => (s.toLowerCase().match(regex) === null ? false : true)\n );\n};\nconsole.log(findWords([\"Hello\", \"Alaska\", \"Dad\", \"Peace\"]));" ]
501
find-mode-in-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 findMode = function(root) { };
Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it. If the tree has more than one mode, return them in any order. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to the node's key. The right subtree of a node contains only nodes with keys greater than or equal to the node's key. Both the left and right subtrees must also be binary search trees.   Example 1: Input: root = [1,null,2,2] Output: [2] Example 2: Input: root = [0] Output: [0]   Constraints: The number of nodes in the tree is in the range [1, 104]. -105 <= Node.val <= 105   Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
Easy
[ "tree", "depth-first-search", "binary-search-tree", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const findMode = function(root) {\n if(root == null) return []\n const hash = {}\n traverse(root, hash)\n const res = Object.entries(hash).sort((a, b) => b[1] - a[1])\n const result = [res[0][0]]\n for(let i = 1; i < res.length; i++) {\n if(res[i][1] === res[0][1]) result.push(res[i][0])\n else break\n }\n return result\n};\n\nfunction traverse(node, hash) {\n if(node === null) return\n hash[node.val] = Object.prototype.hasOwnProperty.call(hash, node.val) ? hash[node.val] + 1 : 1\n traverse(node.left, hash)\n traverse(node.right, hash)\n}", "const findMode = function(root) {\n let res = [];\n let cnt = 1;\n let mx = 0;\n let pre = null;\n let search = function(node) {\n if (!node) return;\n search(node.left);\n if (pre) {\n cnt = (node.val === pre.val) ? cnt + 1 : 1;\n }\n if (cnt >= mx) {\n if (cnt > mx) res.length = 0;\n res.push(node.val);\n mx = cnt;\n }\n pre = node;\n search(node.right);\n }\n search(root);\n return res;\n};" ]
502
ipo
[]
/** * @param {number} k * @param {number} w * @param {number[]} profits * @param {number[]} capital * @return {number} */ var findMaximizedCapital = function(k, w, profits, capital) { };
Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital. The answer is guaranteed to fit in a 32-bit signed integer.   Example 1: Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] Output: 4 Explanation: Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. Example 2: Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] Output: 6   Constraints: 1 <= k <= 105 0 <= w <= 109 n == profits.length n == capital.length 1 <= n <= 105 0 <= profits[i] <= 104 0 <= capital[i] <= 109
Hard
[ "array", "greedy", "sorting", "heap-priority-queue" ]
[ "const findMaximizedCapital = function(k, W, Profits, Capital) {\n const capPQ = new PriorityQueue((a, b) => a.cap < b.cap)\n const proPQ = new PriorityQueue((a, b) => a.pro > b.pro)\n for(let i = 0, len = Profits.length; i < len; i++) {\n capPQ.push({ cap: Capital[i], pro: Profits[i] })\n }\n while(k) {\n while(!capPQ.isEmpty() && capPQ.peek().cap <= W) {\n proPQ.push(capPQ.pop())\n }\n if(proPQ.isEmpty()) break\n \n W += proPQ.pop().pro\n k--\n }\n return W\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}", "const findMaximizedCapital = function(k, W, Profits, Capital) {\n const idxArr = Profits.map((_, i) => i).sort((ia, ib) => Profits[ib] - Profits[ia]);\n while (k) {\n const choose = idxArr.findIndex(i => Capital[i] <= W);\n if (choose == -1) return W;\n W += Profits[idxArr[choose]];\n idxArr.splice(choose, 1);\n k--;\n }\n return W;\n};", "const findMaximizedCapital = function(k, w, profits, capital) {\n const capPQ = new PQ((a, b) => a.cap < b.cap)\n const proPQ = new PQ((a, b) => a.pro > b.pro)\n const n = profits.length\n \n for(let i = 0; i < n; i++) {\n capPQ.push({ cap: capital[i], pro: profits[i] })\n }\n \n while(k) {\n \n while(!capPQ.isEmpty() && capPQ.peek().cap <= w) {\n proPQ.push(capPQ.pop())\n }\n \n if(proPQ.isEmpty()) break\n \n w += proPQ.pop().pro\n k--\n }\n \n \n return w\n};\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}" ]
503
next-greater-element-ii
[]
/** * @param {number[]} nums * @return {number[]} */ var nextGreaterElements = function(nums) { };
Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.   Example 1: Input: nums = [1,2,1] Output: [2,-1,2] Explanation: The first 1's next greater number is 2; The number 2 can't find next greater number. The second 1's next greater number needs to search circularly, which is also 2. Example 2: Input: nums = [1,2,3,4,3] Output: [2,3,4,-1,4]   Constraints: 1 <= nums.length <= 104 -109 <= nums[i] <= 109
Medium
[ "array", "stack", "monotonic-stack" ]
[ "const nextGreaterElements = function(nums) {\n const arr = []\n const n = nums.length\n const res = Array(n).fill(-1)\n nums.push(...nums)\n const stk = []\n for(let i = 0; i < 2 * n; i++) {\n const e = nums[i]\n while(stk.length && nums[stk.at(-1)] < e) {\n const idx = stk.pop()\n res[idx] = e\n }\n if(i < n) stk.push(i)\n }\n \n return res\n};", "const nextGreaterElements = function(nums) {\n const res = [];\n for (let i = 0; i < nums.length; i++) {\n res.push(single(i, nums));\n }\n return res;\n};\n\nfunction single(idx, arr) {\n const base = arr[idx];\n const prev = idx === 0 ? [] : arr.slice(0, idx);\n const next = arr.slice(idx);\n const comb = next.concat(prev);\n for (let i = 0; i < comb.length; i++) {\n if (comb[i] > base) return comb[i];\n }\n return -1;\n}", " const nextGreaterElements = function(nums) {\n const res = [], n = nums.length\n const stack = []\n for(let i = 2 * n - 1; i >= 0; i--) {\n while(stack.length && nums[stack[stack.length - 1]] <= nums[i % n]) {\n stack.pop()\n }\n res[i % n] = stack.length ? nums[stack[stack.length - 1]] : -1\n stack.push(i % n)\n }\n\n return res\n};" ]
504
base-7
[]
/** * @param {number} num * @return {string} */ var convertToBase7 = function(num) { };
Given an integer num, return a string of its base 7 representation.   Example 1: Input: num = 100 Output: "202" Example 2: Input: num = -7 Output: "-10"   Constraints: -107 <= num <= 107
Easy
[ "math" ]
[ "const convertToBase7 = function(num) {\n if(num == null) return ''\n const sign = num >= 0 ? '+' : '-'\n let res = ''\n let remain = Math.abs(num)\n if(num === 0) return '0'\n while(remain > 0) {\n res = remain % 7 + res\n remain = Math.floor(remain / 7)\n }\n \n return sign === '+' ? res : '-' + res\n};", "const convertToBase7 = function(num) {\n return num.toString(7)\n};" ]
506
relative-ranks
[]
/** * @param {number[]} score * @return {string[]} */ var findRelativeRanks = function(score) { };
You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique. The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank: The 1st place athlete's rank is "Gold Medal". The 2nd place athlete's rank is "Silver Medal". The 3rd place athlete's rank is "Bronze Medal". For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is "x"). Return an array answer of size n where answer[i] is the rank of the ith athlete.   Example 1: Input: score = [5,4,3,2,1] Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"] Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th]. Example 2: Input: score = [10,3,8,9,4] Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"] Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th].   Constraints: n == score.length 1 <= n <= 104 0 <= score[i] <= 106 All the values in score are unique.
Easy
[ "array", "sorting", "heap-priority-queue" ]
[ "const findRelativeRanks = function(nums) {\n const numIndexMapping = {}\n for (let index = 0; index < nums.length; ++index) {\n numIndexMapping[nums[index]] = index\n }\n let rank = nums.length\n for (let num in numIndexMapping) {\n const index = numIndexMapping[num]\n if (3 < rank) {\n nums[index] = '' + rank\n } else if (3 == rank) {\n nums[index] = 'Bronze Medal'\n } else if (2 == rank) {\n nums[index] = 'Silver Medal'\n } else {\n nums[index] = 'Gold Medal'\n }\n --rank\n }\n\n return nums\n}" ]