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 |
---|---|---|---|---|---|---|---|---|
669 | trim-a-binary-search-tree | [] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} low
* @param {number} high
* @return {TreeNode}
*/
var trimBST = function(root, low, high) {
}; | Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.
Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.
Example 1:
Input: root = [1,0,2], low = 1, high = 2
Output: [1,null,2]
Example 2:
Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
Output: [3,2,null,1]
Constraints:
The number of nodes in the tree is in the range [1, 104].
0 <= Node.val <= 104
The value of each node in the tree is unique.
root is guaranteed to be a valid binary search tree.
0 <= low <= high <= 104
| Medium | [
"tree",
"depth-first-search",
"binary-search-tree",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const trimBST = function(root, L, R) {\n return single(root, L, R);\n};\n\nfunction single(node, L, R) {\n if (node === null) {\n return null;\n }\n if (node.val > R) {\n return single(node.left, L, R);\n }\n if (node.val < L) {\n return single(node.right, L, R);\n }\n if (node.left !== null) {\n node.left = single(node.left, L, R);\n }\n if (node.right !== null) {\n node.right = single(node.right, L, R);\n }\n return node;\n}"
] |
670 | maximum-swap | [] | /**
* @param {number} num
* @return {number}
*/
var maximumSwap = function(num) {
}; | You are given an integer num. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
Example 1:
Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: num = 9973
Output: 9973
Explanation: No swap.
Constraints:
0 <= num <= 108
| Medium | [
"math",
"greedy"
] | [
"const maximumSwap = function(num) {\n const arr = ('' + num).split('')\n for(let i = 0; i < arr.length - 1; i++) {\n let cur = +arr[i]\n let nextMax = Math.max(...arr.slice(i+1).map(el => +el))\n if (nextMax > cur) {\n let idx = arr.lastIndexOf(''+nextMax)\n arr[i] = nextMax\n arr[idx] = cur\n break\n }\n }\n return +(arr.join(''))\n};"
] |
|
671 | second-minimum-node-in-a-binary-tree | [] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var findSecondMinimumValue = function(root) {
}; | Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example 1:
Input: root = [2,2,5,null,null,5,7]
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input: root = [2,2,2]
Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
Constraints:
The number of nodes in the tree is in the range [1, 25].
1 <= Node.val <= 231 - 1
root.val == min(root.left.val, root.right.val) for each internal node of the tree.
| Easy | [
"tree",
"depth-first-search",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const findSecondMinimumValue = function(root) {\n if(root == null) return -1\n const q = [root]\n let min = Number.MAX_VALUE\n let min2nd = Number.MAX_VALUE\n while(q.length) {\n const len = q.length\n for(let i = 0; i < len; i++) {\n const cur = q.shift()\n if(cur.val <= min) {\n min = cur.val\n } else if(cur.val > min && cur.val < min2nd) {\n min2nd = cur.val\n }\n if(cur.left) q.push(cur.left)\n if(cur.right) q.push(cur.right)\n }\n }\n return min2nd === Number.MAX_VALUE ? -1 : min2nd\n};",
"const findSecondMinimumValue = function (root) {\n if (root === null) return -1;\n if (root.left === null && root.right === null) return -1;\n let left = root.left.val;\n let right = root.right.val;\n if (left === root.val) {\n left = findSecondMinimumValue(root.left);\n }\n if (right === root.val) {\n right = findSecondMinimumValue(root.right);\n }\n if (right !== -1 && left !== -1) {\n return Math.min(left, right);\n }\n if (right === -1) {\n return left;\n }\n if (left === -1) {\n return right;\n }\n};"
] |
672 | bulb-switcher-ii | [] | /**
* @param {number} n
* @param {number} presses
* @return {number}
*/
var flipLights = function(n, presses) {
}; | There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where:
Button 1: Flips the status of all the bulbs.
Button 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ...).
Button 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ...).
Button 4: Flips the status of all the bulbs with a label j = 3k + 1 where k = 0, 1, 2, ... (i.e., 1, 4, 7, 10, ...).
You must make exactly presses button presses in total. For each press, you may pick any of the four buttons to press.
Given the two integers n and presses, return the number of different possible statuses after performing all presses button presses.
Example 1:
Input: n = 1, presses = 1
Output: 2
Explanation: Status can be:
- [off] by pressing button 1
- [on] by pressing button 2
Example 2:
Input: n = 2, presses = 1
Output: 3
Explanation: Status can be:
- [off, off] by pressing button 1
- [on, off] by pressing button 2
- [off, on] by pressing button 3
Example 3:
Input: n = 3, presses = 1
Output: 4
Explanation: Status can be:
- [off, off, off] by pressing button 1
- [off, on, off] by pressing button 2
- [on, off, on] by pressing button 3
- [off, on, on] by pressing button 4
Constraints:
1 <= n <= 1000
0 <= presses <= 1000
| Medium | [
"math",
"bit-manipulation",
"depth-first-search",
"breadth-first-search"
] | [
"const flipLights = function (n, m) {\n n = Math.min(n, 3)\n if (m === 0) return 1\n if (m === 1) return n === 1 ? 2 : n === 2 ? 3 : 4\n if (m === 2) return n === 1 ? 2 : n === 2 ? 4 : 7\n return n === 1 ? 2 : n === 2 ? 4 : 8\n}"
] |
|
673 | number-of-longest-increasing-subsequence | [] | /**
* @param {number[]} nums
* @return {number}
*/
var findNumberOfLIS = function(nums) {
}; | Given an integer array nums, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
Example 1:
Input: nums = [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: nums = [2,2,2,2,2]
Output: 5
Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
Constraints:
1 <= nums.length <= 2000
-106 <= nums[i] <= 106
| Medium | [
"array",
"dynamic-programming",
"binary-indexed-tree",
"segment-tree"
] | [
"const findNumberOfLIS = function(nums) {\n if (nums.length === 0) return 0;\n const len = new Array(nums.length);\n const cnt = new Array(nums.length);\n let max = 1;\n let res=1;\n len[0] = 1;\n cnt[0] = 1;\n for (let i = 1; i < nums.length; i++) {\n len[i] = 1;\n cnt[i] = 1;\n for (let j = 0; j < i; j++) {\n if (nums[j] < nums[i]) {\n if (len[j] + 1 > len[i]) {\n cnt[i] = cnt[j];\n len[i] = len[j] + 1;\n } else if (len[j] + 1 === len[i]) {\n cnt[i] += cnt[j];\n }\n }\n }\n if (len[i] > max) {\n max = len[i];\n res = cnt[i];\n } else if (len[i] === max) {\n res += cnt[i];\n }\n }\n return res;\n};"
] |
|
674 | longest-continuous-increasing-subsequence | [] | /**
* @param {number[]} nums
* @return {number}
*/
var findLengthOfLCIS = function(nums) {
}; | Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.
A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1].
Example 1:
Input: nums = [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
Example 2:
Input: nums = [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
Constraints:
1 <= nums.length <= 104
-109 <= nums[i] <= 109
| Easy | [
"array"
] | [
"const findLengthOfLCIS = function(nums) {\n if (nums.length == 1) {\n return 1;\n }\n let ans = 0,\n anchor = 0;\n for (let i = 1; i < nums.length; i++) {\n if (nums[i - 1] >= nums[i]) {\n anchor = i;\n }\n ans = Math.max(ans, i - anchor + 1);\n }\n return ans;\n};"
] |
|
675 | cut-off-trees-for-golf-event | [] | /**
* @param {number[][]} forest
* @return {number}
*/
var cutOffTree = function(forest) {
}; | You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix:
0 means the cell cannot be walked through.
1 represents an empty cell that can be walked through.
A number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree's height.
In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.
You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell).
Starting from the point (0, 0), return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1.
Note: The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.
Example 1:
Input: forest = [[1,2,3],[0,0,4],[7,6,5]]
Output: 6
Explanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.
Example 2:
Input: forest = [[1,2,3],[0,0,0],[7,6,5]]
Output: -1
Explanation: The trees in the bottom row cannot be accessed as the middle row is blocked.
Example 3:
Input: forest = [[2,3,4],[0,0,5],[8,7,6]]
Output: 6
Explanation: You can follow the same path as Example 1 to cut off all the trees.
Note that you can cut off the first tree at (0, 0) before making any steps.
Constraints:
m == forest.length
n == forest[i].length
1 <= m, n <= 50
0 <= forest[i][j] <= 109
Heights of all trees are distinct.
| Hard | [
"array",
"breadth-first-search",
"heap-priority-queue",
"matrix"
] | [
"const cutOffTree = function (forest) {\n const n = forest.length\n if (n === 0) return 0\n const m = forest[0].length\n if (m === 0) return 0\n const entries = []\n for (let i = 0; i < n; i += 1) {\n for (let j = 0; j < m; j += 1) {\n if (forest[i][j] > 0) {\n entries.push([forest[i][j], i, j])\n }\n }\n }\n entries.sort((e1, e2) => e1[0] - e2[0])\n const direct = [\n [1, 0],\n [-1, 0],\n [0, 1],\n [0, -1],\n ]\n const visited = Array(n)\n .fill(null)\n .map(() => Array(m).fill(0))\n const bfs = function (start, end) {\n for (let i = 0; i < n; i += 1)\n for (let j = 0; j < m; j += 1) visited[i][j] = 0\n let cur = [start],\n next = [],\n step = 0\n visited[start[0]][start[1]] = 1\n while (cur.length > 0) {\n next = []\n for (const [x, y] of cur) {\n if (x === end[0] && y === end[1]) return step\n for (const [dx, dy] of direct) {\n const p = x + dx,\n q = y + dy\n if (\n p < 0 ||\n q < 0 ||\n p >= n ||\n q >= m ||\n visited[p][q] === 1 ||\n forest[p][q] === 0\n )\n continue\n visited[p][q] = 1\n next.push([p, q])\n }\n }\n step += 1\n cur = next\n }\n return -1\n }\n let pre = [0, 0],\n totalCnt = 0\n for (const entry of entries) {\n const step = bfs(pre, entry.slice(1))\n if (step === -1) return -1\n totalCnt += step\n pre = entry.slice(1)\n }\n return totalCnt\n}"
] |
|
676 | implement-magic-dictionary | [] |
var MagicDictionary = function() {
};
/**
* @param {string[]} dictionary
* @return {void}
*/
MagicDictionary.prototype.buildDict = function(dictionary) {
};
/**
* @param {string} searchWord
* @return {boolean}
*/
MagicDictionary.prototype.search = function(searchWord) {
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* var obj = new MagicDictionary()
* obj.buildDict(dictionary)
* var param_2 = obj.search(searchWord)
*/ | Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the MagicDictionary class:
MagicDictionary() Initializes the object.
void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary.
bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false.
Example 1:
Input
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
Output
[null, null, false, true, false, false]
Explanation
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // return False
magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
magicDictionary.search("hell"); // return False
magicDictionary.search("leetcoded"); // return False
Constraints:
1 <= dictionary.length <= 100
1 <= dictionary[i].length <= 100
dictionary[i] consists of only lower-case English letters.
All the strings in dictionary are distinct.
1 <= searchWord.length <= 100
searchWord consists of only lower-case English letters.
buildDict will be called only once before search.
At most 100 calls will be made to search.
| Medium | [
"hash-table",
"string",
"depth-first-search",
"design",
"trie"
] | [
"const MagicDictionary = function(dict) {\n this.dict = [];\n};\n\n\nMagicDictionary.prototype.buildDict = function(dict) {\n this.dict = dict;\n};\n\n\nMagicDictionary.prototype.search = function(word) {\n return check(word, this.dict);\n};\n\n\n\nfunction check(str, arr) {\n let el;\n for (let i = 0; i < arr.length; i++) {\n el = arr[i];\n if (el.length === str.length && oneCharDiff(el, str)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction oneCharDiff(str1, str2) {\n let diff = 0;\n for (let i = 0; i < str1.length; i++) {\n if (str1[i] !== str2[i]) {\n diff += 1;\n }\n }\n return diff === 1 ? true : false;\n}"
] |
|
677 | map-sum-pairs | [] |
var MapSum = function() {
};
/**
* @param {string} key
* @param {number} val
* @return {void}
*/
MapSum.prototype.insert = function(key, val) {
};
/**
* @param {string} prefix
* @return {number}
*/
MapSum.prototype.sum = function(prefix) {
};
/**
* Your MapSum object will be instantiated and called as such:
* var obj = new MapSum()
* obj.insert(key,val)
* var param_2 = obj.sum(prefix)
*/ | Design a map that allows you to do the following:
Maps a string key to a given value.
Returns the sum of the values that have a key with a prefix equal to a given string.
Implement the MapSum class:
MapSum() Initializes the MapSum object.
void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.
int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix.
Example 1:
Input
["MapSum", "insert", "sum", "insert", "sum"]
[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
Output
[null, null, 3, null, 5]
Explanation
MapSum mapSum = new MapSum();
mapSum.insert("apple", 3);
mapSum.sum("ap"); // return 3 (apple = 3)
mapSum.insert("app", 2);
mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5)
Constraints:
1 <= key.length, prefix.length <= 50
key and prefix consist of only lowercase English letters.
1 <= val <= 1000
At most 50 calls will be made to insert and sum.
| Medium | [
"hash-table",
"string",
"design",
"trie"
] | [
"const MapSum = function() {\n this.hash = {};\n};\n\n\nMapSum.prototype.insert = function(key, val) {\n this.hash[key] = val;\n};\n\n\nMapSum.prototype.sum = function(prefix) {\n let res = 0;\n Object.keys(this.hash).forEach(el => {\n if (el.indexOf(prefix) === 0) {\n res += this.hash[el];\n }\n });\n return res;\n};"
] |
|
678 | valid-parenthesis-string | [] | /**
* @param {string} s
* @return {boolean}
*/
var checkValidString = function(s) {
}; | Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.
The following rules define a valid string:
Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a corresponding left parenthesis '('.
Left parenthesis '(' must go before the corresponding right parenthesis ')'.
'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "(*)"
Output: true
Example 3:
Input: s = "(*))"
Output: true
Constraints:
1 <= s.length <= 100
s[i] is '(', ')' or '*'.
| Medium | [
"string",
"dynamic-programming",
"stack",
"greedy"
] | [
"const checkValidString = function(s) {\n let lo = 0, hi = 0;\n for (let i = 0; i < s.length; i++) {\n lo += s[i] == '(' ? 1 : -1;\n hi += s[i] != ')' ? 1 : -1;\n if (hi < 0) break;\n lo = Math.max(lo, 0);\n }\n return lo === 0;\n};",
" const checkValidString = function (s) {\n let lo = 0, hi = 0 // 可能多余的‘(’\n for(let ch of s) {\n if(ch === '(') lo++, hi++\n if(ch === ')') {\n if(lo > 0) lo--\n hi--\n }\n if(ch === '*') {\n if(lo > 0) lo--\n hi++\n }\n if(hi < 0) return false\n }\n return lo === 0\n}"
] |
|
679 | 24-game | [] | /**
* @param {number[]} cards
* @return {boolean}
*/
var judgePoint24 = function(cards) {
}; | You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24.
You are restricted with the following rules:
The division operator '/' represents real division, not integer division.
For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12.
Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator.
For example, if cards = [1, 1, 1, 1], the expression "-1 - 1 - 1 - 1" is not allowed.
You cannot concatenate numbers together
For example, if cards = [1, 2, 1, 2], the expression "12 + 12" is not valid.
Return true if you can get such expression that evaluates to 24, and false otherwise.
Example 1:
Input: cards = [4,1,8,7]
Output: true
Explanation: (8-4) * (7-1) = 24
Example 2:
Input: cards = [1,2,1,2]
Output: false
Constraints:
cards.length == 4
1 <= cards[i] <= 9
| Hard | [
"array",
"math",
"backtracking"
] | [
"const judgePoint24 = function(nums) {\n return dfs(nums)\n}\n\nfunction dfs(list) {\n let eps = 0.0001\n if (list.length === 1) {\n if (Math.abs(list[0] - 24) < eps) {\n return true\n }\n return false\n }\n let n = list.length\n for (let i = 0; i < n; i++) {\n for (let j = i + 1; j < n; j++) {\n const next = new Array(n - 1)\n for (let k = 0, index = 0; k < n; k++) {\n if (k !== i && k !== j) next[index++] = list[k]\n }\n let d1 = list[i],\n d2 = list[j]\n const dirs = [d1 + d2, d1 - d2, d2 - d1, d2 * d1]\n if (d1 > eps) dirs.push(d2 / d1)\n if (d2 > eps) dirs.push(d1 / d2)\n for (let dir of dirs) {\n next[n - 2] = dir\n if (dfs(next)) return true\n }\n }\n }\n return false\n}",
"const judgePoint24 = function(nums) {\n return dfs(nums);\n};\n\nfunction dfs(list) {\n if (list.length === 1) {\n if (Math.abs(list[0] - 24) < 0.001) {\n return true;\n }\n return false;\n }\n for (let i = 0; i < list.length; i++) {\n for (let j = i + 1; j < list.length; j++) {\n for (let c of compute(list[i], list[j])) {\n let nextRound = [];\n nextRound.push(c);\n for (let k = 0; k < list.length; k++) {\n if (k === j || k === i) continue;\n nextRound.push(list[k]);\n }\n if (dfs(nextRound)) return true;\n }\n }\n }\n return false;\n}\n\nfunction compute(a, b) {\n return [a + b, a - b, b - a, a * b, a / b, b / a];\n}"
] |
|
680 | valid-palindrome-ii | [] | /**
* @param {string} s
* @return {boolean}
*/
var validPalindrome = function(s) {
}; | Given a string s, return true if the s can be palindrome after deleting at most one character from it.
Example 1:
Input: s = "aba"
Output: true
Example 2:
Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.
Example 3:
Input: s = "abc"
Output: false
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
| Easy | [
"two-pointers",
"string",
"greedy"
] | [
"const validPalindrome = function(s) {\n let start = 0;\n let end = s.length - 1;\n\n const isPalindrome = function(start, end, removed) {\n while (start <= end) {\n if (s[start] !== s[end]) {\n if (removed) {\n return false;\n }\n\n return (\n isPalindrome(start + 1, end, true) ||\n isPalindrome(start, end - 1, true)\n );\n }\n start++;\n end--;\n }\n return true;\n };\n\n return isPalindrome(start, end, false);\n};"
] |
|
682 | baseball-game | [] | /**
* @param {string[]} operations
* @return {number}
*/
var calPoints = function(operations) {
}; | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings operations, where operations[i] is the ith operation you must apply to the record and is one of the following:
An integer x.
Record a new score of x.
'+'.
Record a new score that is the sum of the previous two scores.
'D'.
Record a new score that is the double of the previous score.
'C'.
Invalidate the previous score, removing it from the record.
Return the sum of all the scores on the record after applying all the operations.
The test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid.
Example 1:
Input: ops = ["5","2","C","D","+"]
Output: 30
Explanation:
"5" - Add 5 to the record, record is now [5].
"2" - Add 2 to the record, record is now [5, 2].
"C" - Invalidate and remove the previous score, record is now [5].
"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
The total sum is 5 + 10 + 15 = 30.
Example 2:
Input: ops = ["5","-2","4","C","D","9","+","+"]
Output: 27
Explanation:
"5" - Add 5 to the record, record is now [5].
"-2" - Add -2 to the record, record is now [5, -2].
"4" - Add 4 to the record, record is now [5, -2, 4].
"C" - Invalidate and remove the previous score, record is now [5, -2].
"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].
"9" - Add 9 to the record, record is now [5, -2, -4, 9].
"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].
"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].
The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.
Example 3:
Input: ops = ["1","C"]
Output: 0
Explanation:
"1" - Add 1 to the record, record is now [1].
"C" - Invalidate and remove the previous score, record is now [].
Since the record is empty, the total sum is 0.
Constraints:
1 <= operations.length <= 1000
operations[i] is "C", "D", "+", or a string representing an integer in the range [-3 * 104, 3 * 104].
For operation "+", there will always be at least two previous scores on the record.
For operations "C" and "D", there will always be at least one previous score on the record.
| Easy | [
"array",
"stack",
"simulation"
] | [
"const calPoints = function(ops) {\n const opArr = [\"C\", \"D\", \"+\"];\n const arr = [];\n ops.forEach((el, idx) => {\n const item = {\n value: 0,\n valid: true\n };\n switch (el) {\n case \"C\":\n findValid(arr, idx, 1).forEach(el => {\n el.value = 0;\n el.valid = false;\n });\n item.valid = false;\n break;\n case \"D\":\n item.value = findValid(arr, idx, 1)[0].value * 2;\n break;\n case \"+\":\n item.value = findValid(arr, idx, 2).reduce(\n (ac, ele) => ac + ele.value,\n 0\n );\n break;\n default:\n item.value = +el;\n break;\n }\n arr.push(item);\n });\n return arr.reduce((ac, el) => ac + el.value, 0);\n};\n\nfunction findValid(arr, idx, backStep) {\n const res = [];\n while (backStep > 0 && idx - 1 >= 0) {\n if (arr[idx - 1].valid === true) {\n backStep -= 1;\n res.push(arr[idx - 1]);\n }\n idx -= 1;\n }\n return res;\n}\n\nconsole.log(calPoints([\"5\", \"2\", \"C\", \"D\", \"+\"]));\nconsole.log(calPoints([\"5\", \"-2\", \"4\", \"C\", \"D\", \"9\", \"+\", \"+\"]));"
] |
|
684 | redundant-connection | [] | /**
* @param {number[][]} edges
* @return {number[]}
*/
var findRedundantConnection = function(edges) {
}; | In this problem, a tree is an undirected graph that is connected and has no cycles.
You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.
Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.
Example 1:
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Example 2:
Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output: [1,4]
Constraints:
n == edges.length
3 <= n <= 1000
edges[i].length == 2
1 <= ai < bi <= edges.length
ai != bi
There are no repeated edges.
The given graph is connected.
| Medium | [
"depth-first-search",
"breadth-first-search",
"union-find",
"graph"
] | [
"const findRedundantConnection = function (edges) {\n const uf = {}\n for (let edge of edges) {\n let u = edge[0]\n let v = edge[1]\n if (find(u) === find(v)) {\n return edge\n } else {\n union(u, v)\n }\n }\n function union(a, b) {\n uf[find(a)] = uf[find(b)]\n }\n function find(x) {\n if (!uf[x]) uf[x] = x\n if (uf[x] === x) return x\n return find(uf[x])\n }\n}"
] |
|
685 | redundant-connection-ii | [] | /**
* @param {number[][]} edges
* @return {number[]}
*/
var findRedundantDirectedConnection = function(edges) {
}; | In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.
The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed.
The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [ui, vi] that represents a directed edge connecting nodes ui and vi, where ui is a parent of child vi.
Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.
Example 1:
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Example 2:
Input: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]
Output: [4,1]
Constraints:
n == edges.length
3 <= n <= 1000
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
| Hard | [
"depth-first-search",
"breadth-first-search",
"union-find",
"graph"
] | [
"const findRedundantDirectedConnection = function (edges) {\n const parent = []\n //detect circle\n for (let i = 1; i <= edges.length; i++) {\n parent[i] = i\n }\n let circleEdge, removedEdge, candidateEdge\n for (let i = 0; i < edges.length; i++) {\n const [u, v] = edges[i]\n const pu = findParent(parent, u)\n const pv = findParent(parent, v)\n if (pv !== v) {\n removedEdge = [u, v] // node with 2 parents\n } else {\n if (pv === pu) {\n circleEdge = [u, v] // circle edge\n }\n parent[v] = pu\n }\n }\n if (!removedEdge) {\n return circleEdge\n }\n if (circleEdge) {\n return edges.find((d) => d[1] === removedEdge[1] && d[0] !== removedEdge[0])\n } else {\n return removedEdge\n }\n}\nconst findParent = function (parent, i) {\n if (parent[i] !== i) {\n parent[i] = findParent(parent, parent[i])\n }\n return parent[i]\n}"
] |
|
686 | repeated-string-match | [] | /**
* @param {string} a
* @param {string} b
* @return {number}
*/
var repeatedStringMatch = function(a, b) {
}; | Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b to be a substring of a after repeating it, return -1.
Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc".
Example 1:
Input: a = "abcd", b = "cdabcdab"
Output: 3
Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.
Example 2:
Input: a = "a", b = "aa"
Output: 2
Constraints:
1 <= a.length, b.length <= 104
a and b consist of lowercase English letters.
| Medium | [
"string",
"string-matching"
] | [
"const repeatedStringMatch = function(A, B) {\n let count = Math.ceil(B.length / A.length);\n let testString = A.repeat(count)\n \n return testString.includes(B) ? count : (testString + A).includes(B) ? count + 1 : -1\n};\n// Form a string of length N from each index in A. \n// If any of these string equals B, then B is a substring of A.\n// const repeatedStringMatch = function(A, B) {\n// for (let i = 0; i < A.length; i++) {\n// if (A.charAt(i) === B.charAt(0)) {\n// let count = 1;\n// let j = 0;\n// let startIx = i;\n// while (j < B.length && A.charAt(startIx) === B.charAt(j)) {\n// j++;\n// startIx++;\n// if (startIx >= A.length && j < B.length) {\n// startIx = startIx % A.length;\n// count++;\n// }\n// }\n// if (j == B.length) return count;\n// }\n// }\n// return -1;\n// };"
] |
|
687 | longest-univalue-path | [] | /**
* 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 longestUnivaluePath = function(root) {
}; | Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.
The length of the path between two nodes is represented by the number of edges between them.
Example 1:
Input: root = [5,4,5,1,1,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 5).
Example 2:
Input: root = [1,4,5,4,4,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 4).
Constraints:
The number of nodes in the tree is in the range [0, 104].
-1000 <= Node.val <= 1000
The depth of the tree will not exceed 1000.
| Medium | [
"tree",
"depth-first-search",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const longestUnivaluePath = function(root) {\n let res = 0\n dfs(root)\n return res\n\n function dfs(node) {\n if(node == null) return 0\n let left = dfs(node.left), right = dfs(node.right)\n if(node.left && node.left.val === node.val) left++\n else left = 0\n\n if(node.right && node.right.val === node.val) right++\n else right = 0\n\n res = Math.max(res, left + right)\n return Math.max(left, right)\n }\n};",
"const getCount = function(root, longest) {\n if (!root) {\n return 0;\n }\n let leftCount = getCount(root.left, longest);\n let rightCount = getCount(root.right, longest);\n if (root.left && root.left.val === root.val) {\n leftCount++;\n } else {\n leftCount = 0;\n }\n if (root.right && root.right.val === root.val) {\n rightCount++;\n } else {\n rightCount = 0;\n }\n longest.max = Math.max(longest.max, leftCount + rightCount);\n return Math.max(leftCount, rightCount);\n};\n\nconst longestUnivaluePath = function(root) {\n let longest = { max: 0 };\n getCount(root, longest);\n return longest.max;\n};"
] |
688 | knight-probability-in-chessboard | [] | /**
* @param {number} n
* @param {number} k
* @param {number} row
* @param {number} column
* @return {number}
*/
var knightProbability = function(n, k, row, column) {
}; | On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1).
A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.
Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.
The knight continues moving until it has made exactly k moves or has moved off the chessboard.
Return the probability that the knight remains on the board after it has stopped moving.
Example 1:
Input: n = 3, k = 2, row = 0, column = 0
Output: 0.06250
Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
From each of those positions, there are also two moves that will keep the knight on the board.
The total probability the knight stays on the board is 0.0625.
Example 2:
Input: n = 1, k = 0, row = 0, column = 0
Output: 1.00000
Constraints:
1 <= n <= 25
0 <= k <= 100
0 <= row, column <= n - 1
| Medium | [
"dynamic-programming"
] | [
"const knightProbability = function (N, K, r, c) {\n const moves = [\n [1, 2],\n [1, -2],\n [2, 1],\n [2, -1],\n [-1, 2],\n [-1, -2],\n [-2, 1],\n [-2, -1],\n ]\n const dp = [...Array(K + 1)].map(() =>\n [...Array(N)].map(() => Array(N).fill(0))\n )\n dp[0][r][c] = 1\n for (let step = 1; step <= K; step++) {\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < N; j++) {\n for (let move of moves) {\n let row = i + move[0],\n col = j + move[1]\n if (row >= 0 && row < N && col >= 0 && col < N)\n dp[step][i][j] += dp[step - 1][row][col] / 8\n }\n }\n }\n }\n let res = 0\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < N; j++) {\n res += dp[K][i][j]\n }\n }\n return res\n}"
] |
|
689 | maximum-sum-of-3-non-overlapping-subarrays | [] | /**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var maxSumOfThreeSubarrays = function(nums, k) {
}; | Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
Example 1:
Input: nums = [1,2,1,2,6,7,5,1], k = 2
Output: [0,3,5]
Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.
Example 2:
Input: nums = [1,2,1,2,1,2,1,2,1], k = 2
Output: [0,2,4]
Constraints:
1 <= nums.length <= 2 * 104
1 <= nums[i] < 216
1 <= k <= floor(nums.length / 3)
| Hard | [
"array",
"dynamic-programming"
] | [
"const maxSumOfThreeSubarrays = (nums, k) => {\n let n = nums.length,\n maxsum = 0\n let sum = new Array(n + 1).fill(0),\n posLeft = new Array(n).fill(0),\n posRight = new Array(n).fill(0),\n ans = new Array(3).fill(0)\n for (let i = 0; i < n; i++) sum[i + 1] = sum[i] + nums[i]\n for (let i = k, tot = sum[k] - sum[0]; i < n; i++) {\n if (sum[i + 1] - sum[i + 1 - k] > tot) {\n posLeft[i] = i + 1 - k\n tot = sum[i + 1] - sum[i + 1 - k]\n } else posLeft[i] = posLeft[i - 1]\n }\n posRight[n - k] = n - k\n for (let i = n - k - 1, tot = sum[n] - sum[n - k]; i >= 0; i--) {\n if (sum[i + k] - sum[i] >= tot) {\n posRight[i] = i\n tot = sum[i + k] - sum[i]\n } else posRight[i] = posRight[i + 1]\n }\n for (let i = k; i <= n - 2 * k; i++) {\n let l = posLeft[i - 1],\n r = posRight[i + k]\n let tot = sum[i + k] - sum[i] + (sum[l + k] - sum[l]) + (sum[r + k] - sum[r])\n if (tot > maxsum) {\n maxsum = tot\n ans[0] = l\n ans[1] = i\n ans[2] = r\n }\n }\n return ans\n}"
] |
|
690 | employee-importance | [] | /**
* Definition for Employee.
* function Employee(id, importance, subordinates) {
* this.id = id;
* this.importance = importance;
* this.subordinates = subordinates;
* }
*/
/**
* @param {Employee[]} employees
* @param {number} id
* @return {number}
*/
var GetImportance = function(employees, id) {
}; | You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.
You are given an array of employees employees where:
employees[i].id is the ID of the ith employee.
employees[i].importance is the importance value of the ith employee.
employees[i].subordinates is a list of the IDs of the direct subordinates of the ith employee.
Given an integer id that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates.
Example 1:
Input: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1
Output: 11
Explanation: Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.
They both have an importance value of 3.
Thus, the total importance value of employee 1 is 5 + 3 + 3 = 11.
Example 2:
Input: employees = [[1,2,[5]],[5,-3,[]]], id = 5
Output: -3
Explanation: Employee 5 has an importance value of -3 and has no direct subordinates.
Thus, the total importance value of employee 5 is -3.
Constraints:
1 <= employees.length <= 2000
1 <= employees[i].id <= 2000
All employees[i].id are unique.
-100 <= employees[i].importance <= 100
One employee has at most one direct leader and may have several subordinates.
The IDs in employees[i].subordinates are valid IDs.
| Medium | [
"hash-table",
"depth-first-search",
"breadth-first-search"
] | /**
* Definition for Employee.
* function Employee(id, importance, subordinates) {
* this.id = id;
* this.importance = importance;
* this.subordinates = subordinates;
* }
*/ | [
"const GetImportance = function (employees, id) {\n const map = {}\n employees.forEach((employee) => {\n map[employee.id] = employee\n })\n const s = [id]\n let importance = 0\n while (s.length) {\n let current = map[s.pop()]\n importance += current.importance\n if (current.subordinates.length) {\n s.push(...current.subordinates.reverse())\n }\n }\n return importance\n}"
] |
691 | stickers-to-spell-word | [
"We want to perform an exhaustive search, but we need to speed it up based on the input data being random. \r\n\r\nFor all stickers, we can ignore any letters that are not in the target word. \r\n\r\nWhen our candidate answer won't be smaller than an answer we have already found, we can stop searching this path. \r\n\r\nWhen a sticker dominates another, we shouldn't include the dominated sticker in our sticker collection. [Here, we say a sticker `A` dominates `B` if `A.count(letter) >= B.count(letter)` for all letters.]"
] | /**
* @param {string[]} stickers
* @param {string} target
* @return {number}
*/
var minStickers = function(stickers, target) {
}; | We are given n different types of stickers. Each sticker has a lowercase English word on it.
You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.
Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.
Example 1:
Input: stickers = ["with","example","science"], target = "thehat"
Output: 3
Explanation:
We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.
Example 2:
Input: stickers = ["notice","possible"], target = "basicbasic"
Output: -1
Explanation:
We cannot form the target "basicbasic" from cutting letters from the given stickers.
Constraints:
n == stickers.length
1 <= n <= 50
1 <= stickers[i].length <= 10
1 <= target.length <= 15
stickers[i] and target consist of lowercase English letters.
| Hard | [
"array",
"string",
"dynamic-programming",
"backtracking",
"bit-manipulation",
"bitmask"
] | [
"const minStickers = function (stickers, target) {\n const n = stickers.length\n const m = target.length\n const limit = 1 << m\n const dp = Array(limit).fill(Infinity)\n dp[0] = 0\n for (let i = 0; i < limit; i++) {\n if (dp[i] === Infinity) continue\n for (const sticker of stickers) {\n let stat = i\n for (const ch of sticker) {\n for (let j = 0; j < m; j++) {\n if (target[j] === ch && ((stat >> j) & 1) === 0) {\n stat |= (1 << j)\n break\n }\n }\n }\n dp[stat] = Math.min(dp[stat], dp[i] + 1)\n }\n }\n\n return dp[limit - 1] === Infinity ? -1 : dp[limit - 1]\n}",
"const minStickers = function(stickers, target) {\n const isEqual = (arr1, arr2) => {\n for (let i = 0; i < arr1.length; ++i) if (arr1[i] !== arr2[i]) return false\n return true\n }\n\n const minus = (arr1, arr2) => {\n let res = []\n for (let i = 0; i < arr1.length; ++i)\n res[i] = arr1[i] <= 0 ? arr1[i] : arr1[i] - arr2[i]\n return res\n }\n\n const isAllNonpositive = arr => {\n return arr.every(item => item <= 0)\n }\n\n const getString = arr => {\n return arr.reduce((acc, cur, idx) => {\n if (cur > 0) return acc + String.fromCharCode(idx + 97).repeat(cur)\n else return acc\n }, '')\n }\n\n let ss = stickers.map(word => {\n let tmp = new Array(26).fill(0)\n for (let i = 0; i < word.length; ++i) tmp[word.charCodeAt(i) - 97]++\n return tmp\n })\n let root = new Array(26).fill(0)\n for (let i = 0; i < target.length; ++i) root[target.charCodeAt(i) - 97]++\n let cache = new Set()\n let queue = [root]\n let size = 0,\n level = 0,\n front = null\n while (queue.length !== 0) {\n size = queue.length\n while (size--) {\n front = queue.shift()\n for (let w of ss) {\n let t = minus(front, w)\n let str = getString(t)\n if (isEqual(t, front) || cache.has(str)) continue\n if (isAllNonpositive(t)) return level + 1\n else {\n queue.push(t)\n cache.add(str)\n }\n }\n }\n level++\n }\n return -1\n}"
] |
|
692 | top-k-frequent-words | [] | /**
* @param {string[]} words
* @param {number} k
* @return {string[]}
*/
var topKFrequent = function(words, k) {
}; | Given an array of strings words and an integer k, return the k most frequent strings.
Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.
Example 1:
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
Constraints:
1 <= words.length <= 500
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
k is in the range [1, The number of unique words[i]]
Follow-up: Could you solve it in O(n log(k)) time and O(n) extra space?
| Medium | [
"hash-table",
"string",
"trie",
"sorting",
"heap-priority-queue",
"bucket-sort",
"counting"
] | [
"const topKFrequent = function(words, k) {\n const hash = {}\n words.forEach(el => {\n if(hash.hasOwnProperty(el)) {\n hash[el]++\n } else {\n hash[el] = 1\n }\n })\n const freqArr = new Array(words.length)\n const keys = Object.keys(hash)\n \n for(let k of keys) {\n let freq = hash[k]\n if(freqArr[freq] == null) {\n freqArr[freq] = []\n }\n freqArr[freq].push(k)\n }\n \n const res = []\n for(let i = freqArr.length; i >= 0 && res.length < k; i--) {\n if(freqArr[i] != null) {\n res.push(...(freqArr[i].sort()))\n }\n }\n \n return res.slice(0, k)\n};"
] |
|
693 | binary-number-with-alternating-bits | [] | /**
* @param {number} n
* @return {boolean}
*/
var hasAlternatingBits = function(n) {
}; | Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
Example 2:
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.
Example 3:
Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.
Constraints:
1 <= n <= 231 - 1
| Easy | [
"bit-manipulation"
] | [
"const hasAlternatingBits = function(n) {\n const str = bin(n);\n for (let i = 1, prev = str.charAt(0); i < str.length; i++) {\n if (str.charAt(i) === prev) {\n return false;\n }\n prev = str.charAt(i);\n }\n return true;\n};\n\nfunction bin(num) {\n return (num >>> 0).toString(2);\n}"
] |
|
695 | max-area-of-island | [] | /**
* @param {number[][]} grid
* @return {number}
*/
var maxAreaOfIsland = function(grid) {
}; | You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of an island in grid. If there is no island, return 0.
Example 1:
Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.
Example 2:
Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j] is either 0 or 1.
| Medium | [
"array",
"depth-first-search",
"breadth-first-search",
"union-find",
"matrix"
] | [
"const maxAreaOfIsland = function(grid) {\n let res = 0\n const seen = []\n for(let i = 0; i < grid.length; i++) {\n seen[i] = []\n }\n for(let i = 0; i < grid.length; i++) {\n for(let j = 0; j < grid[0].length; j++) {\n res = Math.max(res, area(i, j, seen, grid))\n }\n }\n return res\n};\n\nfunction area(r, c, seen, grid) {\n console.log(grid)\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || seen[r][c] || grid[r][c] == 0) return 0;\n seen[r][c] = true;\n return (1 + area(r+1, c, seen, grid) + area(r-1, c, seen, grid) + area(r, c-1, seen, grid) + area(r, c+1, seen, grid));\n}\n\nconsole.log(maxAreaOfIsland([[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]))\nconsole.log(maxAreaOfIsland([[1,0],[1,1]]))\nconsole.log(maxAreaOfIsland([[1,1],[1,0]]))"
] |
|
696 | count-binary-substrings | [
"How many valid binary substrings exist in \"000111\", and how many in \"11100\"? What about \"00011100\"?"
] | /**
* @param {string} s
* @return {number}
*/
var countBinarySubstrings = function(s) {
}; | Given a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
Example 1:
Input: s = "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
Notice that some of these substrings repeat and are counted the number of times they occur.
Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.
Example 2:
Input: s = "10101"
Output: 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.
Constraints:
1 <= s.length <= 105
s[i] is either '0' or '1'.
| Easy | [
"two-pointers",
"string"
] | null | [] |
697 | degree-of-an-array | [
"Say 5 is the only element that occurs the most number of times - for example, nums = [1, 5, 2, 3, 5, 4, 5, 6]. What is the answer?"
] | /**
* @param {number[]} nums
* @return {number}
*/
var findShortestSubArray = function(nums) {
}; | Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
Input: nums = [1,2,2,3,1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.
Example 2:
Input: nums = [1,2,2,3,1,4,2]
Output: 6
Explanation:
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.
Constraints:
nums.length will be between 1 and 50,000.
nums[i] will be an integer between 0 and 49,999.
| Easy | [
"array",
"hash-table"
] | [
"const findShortestSubArray = function(nums) {\n const left = {};\n const right = {};\n const count = {};\n\n for (let i = 0; i < nums.length; i++) {\n if (!left.hasOwnProperty(nums[i])) {\n left[nums[i]] = i;\n }\n right[nums[i]] = i;\n count[nums[i]] = count[nums[i]] ? count[nums[i]] + 1 : 1;\n }\n const degree = Math.max(...Object.keys(count).map(el => count[el]));\n let res = nums.length;\n for (let el in count) {\n if (count.hasOwnProperty(el) && count[el] === degree) {\n res = Math.min(res, right[el] - left[el] + 1);\n }\n }\n\n return res;\n};"
] |
|
698 | partition-to-k-equal-sum-subsets | [
"We can figure out what target each subset must sum to. Then, let's recursively search, where at each call to our function, we choose which of k subsets the next value will join."
] | /**
* @param {number[]} nums
* @param {number} k
* @return {boolean}
*/
var canPartitionKSubsets = function(nums, k) {
}; | Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.
Example 1:
Input: nums = [4,3,2,3,5,2,1], k = 4
Output: true
Explanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
Example 2:
Input: nums = [1,2,3,4], k = 3
Output: false
Constraints:
1 <= k <= nums.length <= 16
1 <= nums[i] <= 104
The frequency of each element is in the range [1, 4].
| Medium | [
"array",
"dynamic-programming",
"backtracking",
"bit-manipulation",
"memoization",
"bitmask"
] | [
"const canPartitionKSubsets = function(nums, k) {\n const sum = nums.reduce((ac, el) => ac + el, 0)\n return k !== 0 && sum % k === 0 && canPartition(0, nums, [], k, 0, sum / k)\n \n};\n\nfunction canPartition(start, nums, seen, k, sum, target) {\n if(k === 1) return true\n if (sum === target) {\n return canPartition(0, nums, seen, k - 1, 0, target)\n }\n for(let i = start; i < nums.length; i++) {\n if (!seen[i]) {\n seen[i] = true\n if(canPartition(i + 1, nums, seen, k, sum + nums[i], target)) {\n return true\n }\n seen[i] = false\n }\n }\n return false\n}"
] |
|
699 | falling-squares | [
"If positions = [[10, 20], [20, 30]], this is the same as [[1, 2], [2, 3]]. Currently, the values of positions are very large. Can you generalize this approach so as to make the values in positions manageable?"
] | /**
* @param {number[][]} positions
* @return {number[]}
*/
var fallingSquares = function(positions) {
}; | There are several squares being dropped onto the X-axis of a 2D plane.
You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti.
Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved.
After each square is dropped, you must record the height of the current tallest stack of squares.
Return an integer array ans where ans[i] represents the height described above after dropping the ith square.
Example 1:
Input: positions = [[1,2],[2,3],[6,1]]
Output: [2,5,5]
Explanation:
After the first drop, the tallest stack is square 1 with a height of 2.
After the second drop, the tallest stack is squares 1 and 2 with a height of 5.
After the third drop, the tallest stack is still squares 1 and 2 with a height of 5.
Thus, we return an answer of [2, 5, 5].
Example 2:
Input: positions = [[100,100],[200,100]]
Output: [100,100]
Explanation:
After the first drop, the tallest stack is square 1 with a height of 100.
After the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.
Thus, we return an answer of [100, 100].
Note that square 2 only brushes the right side of square 1, which does not count as landing on it.
Constraints:
1 <= positions.length <= 1000
1 <= lefti <= 108
1 <= sideLengthi <= 106
| Hard | [
"array",
"segment-tree",
"ordered-set"
] | [
"class Interval {\n constructor(start, end, height) {\n this.start = start\n this.end = end\n this.height = height\n }\n}\nfunction fallingSquares(positions) {\n const intervals = []\n const res = []\n let h = 0\n for (let pos of positions) {\n let cur = new Interval(pos[0], pos[0] + pos[1], pos[1])\n h = Math.max(h, getHeight(intervals, cur))\n res.push(h)\n }\n console.log(intervals)\n return res\n}\nfunction getHeight(intervals, cur) {\n let preMaxHeight = 0\n for (let i of intervals) {\n if (i.end <= cur.start) continue\n if (i.start >= cur.end) continue\n preMaxHeight = Math.max(preMaxHeight, i.height)\n }\n cur.height += preMaxHeight\n intervals.push(cur)\n return cur.height\n}",
"var fallingSquares = function (positions) {\n let ranges = [{ left: 0, height: 0, right: 1e8 + 1e6 }], rtn = [], max = 0\n\n outer:\n for (let [left, length] of positions) {\n let curHeight = 0, startI = -1, right = left + length, newRanges = []\n for (let i = 0; i < ranges.length; i++) {\n let range = ranges[i]\n if (left < range.right && startI == -1) {\n startI = i\n // left part\n if (left != range.left) {\n newRanges.push({\n left: range.left,\n height: range.height,\n right: left\n })\n }\n }\n if (startI != -1) {\n curHeight = Math.max(curHeight, range.height)\n }\n if (right <= range.right) {\n // added part\n let newHeight = length + curHeight\n newRanges.push({\n left,\n height: newHeight,\n right,\n })\n // right part\n if (right != range.right) {\n newRanges.push({\n left: right,\n height: range.height,\n right: range.right,\n })\n }\n max = Math.max(newHeight, max)\n rtn.push(max)\n // replace\n ranges.splice(startI, i - startI + 1, ...newRanges)\n continue outer\n }\n }\n }\n return rtn\n};"
] |
|
700 | search-in-a-binary-search-tree | [] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} val
* @return {TreeNode}
*/
var searchBST = function(root, val) {
}; | You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.
Example 1:
Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
Example 2:
Input: root = [4,2,7,1,3], val = 5
Output: []
Constraints:
The number of nodes in the tree is in the range [1, 5000].
1 <= Node.val <= 107
root is a binary search tree.
1 <= val <= 107
| Easy | [
"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 searchBST = function (root, val) {\n if (!root || root.val === val) {\n return root\n }\n return root.val < val ? searchBST(root.right, val) : searchBST(root.left, val)\n}"
] |
701 | insert-into-a-binary-search-tree | [] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} val
* @return {TreeNode}
*/
var insertIntoBST = function(root, val) {
}; | You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
Example 1:
Input: root = [4,2,7,1,3], val = 5
Output: [4,2,7,1,3,5]
Explanation: Another accepted tree is:
Example 2:
Input: root = [40,20,60,10,30,50,70], val = 25
Output: [40,20,60,10,30,50,70,null,null,25]
Example 3:
Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
Output: [4,2,7,1,3,5]
Constraints:
The number of nodes in the tree will be in the range [0, 104].
-108 <= Node.val <= 108
All the values Node.val are unique.
-108 <= val <= 108
It's guaranteed that val does not exist in the original BST.
| 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 insertIntoBST = function(root, val) {\n if(root == null) return new TreeNode(val);\n let cur = root;\n while(true) {\n if(cur.val <= val) {\n if(cur.right != null) cur = cur.right;\n else {\n cur.right = new TreeNode(val);\n break;\n }\n } else {\n if(cur.left != null) cur = cur.left;\n else {\n cur.left = new TreeNode(val);\n break;\n }\n }\n }\n return root;\n}; ",
"const insertIntoBST = function(root, val) {\n if (root == null) {\n return new TreeNode(val);\n }\n if (root.val > val) {\n root.left = insertIntoBST(root.left, val);\n } else {\n root.right = insertIntoBST(root.right, val);\n }\n return root;\n}; ",
"const insertIntoBST = function(root, val) {\n if(root == null) return new TreeNode(val)\n if(val < root.val) root.left = insertIntoBST(root.left, val)\n else if(val > root.val) root.right = insertIntoBST(root.right, val)\n return root\n};"
] |
703 | kth-largest-element-in-a-stream | [] | /**
* @param {number} k
* @param {number[]} nums
*/
var KthLargest = function(k, nums) {
};
/**
* @param {number} val
* @return {number}
*/
KthLargest.prototype.add = function(val) {
};
/**
* Your KthLargest object will be instantiated and called as such:
* var obj = new KthLargest(k, nums)
* var param_1 = obj.add(val)
*/ | Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Implement KthLargest class:
KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.
Example 1:
Input
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[null, 4, 5, 5, 8, 8]
Explanation
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8
Constraints:
1 <= k <= 104
0 <= nums.length <= 104
-104 <= nums[i] <= 104
-104 <= val <= 104
At most 104 calls will be made to add.
It is guaranteed that there will be at least k elements in the array when you search for the kth element.
| Easy | [
"tree",
"design",
"binary-search-tree",
"heap-priority-queue",
"binary-tree",
"data-stream"
] | [
"const KthLargest = function(k, nums) {\n this.sorted = nums.sort((a, b) => a - b);\n this.k = k;\n};\n\n\nKthLargest.prototype.add = function(val) {\n let left = 0;\n let right = this.sorted.length - 1;\n let insertIndex = left;\n while (left <= right) {\n let mid = left + Math.floor((right - left) / 2);\n if (val > this.sorted[mid]) {\n left = mid + 1;\n insertIndex = mid + 1;\n } else if (val < this.sorted[mid]) {\n right = mid - 1;\n insertIndex = mid;\n } else {\n insertIndex = mid;\n break;\n }\n }\n this.sorted.splice(insertIndex, 0, val);\n return this.sorted[this.sorted.length - this.k];\n};"
] |
|
704 | binary-search | [] | /**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
}; | Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
1 <= nums.length <= 104
-104 < nums[i], target < 104
All the integers in nums are unique.
nums is sorted in ascending order.
| Easy | [
"array",
"binary-search"
] | [
"const search = function(nums, target) {\n let start = 0;\n let end = nums.length - 1;\n \n while(start <= end){\n let mid = parseInt((start + end) / 2);\n if(nums[mid] === target) return mid;\n if(nums[mid] > target) end = mid -1;\n if(nums[mid] < target) start = mid + 1;\n }\n return -1;\n};"
] |
|
705 | design-hashset | [] |
var MyHashSet = function() {
};
/**
* @param {number} key
* @return {void}
*/
MyHashSet.prototype.add = function(key) {
};
/**
* @param {number} key
* @return {void}
*/
MyHashSet.prototype.remove = function(key) {
};
/**
* @param {number} key
* @return {boolean}
*/
MyHashSet.prototype.contains = function(key) {
};
/**
* Your MyHashSet object will be instantiated and called as such:
* var obj = new MyHashSet()
* obj.add(key)
* obj.remove(key)
* var param_3 = obj.contains(key)
*/ | Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet class:
void add(key) Inserts the value key into the HashSet.
bool contains(key) Returns whether the value key exists in the HashSet or not.
void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.
Example 1:
Input
["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
[[], [1], [2], [1], [3], [2], [2], [2], [2]]
Output
[null, null, null, true, false, null, true, null, false]
Explanation
MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1); // set = [1]
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(1); // return True
myHashSet.contains(3); // return False, (not found)
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(2); // return True
myHashSet.remove(2); // set = [1]
myHashSet.contains(2); // return False, (already removed)
Constraints:
0 <= key <= 106
At most 104 calls will be made to add, remove, and contains.
| Easy | [
"array",
"hash-table",
"linked-list",
"design",
"hash-function"
] | [
"const MyHashSet = function() {\n this.s = {}\n};\n\n\nMyHashSet.prototype.add = function(key) {\n this.s[key] = true\n};\n\n\nMyHashSet.prototype.remove = function(key) {\n delete this.s[key]\n};\n\n\nMyHashSet.prototype.contains = function(key) {\n return Object.prototype.hasOwnProperty.call(this.s, key)\n};"
] |
|
706 | design-hashmap | [] |
var MyHashMap = function() {
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
MyHashMap.prototype.put = function(key, value) {
};
/**
* @param {number} key
* @return {number}
*/
MyHashMap.prototype.get = function(key) {
};
/**
* @param {number} key
* @return {void}
*/
MyHashMap.prototype.remove = function(key) {
};
/**
* Your MyHashMap object will be instantiated and called as such:
* var obj = new MyHashMap()
* obj.put(key,value)
* var param_2 = obj.get(key)
* obj.remove(key)
*/ | Design a HashMap without using any built-in hash table libraries.
Implement the MyHashMap class:
MyHashMap() initializes the object with an empty map.
void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.
int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.
Example 1:
Input
["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
Output
[null, null, null, 1, -1, null, 1, null, -1]
Explanation
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // The map is now [[1,1]]
myHashMap.put(2, 2); // The map is now [[1,1], [2,2]]
myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]
myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]
myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)
myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]
myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]
myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]
Constraints:
0 <= key, value <= 106
At most 104 calls will be made to put, get, and remove.
| Easy | [
"array",
"hash-table",
"linked-list",
"design",
"hash-function"
] | [
"const MyHashMap = function() {\n this.h = {}\n};\n\n\nMyHashMap.prototype.put = function(key, value) {\n this.h[key] = value\n};\n\n\nMyHashMap.prototype.get = function(key) {\n return {}.hasOwnProperty.call(this.h, key) ? this.h[key] : -1\n};\n\n\nMyHashMap.prototype.remove = function(key) {\n delete this.h[key]\n};"
] |
|
707 | design-linked-list | [] |
var MyLinkedList = function() {
};
/**
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function(index) {
};
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function(val) {
};
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function(val) {
};
/**
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function(index, val) {
};
/**
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function(index) {
};
/**
* Your MyLinkedList object will be instantiated and called as such:
* var obj = new MyLinkedList()
* var param_1 = obj.get(index)
* obj.addAtHead(val)
* obj.addAtTail(val)
* obj.addAtIndex(index,val)
* obj.deleteAtIndex(index)
*/ | Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.
If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.
Implement the MyLinkedList class:
MyLinkedList() Initializes the MyLinkedList object.
int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1.
void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
void addAtTail(int val) Append a node of value val as the last element of the linked list.
void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted.
void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.
Example 1:
Input
["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
[[], [1], [3], [1, 2], [1], [1], [1]]
Output
[null, null, null, null, 2, null, 3]
Explanation
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3
myLinkedList.get(1); // return 2
myLinkedList.deleteAtIndex(1); // now the linked list is 1->3
myLinkedList.get(1); // return 3
Constraints:
0 <= index, val <= 1000
Please do not use the built-in LinkedList library.
At most 2000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex.
| Medium | [
"linked-list",
"design"
] | [
"var MyLinkedList = function() {\n this.arr = []\n}\n\n\nMyLinkedList.prototype.get = function(index) {\n if (this.arr[index] !== undefined) {\n return this.arr[index]\n } else {\n return -1\n }\n}\n\n\nMyLinkedList.prototype.addAtHead = function(val) {\n this.arr.unshift(val)\n}\n\n\nMyLinkedList.prototype.addAtTail = function(val) {\n this.arr.push(val)\n}\n\n\nMyLinkedList.prototype.addAtIndex = function(index, val) {\n if (this.arr.length >= index) {\n this.arr.splice(index, 0, val)\n }\n if (index < 0) {\n this.arr.unshift(val)\n }\n}\n\n\nMyLinkedList.prototype.deleteAtIndex = function(index) {\n if (index >= 0 && index < this.arr.length) {\n this.arr.splice(index, 1)\n }\n}",
"var MyLinkedList = function(val) {\n this.head = null\n this.tail = null\n this.size = 0\n}\n\n// Create Node class to store node data as an 'object'\nvar Node = function(val) {\n this.val = val\n this.next = null\n}\n\n\nMyLinkedList.prototype.get = function(index) {\n if (index < 0 || this.size === 0 || index > this.size - 1) return -1\n let curr = this.head\n let i = 0\n while (i < index) {\n curr = curr.next\n i += 1\n }\n return curr.val\n}\n\n\nMyLinkedList.prototype.addAtHead = function(val) {\n let newNode = new Node(val)\n if (this.head === null) {\n this.head = newNode\n this.tail = newNode\n } else {\n newNode.next = this.head\n this.head = newNode\n }\n this.size++\n return this\n}\n\n\nMyLinkedList.prototype.addAtTail = function(val) {\n const newNode = new Node(val)\n if (this.head === null) {\n this.head = newNode\n this.tail = newNode\n } else {\n this.tail.next = newNode\n this.tail = newNode\n }\n this.size++\n return this\n}\n\n\nMyLinkedList.prototype.addAtIndex = function(index, val) {\n if (index > this.size) return\n if (index <= 0) return this.addAtHead(val)\n if (index === this.size) return this.addAtTail(val)\n let newNode = new Node(val)\n let i = 0\n let curr = this.head\n while (i < index - 1) {\n curr = curr.next\n i++\n }\n newNode.next = curr.next ? curr.next : null\n curr.next = newNode\n this.size++\n return this\n}\n\n\nMyLinkedList.prototype.deleteAtIndex = function(index) {\n if (index >= this.size || index < 0) return\n if (index === 0) {\n this.head = this.head.next\n this.size--\n return this\n }\n let curr = this.head\n let i = 0\n while (i < index - 1) {\n i++\n curr = curr.next\n }\n curr.next = curr.next.next ? curr.next.next : null\n if (!curr.next) this.tail = curr\n this.size--\n return this\n}"
] |
|
709 | to-lower-case | [
"Most languages support lowercase conversion for a string data type. However, that is certainly not the purpose of the problem. Think about how the implementation of the lowercase function call can be done easily.",
"<b>Think ASCII!</b>",
"Think about the different capital letters and their ASCII codes and how that relates to their lowercase counterparts. Does there seem to be any pattern there? Any mathematical relationship that we can use?"
] | /**
* @param {string} s
* @return {string}
*/
var toLowerCase = function(s) {
}; | Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.
Example 1:
Input: s = "Hello"
Output: "hello"
Example 2:
Input: s = "here"
Output: "here"
Example 3:
Input: s = "LOVELY"
Output: "lovely"
Constraints:
1 <= s.length <= 100
s consists of printable ASCII characters.
| Easy | [
"string"
] | null | [] |
710 | random-pick-with-blacklist | [] | /**
* @param {number} n
* @param {number[]} blacklist
*/
var Solution = function(n, blacklist) {
};
/**
* @return {number}
*/
Solution.prototype.pick = function() {
};
/**
* Your Solution object will be instantiated and called as such:
* var obj = new Solution(n, blacklist)
* var param_1 = obj.pick()
*/ | You are given an integer n and an array of unique integers blacklist. Design an algorithm to pick a random integer in the range [0, n - 1] that is not in blacklist. Any integer that is in the mentioned range and not in blacklist should be equally likely to be returned.
Optimize your algorithm such that it minimizes the number of calls to the built-in random function of your language.
Implement the Solution class:
Solution(int n, int[] blacklist) Initializes the object with the integer n and the blacklisted integers blacklist.
int pick() Returns a random integer in the range [0, n - 1] and not in blacklist.
Example 1:
Input
["Solution", "pick", "pick", "pick", "pick", "pick", "pick", "pick"]
[[7, [2, 3, 5]], [], [], [], [], [], [], []]
Output
[null, 0, 4, 1, 6, 1, 0, 4]
Explanation
Solution solution = new Solution(7, [2, 3, 5]);
solution.pick(); // return 0, any integer from [0,1,4,6] should be ok. Note that for every call of pick,
// 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4).
solution.pick(); // return 4
solution.pick(); // return 1
solution.pick(); // return 6
solution.pick(); // return 1
solution.pick(); // return 0
solution.pick(); // return 4
Constraints:
1 <= n <= 109
0 <= blacklist.length <= min(105, n - 1)
0 <= blacklist[i] < n
All the values of blacklist are unique.
At most 2 * 104 calls will be made to pick.
| Hard | [
"array",
"hash-table",
"math",
"binary-search",
"sorting",
"randomized"
] | [
"const Solution = function (N, blacklist) {\n this.map = new Map()\n for (let b of blacklist) this.map.set(b, -1)\n this.M = N - this.map.size\n for (let b of blacklist) {\n if (b < this.M) {\n while (this.map.has(N - 1)) N--\n this.map.set(b, N - 1)\n N--\n }\n }\n}\n\n\nSolution.prototype.pick = function () {\n const p = Math.floor(Math.random() * this.M)\n if (this.map.has(p)) return this.map.get(p)\n return p\n}"
] |
|
712 | minimum-ascii-delete-sum-for-two-strings | [
"Let dp(i, j) be the answer for inputs s1[i:] and s2[j:]."
] | /**
* @param {string} s1
* @param {string} s2
* @return {number}
*/
var minimumDeleteSum = function(s1, s2) {
}; | Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.
Example 1:
Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
Example 2:
Input: s1 = "delete", s2 = "leet"
Output: 403
Explanation: Deleting "dee" from "delete" to turn the string into "let",
adds 100[d] + 101[e] + 101[e] to the sum.
Deleting "e" from "leet" adds 101[e] to the sum.
At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.
If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.
Constraints:
1 <= s1.length, s2.length <= 1000
s1 and s2 consist of lowercase English letters.
| Medium | [
"string",
"dynamic-programming"
] | [
"const minimumDeleteSum = function(s1, s2) {\n const l1 = s1.length;\n const l2 = s2.length;\n const dp = [];\n for (let i = 0; i <= l1; i++) {\n dp[i] = [];\n }\n let sum = 0;\n for (let i = 0; i <= l1; i++) {\n for (let j = 0; j <= l2; j++) {\n if (i === 0 || j === 0) {\n sum = 0;\n for (let k = 0; k < Math.max(i, j); k++) {\n sum += i > j ? s1.charCodeAt(k) : s2.charCodeAt(k);\n }\n dp[i][j] = sum;\n } else {\n if (s1[i - 1] === s2[j - 1]) {\n dp[i][j] = dp[i - 1][j - 1];\n } else {\n dp[i][j] = Math.min(\n s1.charCodeAt(i - 1) + dp[i - 1][j],\n s2.charCodeAt(j - 1) + dp[i][j - 1],\n s1.charCodeAt(i - 1) + s2.charCodeAt(j - 1) + dp[i - 1][j - 1]\n );\n }\n }\n }\n }\n return dp[l1][l2];\n};"
] |
|
713 | subarray-product-less-than-k | [
"For each j, let opt(j) be the smallest i so that nums[i] * nums[i+1] * ... * nums[j] is less than k. opt is an increasing function."
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var numSubarrayProductLessThanK = function(nums, k) {
}; | Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.
Example 1:
Input: nums = [10,5,2,6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
Example 2:
Input: nums = [1,2,3], k = 0
Output: 0
Constraints:
1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106
| Medium | [
"array",
"sliding-window"
] | [
"const numSubarrayProductLessThanK = function(nums, k) {\n if (k == 0) return 0\n let cnt = 0\n let pro = 1\n for (let i = 0, j = 0, len = nums.length; j < len; j++) {\n pro *= nums[j]\n while (i <= j && pro >= k) {\n pro /= nums[i++]\n }\n cnt += j - i + 1\n }\n return cnt\n}"
] |
|
714 | best-time-to-buy-and-sell-stock-with-transaction-fee | [
"Consider the first K stock prices. At the end, the only legal states are that you don't own a share of stock, or that you do. Calculate the most profit you could have under each of these two cases."
] | /**
* @param {number[]} prices
* @param {number} fee
* @return {number}
*/
var maxProfit = function(prices, fee) {
}; | You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
Note:
You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
The transaction fee is only charged once for each stock purchase and sale.
Example 1:
Input: prices = [1,3,2,8,4,9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
- Buying at prices[0] = 1
- Selling at prices[3] = 8
- Buying at prices[4] = 4
- Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
Example 2:
Input: prices = [1,3,7,5,10,3], fee = 3
Output: 6
Constraints:
1 <= prices.length <= 5 * 104
1 <= prices[i] < 5 * 104
0 <= fee < 5 * 104
| Medium | [
"array",
"dynamic-programming",
"greedy"
] | [
"const maxProfit = function(prices, fee) {\n let cash = 0,\n hold = -prices[0];\n for (let i = 1; i < prices.length; i++) {\n cash = Math.max(cash, hold + prices[i] - fee);\n hold = Math.max(hold, cash - prices[i]);\n }\n return cash;\n};\n\nconsole.log(maxProfit([1, 3, 2, 8, 4, 9], 2));"
] |
|
715 | range-module | [
"Maintain a sorted set of disjoint intervals. addRange and removeRange can be performed with time complexity linear to the size of this set; queryRange can be performed with time complexity logarithmic to the size of this set."
] |
var RangeModule = function() {
};
/**
* @param {number} left
* @param {number} right
* @return {void}
*/
RangeModule.prototype.addRange = function(left, right) {
};
/**
* @param {number} left
* @param {number} right
* @return {boolean}
*/
RangeModule.prototype.queryRange = function(left, right) {
};
/**
* @param {number} left
* @param {number} right
* @return {void}
*/
RangeModule.prototype.removeRange = function(left, right) {
};
/**
* Your RangeModule object will be instantiated and called as such:
* var obj = new RangeModule()
* obj.addRange(left,right)
* var param_2 = obj.queryRange(left,right)
* obj.removeRange(left,right)
*/ | A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them.
A half-open interval [left, right) denotes all the real numbers x where left <= x < right.
Implement the RangeModule class:
RangeModule() Initializes the object of the data structure.
void addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked.
boolean queryRange(int left, int right) Returns true if every real number in the interval [left, right) is currently being tracked, and false otherwise.
void removeRange(int left, int right) Stops tracking every real number currently being tracked in the half-open interval [left, right).
Example 1:
Input
["RangeModule", "addRange", "removeRange", "queryRange", "queryRange", "queryRange"]
[[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]]
Output
[null, null, null, true, false, true]
Explanation
RangeModule rangeModule = new RangeModule();
rangeModule.addRange(10, 20);
rangeModule.removeRange(14, 16);
rangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked)
rangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)
rangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)
Constraints:
1 <= left < right <= 109
At most 104 calls will be made to addRange, queryRange, and removeRange.
| Hard | [
"design",
"segment-tree",
"ordered-set"
] | [
"const RangeModule = function() {\n this.st = new SegmentTree();\n};\n\n\nRangeModule.prototype.addRange = function(left, right) {\n this.st.add(left, right);\n};\n\n\nRangeModule.prototype.queryRange = function(left, right) {\n return this.st.query(left, right);\n};\n\n\nRangeModule.prototype.removeRange = function(left, right) {\n this.st.remove(left, right);\n};\n\n\nclass SegNode {\n constructor(l, r, state) {\n this.l = l;\n this.r = r;\n this.state = state;\n this.left = null;\n this.right = null; \n }\n}\n\nfunction SegmentTree() {\n let root = new SegNode(0, 1e9, false);\n return { update, query, add, remove }\n function update(node, l, r, state) {\n if (l <= node.l && r >= node.r) {\n node.state = state;\n node.left = null;\n node.right = null;\n return node.state;\n }\n if (l >= node.r || r <= node.l) return node.state;\n let mid = node.l + parseInt((node.r - node.l) / 2);\n if (node.left == null) {\n node.left = new SegNode(node.l, mid, node.state);\n node.right = new SegNode(mid, node.r, node.state);\n }\n let left = update(node.left, l, r, state);\n let right = update(node.right, l, r, state);\n node.state = left && right;\n return node.state;\n }\n function query(l, r) {\n return dfs(root, l, r);\n }\n function dfs(node, l, r) {\n if (l >= node.r || r <= node.l) return true;\n if ((l <= node.l && r >= node.r) || (node.left == null)) return node.state;\n let mid = node.l + parseInt((node.r - node.l) / 2);\n if (r <= mid) {\n return dfs(node.left, l, r);\n } else if (l >= mid) {\n return dfs(node.right, l, r);\n } else {\n return dfs(node.left, l, r) && dfs(node.right, l, r);\n }\n }\n function add(l, r) {\n update(root, l, r, true);\n }\n function remove(l, r) {\n update(root, l, r, false);\n }\n}",
"const RangeModule = function() {\n this.range = []\n}\n\n\nRangeModule.prototype.addRange = function(left, right) {\n let index1 = this.range.length\n let low = 0\n let high = this.range.length - 1\n while (low <= high) {\n const mid = (low + high) >> 1\n if (this.range[mid][1] >= left) {\n index1 = Math.min(index1, mid)\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n\n let index2 = -1\n low = 0\n high = this.range.length - 1\n while (low <= high) {\n const mid = (low + high) >> 1\n if (this.range[mid][0] <= right) {\n index2 = Math.max(index2, mid)\n low = mid + 1\n } else {\n high = mid - 1\n }\n }\n\n if (index1 === this.range.length) {\n this.range.push([left, right])\n return\n } else if (index2 === -1) {\n this.range.unshift([left, right])\n return\n }\n left = Math.min(left, this.range[index1][0])\n right = Math.max(right, this.range[index2][1])\n this.range.splice(index1, index2 - index1 + 1, [left, right])\n}\n\n\nRangeModule.prototype.queryRange = function(left, right) {\n let index = -1\n let low = 0\n let high = this.range.length - 1\n while (low <= high) {\n const mid = (low + high) >> 1\n if (this.range[mid][0] <= left) {\n index = Math.max(index, mid)\n low = mid + 1\n } else {\n high = mid - 1\n }\n }\n if (index === -1 || this.range[index][1] < right) {\n return false\n }\n return true\n}\n\n\nRangeModule.prototype.removeRange = function(left, right) {\n let index1 = this.range.length\n let low = 0\n let high = this.range.length - 1\n while (low <= high) {\n const mid = (low + high) >> 1\n if (this.range[mid][1] >= left) {\n index1 = Math.min(index1, mid)\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n\n let index2 = -1\n low = 0\n high = this.range.length - 1\n while (low <= high) {\n const mid = (low + high) >> 1\n if (this.range[mid][0] <= right) {\n index2 = Math.max(index2, mid)\n low = mid + 1\n } else {\n high = mid - 1\n }\n }\n\n if (index1 === this.range.length || index2 === -1) {\n return\n }\n\n const newRange = []\n if (left > this.range[index1][0]) {\n newRange.push([this.range[index1][0], left])\n }\n if (right < this.range[index2][1]) {\n newRange.push([right, this.range[index2][1]])\n }\n this.range.splice(index1, index2 - index1 + 1, ...newRange)\n}",
"const RangeModule = function () {\n this.intervals = []\n}\n\n\nRangeModule.prototype.addRange = function (left, right) {\n const n = this.intervals.length\n const tmp = []\n for (let i = 0; i <= n; i++) {\n const cur = this.intervals[i]\n\n if (i == n || cur[0] > right) {\n tmp.push([left, right])\n while (i < n) tmp.push(this.intervals[i++])\n } else if (cur[1] < left) tmp.push(cur)\n else {\n left = Math.min(left, cur[0])\n right = Math.max(right, cur[1])\n }\n }\n this.intervals = tmp\n}\n\n\nRangeModule.prototype.queryRange = function (left, right) {\n const n = this.intervals.length\n let l = 0,\n r = n - 1\n while (l <= r) {\n let m = ~~(l + (r - l) / 2)\n if (this.intervals[m][0] >= right) r = m - 1\n else if (this.intervals[m][1] <= left) l = m + 1\n else return this.intervals[m][0] <= left && this.intervals[m][1] >= right\n }\n return false\n}\n\n\nRangeModule.prototype.removeRange = function (left, right) {\n const n = this.intervals.length\n const tmp = []\n for (let i = 0; i < n; i++) {\n const cur = this.intervals[i]\n if (cur[1] <= left || cur[0] >= right) tmp.push(cur)\n else {\n if (cur[0] < left) tmp.push([cur[0], left])\n if (cur[1] > right) tmp.push([right, cur[1]])\n }\n }\n this.intervals = tmp\n}",
"const RangeModule = function () {\n this.intervals = []\n}\n\n\nRangeModule.prototype.addRange = function (left, right) {\n const tmp = []\n const n = this.intervals.length\n for(let i = 0; i <= n; i++) {\n const cur = this.intervals[i]\n if(i === n || cur[0] > right) {\n tmp.push([left, right])\n while(i < n) tmp.push(this.intervals[i++])\n }else if(cur[1] < left) {\n tmp.push(cur)\n }else {\n // cur[0] <= right\n // left <= cur[1]\n left = Math.min(left, cur[0])\n right = Math.max(right, cur[1])\n }\n }\n // console.log(tmp)\n this.intervals = tmp\n}\n\n\nRangeModule.prototype.queryRange = function (left, right) {\n const n = this.intervals.length, arr = this.intervals\n let l = 0, r = n - 1\n while(l <= r) {\n const mid = ~~(l + (r - l) / 2)\n if(arr[mid][0] >= right) r = mid - 1\n else if(arr[mid][1] <= left) l = mid + 1\n else return arr[mid][0] <= left && arr[mid][1] >= right\n }\n \n return false\n}\n\n\nRangeModule.prototype.removeRange = function (left, right) {\n const tmp = []\n const n = this.intervals.length\n \n for(let i = 0; i < n; i++) {\n const cur = this.intervals[i]\n if(cur[1] < left) {\n tmp.push(cur)\n }else if(cur[0] > right) tmp.push(cur)\n else {\n // left <= cur[1]\n // cur[0] <= right\n if(left > cur[0]) tmp.push([cur[0], left])\n if(right < cur[1]) tmp.push([right, cur[1]])\n }\n }\n // console.log(tmp)\n this.intervals = tmp\n}"
] |
|
717 | 1-bit-and-2-bit-characters | [
"Keep track of where the next character starts. At the end, you want to know if you started on the last bit."
] | /**
* @param {number[]} bits
* @return {boolean}
*/
var isOneBitCharacter = function(bits) {
}; | We have two special characters:
The first character can be represented by one bit 0.
The second character can be represented by two bits (10 or 11).
Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.
Example 1:
Input: bits = [1,0,0]
Output: true
Explanation: The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
Example 2:
Input: bits = [1,1,1,0]
Output: false
Explanation: The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
Constraints:
1 <= bits.length <= 1000
bits[i] is either 0 or 1.
| Easy | [
"array"
] | [
"const isOneBitCharacter = function(bits) {\n let ones = 0;\n //Starting from one but last, as last one is always 0.\n for (let i = bits.length - 2; i >= 0 && bits[i] != 0; i--) {\n ones++;\n }\n return ones % 2 > 0 ? false : true;\n};"
] |
|
718 | maximum-length-of-repeated-subarray | [
"Use dynamic programming. dp[i][j] will be the longest common prefix of A[i:] and B[j:].",
"The answer is max(dp[i][j]) over all i, j."
] | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var findLength = function(nums1, nums2) {
}; | Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.
Example 1:
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
Output: 3
Explanation: The repeated subarray with maximum length is [3,2,1].
Example 2:
Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
Output: 5
Explanation: The repeated subarray with maximum length is [0,0,0,0,0].
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 100
| Medium | [
"array",
"binary-search",
"dynamic-programming",
"sliding-window",
"rolling-hash",
"hash-function"
] | [
"const findLength = function(A, B) {\n let ans = 0;\n let memo = [];\n for (let i = 0; i < A.length + 1; i++) {\n memo[i] = Array(B.length + 1).fill(0);\n }\n for (let i = A.length - 1; i >= 0; --i) {\n for (let j = B.length - 1; j >= 0; --j) {\n if (A[i] == B[j]) {\n memo[i][j] = memo[i + 1][j + 1] + 1;\n if (ans < memo[i][j]) ans = memo[i][j];\n }\n }\n }\n return ans;\n};"
] |
|
719 | find-k-th-smallest-pair-distance | [
"Binary search for the answer. How can you check how many pairs have distance <= X?"
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var smallestDistancePair = function(nums, k) {
}; | The distance of a pair of integers a and b is defined as the absolute difference between a and b.
Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.
Example 1:
Input: nums = [1,3,1], k = 1
Output: 0
Explanation: Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
Example 2:
Input: nums = [1,1,1], k = 2
Output: 0
Example 3:
Input: nums = [1,6,1], k = 3
Output: 5
Constraints:
n == nums.length
2 <= n <= 104
0 <= nums[i] <= 106
1 <= k <= n * (n - 1) / 2
| Hard | [
"array",
"two-pointers",
"binary-search",
"sorting"
] | [
"function smallestDistancePair(nums, k) {\n nums.sort((a, b) => a - b)\n let l = 0, n = nums.length, r = nums[n - 1] - nums[0]\n \n let res = 0\n while(l < r) {\n let cnt = 0, mid = l + ((r - l) >> 1)\n for(let i = 0, j = 0; i < n; i++) {\n while(j < n && nums[j] <= nums[i] + mid) j++\n cnt += j - 1 - i\n }\n if(cnt < k) l = mid + 1\n else r = mid\n }\n\n return l\n}",
"const smallestDistancePair = function(nums, k) {\n nums.sort((a, b) => a - b)\n let lo = 0\n let hi = nums[nums.length - 1] - nums[0]\n while (lo < hi) {\n let mi = Math.floor((lo + hi) / 2)\n let count = 0\n let left = 0\n for (let right = 0; right < nums.length; right++) {\n while (nums[right] - nums[left] > mi) left++\n count += right - left\n }\n //count = number of pairs with distance <= mi\n if (count >= k) hi = mi\n else lo = mi + 1\n }\n return lo\n}"
] |
|
720 | longest-word-in-dictionary | [
"For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set."
] | /**
* @param {string[]} words
* @return {string}
*/
var longestWord = function(words) {
}; | Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
Example 1:
Input: words = ["w","wo","wor","worl","world"]
Output: "world"
Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Example 2:
Input: words = ["a","banana","app","appl","ap","apply","apple"]
Output: "apple"
Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 30
words[i] consists of lowercase English letters.
| Medium | [
"array",
"hash-table",
"string",
"trie",
"sorting"
] | [
"const longestWord = function(words) {\n if(words == null || words.length === 0) return ''\n words.sort()\n const s = new Set()\n let res = ''\n for(let i = 0, len = words.length; i < len; i++) {\n const w = words[i]\n if(w.length === 1 || s.has(w.slice(0, w.length - 1))) {\n res = w.length > res.length ? w : res\n s.add(w)\n }\n }\n return res\n};"
] |
|
721 | accounts-merge | [
"For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph."
] | /**
* @param {string[][]} accounts
* @return {string[][]}
*/
var accountsMerge = function(accounts) {
}; | Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
Example 1:
Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Explanation:
The first and second John's are the same person as they have the common email "johnsmith@mail.com".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'],
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
Example 2:
Input: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]]
Output: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]
Constraints:
1 <= accounts.length <= 1000
2 <= accounts[i].length <= 10
1 <= accounts[i][j].length <= 30
accounts[i][0] consists of English letters.
accounts[i][j] (for j > 0) is a valid email.
| Medium | [
"array",
"hash-table",
"string",
"depth-first-search",
"breadth-first-search",
"union-find",
"sorting"
] | [
"const accountsMerge = function (accounts) {\n const roots = new Set()\n const owner = {}\n const parent = {}\n const children = {}\n\n for (let account of accounts) {\n let [user, root, ...emails] = account\n let r1 = find(root)\n owner[root] = user\n children[r1] = children[r1] || [root]\n roots.add(r1)\n\n for (let email of emails) {\n let r2 = find(email)\n if (r2 !== r1) {\n parent[r2] = r1\n children[r1].push(...(children[r2] ? children[r2] : [email]))\n roots.delete(r2)\n delete children[r2]\n }\n }\n }\n\n return [...roots].map((r) => [owner[r], ...children[r].sort()])\n\n function find(a) {\n parent[a] = parent[a] || a\n return a === parent[a] ? a : find(parent[a])\n }\n}"
] |
|
722 | remove-comments | [
"Carefully parse each line according to the following rules:\r\n\r\n* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.\r\n\r\n* If we end a block comment and we are in a block, then we will skip over the next two characters and change our state to be *not* in a block.\r\n\r\n* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.\r\n\r\n* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.\r\n\r\n* At the end of each line, if we aren't in a block, we will record the line."
] | /**
* @param {string[]} source
* @return {string[]}
*/
var removeComments = function(source) {
}; | Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith line of the source code. This represents the result of splitting the original source code string by the newline character '\n'.
In C++, there are two types of comments, line comments, and block comments.
The string "//" denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
The string "/*" denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of "*/" should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string "/*/" does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
For example, if the string "//" occurs in a block comment, it is ignored.
Similarly, if the string "/*" occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
For example, source = "string s = "/* Not a comment. */";" will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so "/*" outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return the source code in the same format.
Example 1:
Input: source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"]
Output: ["int main()","{ "," ","int a, b, c;","a = b + c;","}"]
Explanation: The line by line code is visualized as below:
/*Test program */
int main()
{
// variable declaration
int a, b, c;
/* This is a test
multiline
comment for
testing */
a = b + c;
}
The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
Example 2:
Input: source = ["a/*comment", "line", "more_comment*/b"]
Output: ["ab"]
Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].
Constraints:
1 <= source.length <= 100
0 <= source[i].length <= 80
source[i] consists of printable ASCII characters.
Every open block comment is eventually closed.
There are no single-quote or double-quote in the input.
| Medium | [
"array",
"string"
] | [
"const removeComments = function (source) {\n const code = source.join('\\n')\n const isBlockStart = (c, i) => c[i] === '/' && c[i + 1] === '*'\n const isBlockEnd = (c, i) => c[i] === '*' && c[i + 1] === '/'\n const isLineStart = (c, i) => c[i] === '/' && c[i + 1] === '/'\n const isNewLine = (c, i) => c[i] === '\\n'\n let i = 0,\n output = ''\n\n while (i < code.length) {\n if (isBlockStart(code, i)) {\n i += 2\n while (!isBlockEnd(code, i) && i < code.length) i++\n i += 2\n } else if (isLineStart(code, i)) {\n i += 2\n while (!isNewLine(code, i) && i < code.length) i++\n } else {\n output += code[i++]\n }\n }\n\n return output.split('\\n').filter((l) => l.length)\n}"
] |
|
724 | find-pivot-index | [
"Create an array sumLeft where sumLeft[i] is the sum of all the numbers to the left of index i.",
"Create an array sumRight where sumRight[i] is the sum of all the numbers to the right of index i.",
"For each index i, check if sumLeft[i] equals sumRight[i] return i. If no i found, return -1."
] | /**
* @param {number[]} nums
* @return {number}
*/
var pivotIndex = function(nums) {
}; | Given an array of integers nums, calculate the pivot index of this array.
The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.
If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.
Return the leftmost pivot index. If no such index exists, return -1.
Example 1:
Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation:
The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11
Example 2:
Input: nums = [1,2,3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
Example 3:
Input: nums = [2,1,-1]
Output: 0
Explanation:
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0
Constraints:
1 <= nums.length <= 104
-1000 <= nums[i] <= 1000
Note: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/
| Easy | [
"array",
"prefix-sum"
] | [
"const pivotIndex = function(nums) {\n let sum = 0;\n let leftSum = 0;\n nums.forEach(num => {sum += num});\n \n for (let i = 0; i < nums.length; i++) {\n if (leftSum === sum - leftSum - nums[i]) return i;\n leftSum += nums[i];\n }\n return -1;\n};"
] |
|
725 | split-linked-list-in-parts | [
"If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one."
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode[]}
*/
var splitListToParts = function(head, k) {
}; | Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return an array of the k parts.
Example 1:
Input: head = [1,2,3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null, but its string representation as a ListNode is [].
Example 2:
Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3
Output: [[1,2,3,4],[5,6,7],[8,9,10]]
Explanation:
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
Constraints:
The number of nodes in the list is in the range [0, 1000].
0 <= Node.val <= 1000
1 <= k <= 50
| Medium | [
"linked-list"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const splitListToParts = function(root, k) {\n let cur = root;\n let N = 0;\n while (cur != null) {\n cur = cur.next;\n N++;\n }\n let width = Math.floor(N / k),\n rem = N % k;\n let ans = [];\n cur = root;\n for (let i = 0; i < k; ++i) {\n let head = cur;\n for (let j = 0; j < width + (i < rem ? 1 : 0) - 1; ++j) {\n if (cur != null) cur = cur.next;\n }\n if (cur != null) {\n let prev = cur;\n cur = cur.next;\n prev.next = null;\n }\n ans[i] = head;\n }\n return ans;\n};"
] |
726 | number-of-atoms | [
"To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.\r\n\r\nOtherwise, we should see an uppercase character: we will parse the rest of the letters to get the name, and add that (plus the multiplicity if there is one.)"
] | /**
* @param {string} formula
* @return {string}
*/
var countOfAtoms = function(formula) {
}; | Given a string formula representing a chemical formula, return the count of each atom.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.
For example, "H2O" and "H2O2" are possible, but "H1O2" is impossible.
Two formulas are concatenated together to produce another formula.
For example, "H2O2He3Mg4" is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
For example, "(H2O2)" and "(H2O2)3" are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.
The test cases are generated so that all the values in the output fit in a 32-bit integer.
Example 1:
Input: formula = "H2O"
Output: "H2O"
Explanation: The count of elements are {'H': 2, 'O': 1}.
Example 2:
Input: formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
Example 3:
Input: formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
Constraints:
1 <= formula.length <= 1000
formula consists of English letters, digits, '(', and ')'.
formula is always valid.
| Hard | [
"hash-table",
"string",
"stack",
"sorting"
] | [
"function countOfAtoms(formula) {\n let [dic, coeff, stack, elem, cnt, j, res] = [{}, 1, [], '', 0, 0, '']\n for (let i = formula.length - 1; i >= 0; i--) {\n if (!isNaN(formula[i] * 1)) {\n ;(cnt += Number(formula[i]) * 10 ** j), (j += 1)\n } else if (formula[i] == ')') {\n stack.push(cnt), (coeff *= cnt), (j = cnt = 0)\n } else if (formula[i] == '(') {\n ;(coeff = Math.floor(coeff / stack.pop())), (j = cnt = 0)\n } else if (formula[i] == formula[i].toUpperCase()) {\n elem += formula[i]\n elem = elem\n .split('')\n .reverse()\n .join('')\n dic[elem] = dic[elem] || 0\n dic[elem] += (cnt || 1) * coeff\n ;(elem = ''), (j = cnt = 0)\n } else {\n elem += formula[i]\n }\n }\n Object.keys(dic)\n .sort()\n .forEach(function(c) {\n res += dic[c] > 1 ? c + String(dic[c]) : c\n })\n return res\n}"
] |
|
728 | self-dividing-numbers | [
"For each number in the range, check whether it is self dividing by converting that number to a character array (or string in Python), then checking that each digit is nonzero and divides the original number."
] | /**
* @param {number} left
* @param {number} right
* @return {number[]}
*/
var selfDividingNumbers = function(left, right) {
}; | A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
A self-dividing number is not allowed to contain the digit zero.
Given two integers left and right, return a list of all the self-dividing numbers in the range [left, right].
Example 1:
Input: left = 1, right = 22
Output: [1,2,3,4,5,6,7,8,9,11,12,15,22]
Example 2:
Input: left = 47, right = 85
Output: [48,55,66,77]
Constraints:
1 <= left <= right <= 104
| Easy | [
"math"
] | null | [] |
729 | my-calendar-i | [
"Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added."
] |
var MyCalendar = function() {
};
/**
* @param {number} start
* @param {number} end
* @return {boolean}
*/
MyCalendar.prototype.book = function(start, end) {
};
/**
* Your MyCalendar object will be instantiated and called as such:
* var obj = new MyCalendar()
* var param_1 = obj.book(start,end)
*/ | You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking.
A double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.).
The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.
Implement the MyCalendar class:
MyCalendar() Initializes the calendar object.
boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar.
Example 1:
Input
["MyCalendar", "book", "book", "book"]
[[], [10, 20], [15, 25], [20, 30]]
Output
[null, true, false, true]
Explanation
MyCalendar myCalendar = new MyCalendar();
myCalendar.book(10, 20); // return True
myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.
myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.
Constraints:
0 <= start < end <= 109
At most 1000 calls will be made to book.
| Medium | [
"binary-search",
"design",
"segment-tree",
"ordered-set"
] | [
"const MyCalendar = function () {\n this.root = null\n}\n\nconst Node = function (start, end) {\n this.start = start\n this.end = end\n this.left = null\n this.right = null\n}\n\nNode.prototype.insert = function (node) {\n if (node.start >= this.end) {\n if (this.right === null) {\n this.right = node\n return true\n }\n return this.right.insert(node)\n } else if (node.end <= this.start) {\n if (this.left === null) {\n this.left = node\n return true\n }\n return this.left.insert(node)\n } else {\n return false\n }\n}\n\n\nMyCalendar.prototype.book = function (start, end) {\n const newNode = new Node(start, end)\n if (this.root === null) {\n this.root = newNode\n return true\n } else {\n return this.root.insert(newNode)\n }\n}",
"const MyCalendar = function() {\n this.s = new Set()\n};\n\n\nMyCalendar.prototype.book = function(start, end) {\n for(let e of this.s) {\n if(Math.max(start, e[0]) < Math.min(end, e[1])) return false\n }\n this.s.add([start, end])\n return true\n};"
] |
|
730 | count-different-palindromic-subsequences | [
"Let dp(i, j) be the answer for the string T = S[i:j+1] including the empty sequence. The answer is the number of unique characters in T, plus palindromes of the form \"a_a\", \"b_b\", \"c_c\", and \"d_d\", where \"_\" represents zero or more characters."
] | /**
* @param {string} s
* @return {number}
*/
var countPalindromicSubsequences = function(s) {
}; | Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 109 + 7.
A subsequence of a string is obtained by deleting zero or more characters from the string.
A sequence is palindromic if it is equal to the sequence reversed.
Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi.
Example 1:
Input: s = "bccb"
Output: 6
Explanation: The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
Note that 'bcb' is counted only once, even though it occurs twice.
Example 2:
Input: s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba"
Output: 104860361
Explanation: There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7.
Constraints:
1 <= s.length <= 1000
s[i] is either 'a', 'b', 'c', or 'd'.
| Hard | [
"string",
"dynamic-programming"
] | [
"const countPalindromicSubsequences = function(S) {\n const len = S.length\n const dp = Array.from({ length: len }, () => new Array(len).fill(0))\n const mod = 10 ** 9 + 7\n for (let i = 0; i < len; i++) dp[i][i] = 1\n for (let distance = 1; distance < len; distance++) {\n for (let i = 0; i < len - distance; i++) {\n let j = i + distance\n if (S[i] === S[j]) {\n let low = i + 1\n let high = j - 1\n while (low <= high && S[low] != S[j]) low++\n while (low <= high && S[high] != S[j]) high--\n if (low > high) {\n dp[i][j] = dp[i + 1][j - 1] * 2 + 2\n } else if (low == high) {\n dp[i][j] = dp[i + 1][j - 1] * 2 + 1\n } else {\n dp[i][j] = dp[i + 1][j - 1] * 2 - dp[low + 1][high - 1]\n }\n } else {\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]\n }\n dp[i][j] = dp[i][j] < 0 ? dp[i][j] + mod : dp[i][j] % mod\n }\n }\n return dp[0][len - 1]\n}"
] |
|
731 | my-calendar-ii | [
"Store two sorted lists of intervals: one list will be all times that are at least single booked, and another list will be all times that are definitely double booked. If none of the double bookings conflict, then the booking will succeed, and you should update your single and double bookings accordingly."
] |
var MyCalendarTwo = function() {
};
/**
* @param {number} start
* @param {number} end
* @return {boolean}
*/
MyCalendarTwo.prototype.book = function(start, end) {
};
/**
* Your MyCalendarTwo object will be instantiated and called as such:
* var obj = new MyCalendarTwo()
* var param_1 = obj.book(start,end)
*/ | You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking.
A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).
The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.
Implement the MyCalendarTwo class:
MyCalendarTwo() Initializes the calendar object.
boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar.
Example 1:
Input
["MyCalendarTwo", "book", "book", "book", "book", "book", "book"]
[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Output
[null, true, true, true, false, true, true]
Explanation
MyCalendarTwo myCalendarTwo = new MyCalendarTwo();
myCalendarTwo.book(10, 20); // return True, The event can be booked.
myCalendarTwo.book(50, 60); // return True, The event can be booked.
myCalendarTwo.book(10, 40); // return True, The event can be double booked.
myCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.
myCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.
myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.
Constraints:
0 <= start < end <= 109
At most 1000 calls will be made to book.
| Medium | [
"binary-search",
"design",
"segment-tree",
"ordered-set"
] | [
"const MyCalendarTwo = function () {\n this.calendar = []\n this.overlaps = []\n}\n\n\nMyCalendarTwo.prototype.book = function (start, end) {\n for (let i = 0; i < this.overlaps.length; i++) {\n if (start < this.overlaps[i].end && end > this.overlaps[i].start)\n return false\n }\n\n for (let i = 0; i < this.calendar.length; i++) {\n if (start < this.calendar[i].end && end > this.calendar[i].start)\n this.overlaps.push({\n start: Math.max(start, this.calendar[i].start),\n end: Math.min(end, this.calendar[i].end),\n })\n }\n this.calendar.push({ start: start, end: end })\n return true\n}"
] |
|
732 | my-calendar-iii | [
"Treat each interval [start, end) as two events \"start\" and \"end\", and process them in sorted order."
] |
var MyCalendarThree = function() {
};
/**
* @param {number} startTime
* @param {number} endTime
* @return {number}
*/
MyCalendarThree.prototype.book = function(startTime, endTime) {
};
/**
* Your MyCalendarThree object will be instantiated and called as such:
* var obj = new MyCalendarThree()
* var param_1 = obj.book(startTime,endTime)
*/ | A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)
You are given some events [startTime, endTime), after each given event, return an integer k representing the maximum k-booking between all the previous events.
Implement the MyCalendarThree class:
MyCalendarThree() Initializes the object.
int book(int startTime, int endTime) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar.
Example 1:
Input
["MyCalendarThree", "book", "book", "book", "book", "book", "book"]
[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Output
[null, 1, 1, 2, 3, 3, 3]
Explanation
MyCalendarThree myCalendarThree = new MyCalendarThree();
myCalendarThree.book(10, 20); // return 1
myCalendarThree.book(50, 60); // return 1
myCalendarThree.book(10, 40); // return 2
myCalendarThree.book(5, 15); // return 3
myCalendarThree.book(5, 10); // return 3
myCalendarThree.book(25, 55); // return 3
Constraints:
0 <= startTime < endTime <= 109
At most 400 calls will be made to book.
| Hard | [
"binary-search",
"design",
"segment-tree",
"ordered-set"
] | [
"const find = (cals, time, count) => {\n let l = 0\n let r = cals.length\n let mid\n while (l < r) {\n mid = Math.trunc((l + r) / 2)\n if (cals[mid][0] === time) {\n cals[mid][1] += count\n return\n } else if (cals[mid][0] < time) {\n l = mid + 1\n } else {\n r = mid\n }\n }\n cals.splice(l, 0, [time, count])\n}\nconst MyCalendarThree = function() {\n this.cals = []\n}\n\n\nMyCalendarThree.prototype.book = function(start, end) {\n let idx = find(this.cals, start, 1)\n idx = find(this.cals, end, -1)\n let count = 0\n let max = 0\n for (let cal of this.cals) {\n count += cal[1]\n max = Math.max(max, count)\n }\n return max\n}",
"var MyCalendarThree = function() {\n this.st = new SegmentTree(0, 10 ** 9);\n};\n\n\nMyCalendarThree.prototype.book = function(start, end) {\n this.st.add(start, end); \n return this.st.getMax();\n};\n\n\n\nclass SegmentTree {\n constructor(start, end) {\n this.root = new TreeNode(start, end);\n }\n \n add(qs, qe, node=this.root) {\n \n // completely outside of query range\n if(qs > node.end || qe <= node.start) {\n return node.val;\n }\n \n // completely covered by query range\n if(qs <= node.start && qe > node.end) {\n node.booked += 1;\n node.val += 1;\n return node.val;\n }\n\n let mid = (node.start + node.end)/2 >> 0;\n\n if(!node.left) {\n node.left = new TreeNode(node.start, mid);\n }\n\n if(!node.right) {\n node.right = new TreeNode(mid+1, node.end);\n }\n\n node.val = Math.max(\n this.add(qs, qe, node.left),\n this.add(qs, qe, node.right),\n ) + node.booked;\n\n return node.val;\n \n }\n \n getMax() {\n return this.root.val;\n }\n \n}\n\nclass TreeNode {\n constructor(start, end) {\n this.start = start;\n this.end = end;\n this.val = 0;\n this.booked = 0;\n this.left = this.right = null;\n }\n}"
] |
|
733 | flood-fill | [
"Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels."
] | /**
* @param {number[][]} image
* @param {number} sr
* @param {number} sc
* @param {number} color
* @return {number[][]}
*/
var floodFill = function(image, sr, sc, color) {
}; | An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.
Return the modified image after performing the flood fill.
Example 1:
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
Example 2:
Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0
Output: [[0,0,0],[0,0,0]]
Explanation: The starting pixel is already colored 0, so no changes are made to the image.
Constraints:
m == image.length
n == image[i].length
1 <= m, n <= 50
0 <= image[i][j], color < 216
0 <= sr < m
0 <= sc < n
| Easy | [
"array",
"depth-first-search",
"breadth-first-search",
"matrix"
] | [
"const floodFill = function(image, sr, sc, newColor, firstColor = image[sr][sc]) {\n if (\n sr < 0 ||\n sc < 0 ||\n sr >= image.length ||\n sc >= image[sr].length ||\n image[sr][sc] !== firstColor ||\n image[sr][sc] === newColor\n ) {\n return image\n }\n\n image[sr][sc] = newColor\n\n floodFill(image, sr + 1, sc, newColor, firstColor)\n floodFill(image, sr - 1, sc, newColor, firstColor)\n floodFill(image, sr, sc + 1, newColor, firstColor)\n floodFill(image, sr, sc - 1, newColor, firstColor)\n\n return image\n}",
"const floodFill = function (\n image,\n sr,\n sc,\n newColor,\n firstColor = image[sr][sc]\n) {\n const dirs = [0, -1, 0, 1, 0]\n const rows = image.length\n const cols = image[0].length\n const q = [[sr, sc]]\n while (q.length) {\n const len = q.length\n for (let i = 0; i < len; i++) {\n const cur = q.shift()\n image[cur[0]][cur[1]] = newColor\n for (let j = 0; j < 4; j++) {\n const [nr, nc] = [cur[0] + dirs[j], cur[1] + dirs[j + 1]]\n if (\n nr >= 0 &&\n nr < rows &&\n nc >= 0 &&\n nc < cols &&\n image[nr][nc] === firstColor &&\n image[nr][nc] !== newColor\n ) {\n q.push([nr, nc])\n }\n }\n }\n }\n return image\n}"
] |
|
735 | asteroid-collision | [
"Say a row of asteroids is stable. What happens when a new asteroid is added on the right?"
] | /**
* @param {number[]} asteroids
* @return {number[]}
*/
var asteroidCollision = function(asteroids) {
}; | We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
Example 1:
Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input: asteroids = [8,-8]
Output: []
Explanation: The 8 and -8 collide exploding each other.
Example 3:
Input: asteroids = [10,2,-5]
Output: [10]
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
Constraints:
2 <= asteroids.length <= 104
-1000 <= asteroids[i] <= 1000
asteroids[i] != 0
| Medium | [
"array",
"stack",
"simulation"
] | [
"const asteroidCollision = function(asteroids) {\n const positive = []\n const res = []\n for(let i = 0; i < asteroids.length; i++) {\n if (asteroids[i] > 0) {\n positive.push(i)\n } else {\n const negVal = asteroids[i];\n\n while(positive.length > 0 && asteroids[ positive[positive.length - 1] ] + negVal < 0 ) {\n asteroids[ positive[positive.length - 1] ] = undefined\n positive.pop()\n }\n\n if (positive.length > 0) {\n if (asteroids[ positive[positive.length - 1] ] + negVal > 0) {\n asteroids[i] = undefined\n } else if(asteroids[ positive[positive.length - 1] ] + negVal === 0) {\n asteroids[i] = undefined\n asteroids[ positive[positive.length - 1] ] = undefined\n positive.pop()\n }\n }\n }\n }\n return asteroids.filter(el => el !== undefined)\n};"
] |
|
736 | parse-lisp-expression | [
"* If the expression starts with a digit or '-', it's an integer: return it.\r\n\r\n* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.\r\n\r\n* Otherwise, group the tokens (variables or expressions) within this expression by counting the \"balance\" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.\r\n\r\n* For add and mult expressions, evaluate each token and return the addition or multiplication of them.\r\n\r\n* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression."
] | /**
* @param {string} expression
* @return {number}
*/
var evaluate = function(expression) {
}; | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
(An integer could be positive or negative.)
A let expression takes the form "(let v1 e1 v2 e2 ... vn en expr)", where let is always the string "let", then there are one or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let expression is the value of the expression expr.
An add expression takes the form "(add e1 e2)" where add is always the string "add", there are always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the evaluation of e2.
A mult expression takes the form "(mult e1 e2)" where mult is always the string "mult", there are always two expressions e1, e2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names "add", "let", and "mult" are protected and will never be used as variable names.
Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
Example 1:
Input: expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))"
Output: 14
Explanation: In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
Example 2:
Input: expression = "(let x 3 x 2 x)"
Output: 2
Explanation: Assignment in let statements is processed sequentially.
Example 3:
Input: expression = "(let x 1 y 2 x (add x y) (add x y))"
Output: 5
Explanation: The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
Constraints:
1 <= expression.length <= 2000
There are no leading or trailing spaces in expression.
All tokens are separated by a single space in expression.
The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.
The expression is guaranteed to be legal and evaluate to an integer.
| Hard | [
"hash-table",
"string",
"stack",
"recursion"
] | [
"const evaluate = (x) =>\n e(\n JSON.parse(\n x.replace(/[() ]|([a-z][a-z0-9]*)/g, (m) =>\n m === '(' ? '[' : m === ')' ? ']' : m === ' ' ? ',' : `\"${m}\"`\n )\n )\n )\nconst e = (x, v = []) =>\n ({\n string: () => v.find((y) => y[0] === x)[1],\n number: () => x,\n object: () =>\n ({\n add: () => e(x[1], v) + e(x[2], v),\n mult: () => e(x[1], v) * e(x[2], v),\n let: () =>\n e(\n x[x.length - 1],\n x\n .slice(1, -1)\n .reduce(\n ({ v, t }, z) =>\n t ? { v: [[t, e(z, v)], ...v] } : { v, t: z },\n { v }\n ).v\n ),\n }[x[0]]()),\n }[typeof x]())",
"const evaluate = function (expression) {\n const tokens = tokenizer(expression)\n let i = 0\n function exec(scope) {\n let value = null\n const next = tokens[i++]\n if (next === '(') {\n scope = enter(scope)\n switch (tokens[i++]) {\n case 'add':\n const a = exec(scope)\n const b = exec(scope)\n value = a + b\n break\n case 'mult':\n const x = exec(scope)\n const y = exec(scope)\n value = x * y\n break\n case 'let':\n while (tokens[i] !== '(' && tokens[i + 1] !== ')') {\n scope.variables[tokens[i++]] = exec(scope)\n }\n value = exec(scope)\n break\n }\n scope = exit(scope)\n i++\n } else if (isNumber(next)) {\n value = Number(next)\n } else {\n // Find variable in current scope otherwise go to parent\n let t = scope\n while (t) {\n if (next in t.variables) {\n value = t.variables[next]\n break\n }\n t = t.parent\n }\n }\n return value\n }\n return exec(newScope())\n}\nfunction tokenizer(expression) {\n const tokens = []\n let token = ''\n for (const c of expression) {\n if (c === '(' || c === ')') {\n if (token) tokens.push(token)\n tokens.push(c)\n token = ''\n } else if (c === ' ') {\n if (token) tokens.push(token)\n token = ''\n } else {\n token += c\n }\n }\n if (token) {\n tokens.push(token)\n }\n return tokens\n}\nfunction isNumber(n) {\n return !isNaN(n)\n}\nfunction newScope() {\n return { parent: null, variables: {} }\n}\nfunction enter(scope) {\n const next = newScope()\n next.parent = scope\n return next\n}\nfunction exit(scope) {\n return scope.parent\n}"
] |
|
738 | monotone-increasing-digits | [
"Build the answer digit by digit, adding the largest possible one that would make the number still less than or equal to N."
] | /**
* @param {number} n
* @return {number}
*/
var monotoneIncreasingDigits = function(n) {
}; | An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.
Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits.
Example 1:
Input: n = 10
Output: 9
Example 2:
Input: n = 1234
Output: 1234
Example 3:
Input: n = 332
Output: 299
Constraints:
0 <= n <= 109
| Medium | [
"math",
"greedy"
] | [
"function monotoneIncreasingDigits(N) {\n const arr = (''+N).split('').map(el => +el)\n let mark = arr.length\n for(let i = arr.length - 1; i > 0; i--) {\n if (arr[i] < arr[i - 1]) {\n mark = i - 1\n arr[i - 1]--\n }\n }\n for(let i = mark + 1; i < arr.length; i++) {\n arr[i] = 9\n }\n\n return arr.join('')\n}"
] |
|
739 | daily-temperatures | [
"If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next."
] | /**
* @param {number[]} temperatures
* @return {number[]}
*/
var dailyTemperatures = function(temperatures) {
}; | Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90]
Output: [1,1,0]
Constraints:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100
| Medium | [
"array",
"stack",
"monotonic-stack"
] | [
"const dailyTemperatures = function(T) {\n const n = T.length;\n const sk = [];\n const res = new Array(n).fill(0);\n for (let i = 0; i < n; i++) {\n let cur = T[i];\n while (sk.length && T[sk[sk.length - 1]] < cur) {\n let tail = sk.pop();\n res[tail] = i - tail;\n }\n sk.push(i);\n }\n return res;\n};"
] |
|
740 | delete-and-earn | [
"If you take a number, you might as well take them all. Keep track of what the value is of the subset of the input with maximum M when you either take or don't take M."
] | /**
* @param {number[]} nums
* @return {number}
*/
var deleteAndEarn = function(nums) {
}; | You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:
Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.
Return the maximum number of points you can earn by applying the above operation some number of times.
Example 1:
Input: nums = [3,4,2]
Output: 6
Explanation: You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].
- Delete 2 to earn 2 points. nums = [].
You earn a total of 6 points.
Example 2:
Input: nums = [2,2,3,3,3,4]
Output: 9
Explanation: You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].
- Delete a 3 again to earn 3 points. nums = [3].
- Delete a 3 once more to earn 3 points. nums = [].
You earn a total of 9 points.
Constraints:
1 <= nums.length <= 2 * 104
1 <= nums[i] <= 104
| Medium | [
"array",
"hash-table",
"dynamic-programming"
] | [
"const deleteAndEarn = function (nums) {\n const n = 10001\n const values = new Array(n).fill(0)\n for (let num of nums) values[num] += num\n\n let take = 0,\n skip = 0\n for (let i = 0; i < n; i++) {\n const takei = skip + values[i]\n const skipi = Math.max(skip, take)\n take = takei\n skip = skipi\n }\n return Math.max(take, skip)\n}"
] |
|
741 | cherry-pickup | [] | /**
* @param {number[][]} grid
* @return {number}
*/
var cherryPickup = function(grid) {
}; | You are given an n x n grid representing a field of cherries, each cell is one of three possible integers.
0 means the cell is empty, so you can pass through,
1 means the cell contains a cherry that you can pick up and pass through, or
-1 means the cell contains a thorn that blocks your way.
Return the maximum number of cherries you can collect by following the rules below:
Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1).
After reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells.
When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell 0.
If there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected.
Example 1:
Input: grid = [[0,1,-1],[1,0,-1],[1,1,1]]
Output: 5
Explanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).
4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.
Example 2:
Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]
Output: 0
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 50
grid[i][j] is -1, 0, or 1.
grid[0][0] != -1
grid[n - 1][n - 1] != -1
| Hard | [
"array",
"dynamic-programming",
"matrix"
] | [
"const cherryPickup = grid => {\n const n = grid.length\n const dp = [...new Array(n)].map(() =>\n [...new Array(n)].map(() => Array(n).fill(-Infinity))\n )\n dp[0][0][0] = grid[0][0]\n const go = (x1, y1, x2) => {\n const y2 = x1 + y1 - x2\n if (x1 < 0 || y1 < 0 || x2 < 0 || y2 < 0) return -1\n if (grid[y1][x1] === -1 || grid[y2][x2] === -1) return -1\n if (dp[y1][x1][x2] !== -Infinity) return dp[y1][x1][x2]\n dp[y1][x1][x2] = Math.max(\n go(x1 - 1, y1, x2 - 1),\n go(x1, y1 - 1, x2),\n go(x1, y1 - 1, x2 - 1),\n go(x1 - 1, y1, x2)\n )\n if (dp[y1][x1][x2] >= 0) {\n dp[y1][x1][x2] += grid[y1][x1]\n if (x1 !== x2) dp[y1][x1][x2] += grid[y2][x2]\n }\n return dp[y1][x1][x2]\n }\n return Math.max(0, go(n - 1, n - 1, n - 1))\n}"
] |
|
743 | network-delay-time | [
"We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm."
] | /**
* @param {number[][]} times
* @param {number} n
* @param {number} k
* @return {number}
*/
var networkDelayTime = function(times, n, k) {
}; | You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.
We will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.
Example 1:
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2
Example 2:
Input: times = [[1,2,1]], n = 2, k = 1
Output: 1
Example 3:
Input: times = [[1,2,1]], n = 2, k = 2
Output: -1
Constraints:
1 <= k <= n <= 100
1 <= times.length <= 6000
times[i].length == 3
1 <= ui, vi <= n
ui != vi
0 <= wi <= 100
All the pairs (ui, vi) are unique. (i.e., no multiple edges.)
| Medium | [
"depth-first-search",
"breadth-first-search",
"graph",
"heap-priority-queue",
"shortest-path"
] | [
"const networkDelayTime = function(times, n, k) {\n const graph = {}\n for(const [u, v, w] of times) {\n if(graph[u] == null) graph[u] = []\n graph[u][v] = w\n }\n const visited = new Array(n + 1).fill(false)\n const pq = new PQ((a, b) => a[0] < b[0])\n pq.push([0, k])\n let res = 0\n while(!pq.isEmpty()) {\n const [dist, cur] = pq.pop()\n if(visited[cur]) continue\n visited[cur] = true\n n--\n res = dist\n if(graph[cur]) {\n for(const nxt of Object.keys(graph[cur])) {\n pq.push([res + graph[cur][nxt], nxt])\n }\n }\n }\n return n === 0 ? res : -1\n};\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}",
"const networkDelayTime = function (times, N, K) {\n const mins = new Array(N).fill(Infinity)\n mins[K - 1] = 0\n for (let i = 0; i < N; i++) {\n for (let [u, v, t] of times) {\n if (mins[u - 1] === Infinity) continue\n if (mins[v - 1] > mins[u - 1] + t) {\n mins[v - 1] = mins[u - 1] + t\n }\n }\n }\n return mins.includes(Infinity) ? -1 : Math.max(...mins)\n}",
"const networkDelayTime = function(times, N, K) {\n const distances = new Array(N).fill(Infinity);\n distances[K - 1] = 0;\n \n for(let i = 0 ; i < N -1 ; i++){\n let counter = 0;\n for(let j = 0 ; j < times.length ; j++){\n const source = times[j][0];\n const target = times[j][1];\n const weight = times[j][2];\n if(distances[source - 1] + weight < distances[target - 1]){\n distances[target - 1] = distances[source - 1] + weight;\n counter++\n }\n }\n if(counter === 0) break\n }\n \n const res = Math.max(...distances);\n return res === Infinity ? -1 : res;\n};",
"const networkDelayTime = function (times, N, K) {\n const hash = {}\n for(const [u, v, t] of times) {\n if(hash[u] == null) hash[u] = {}\n hash[u][v] = t\n }\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n pq.push([0, K])\n const visited = Array.from(N + 1)\n let res = 0\n while(!pq.isEmpty()) {\n const [dist, cur] = pq.pop()\n if(visited[cur]) continue\n visited[cur] = true\n res = dist\n N--\n if(hash[cur]) {\n for(let next of Object.keys(hash[cur])) {\n pq.push([dist + hash[cur][next], next])\n }\n }\n }\n return N === 0 ? res : -1\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}"
] |
|
744 | find-smallest-letter-greater-than-target | [
"Try to find whether each of 26 next letters are in the given string array."
] | /**
* @param {character[]} letters
* @param {character} target
* @return {character}
*/
var nextGreatestLetter = function(letters, target) {
}; | You are given an array of characters letters that is sorted in non-decreasing order, and a character target. There are at least two different characters in letters.
Return the smallest character in letters that is lexicographically greater than target. If such a character does not exist, return the first character in letters.
Example 1:
Input: letters = ["c","f","j"], target = "a"
Output: "c"
Explanation: The smallest character that is lexicographically greater than 'a' in letters is 'c'.
Example 2:
Input: letters = ["c","f","j"], target = "c"
Output: "f"
Explanation: The smallest character that is lexicographically greater than 'c' in letters is 'f'.
Example 3:
Input: letters = ["x","x","y","y"], target = "z"
Output: "x"
Explanation: There are no characters in letters that is lexicographically greater than 'z' so we return letters[0].
Constraints:
2 <= letters.length <= 104
letters[i] is a lowercase English letter.
letters is sorted in non-decreasing order.
letters contains at least two different characters.
target is a lowercase English letter.
| Easy | [
"array",
"binary-search"
] | [
"const nextGreatestLetter = function (letters, target) {\n const n = letters.length\n if (target < letters[0] || target >= letters[n - 1]) return letters[0]\n let left = 0\n let right = n - 1\n while (left < right) {\n let mid = left + ((right - left) >> 1)\n if (letters[mid] <= target) left = mid + 1\n else right = mid\n }\n return letters[right]\n}"
] |
|
745 | prefix-and-suffix-search | [
"Take \"apple\" as an example, we will insert add \"apple{apple\", \"pple{apple\", \"ple{apple\", \"le{apple\", \"e{apple\", \"{apple\" into the Trie Tree.",
"If the query is: prefix = \"app\", suffix = \"le\", we can find it by querying our trie for\r\n\"le { app\".",
"We use '{' because in ASCii Table, '{' is next to 'z', so we just need to create new TrieNode[27] instead of 26. Also, compared with traditional Trie, we add the attribute weight in class TrieNode.\r\nYou can still choose any different character."
] | /**
* @param {string[]} words
*/
var WordFilter = function(words) {
};
/**
* @param {string} pref
* @param {string} suff
* @return {number}
*/
WordFilter.prototype.f = function(pref, suff) {
};
/**
* Your WordFilter object will be instantiated and called as such:
* var obj = new WordFilter(words)
* var param_1 = obj.f(pref,suff)
*/ | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the WordFilter class:
WordFilter(string[] words) Initializes the object with the words in the dictionary.
f(string pref, string suff) Returns the index of the word in the dictionary, which has the prefix pref and the suffix suff. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.
Example 1:
Input
["WordFilter", "f"]
[[["apple"]], ["a", "e"]]
Output
[null, 0]
Explanation
WordFilter wordFilter = new WordFilter(["apple"]);
wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = "e".
Constraints:
1 <= words.length <= 104
1 <= words[i].length <= 7
1 <= pref.length, suff.length <= 7
words[i], pref and suff consist of lowercase English letters only.
At most 104 calls will be made to the function f.
| Hard | [
"hash-table",
"string",
"design",
"trie"
] | [
"const WordFilter = function (words) {\n this.trie = new trie()\n let val = 0\n for (let word of words) {\n \n let temp = ''\n this.trie.insert('#' + word, val)\n this.trie.insert(word + '#', val)\n for (let i = 0; i < word.length; i++) {\n temp = word.substring(i)\n temp += '#' + word\n this.trie.insert(temp, val)\n }\n val++\n }\n}\n\nWordFilter.prototype.f = function (prefix, suffix) {\n return this.trie.startsWith(suffix + '#' + prefix)\n}\n\nconst trie = function () {\n this.map = new Map()\n this.isEnd = false\n this.val = -1\n}\ntrie.prototype.insert = function (word, val) {\n let temp = this\n let i = 0\n while (i < word.length && temp.map.has(word[i])) {\n temp.val = Math.max(temp.val, val)\n temp = temp.map.get(word[i++])\n }\n while (i < word.length) {\n let t2 = new trie()\n temp.map.set(word[i++], t2)\n temp.val = Math.max(temp.val, val)\n temp = t2\n }\n temp.isEnd = true\n temp.val = Math.max(temp.val, val)\n return true\n}\ntrie.prototype.startsWith = function (prefix) {\n let temp = this\n let i = 0\n while (i < prefix.length && temp.map.has(prefix[i]))\n temp = temp.map.get(prefix[i++])\n return i >= prefix.length ? temp.val : -1\n}"
] |
|
746 | min-cost-climbing-stairs | [
"Build an array dp where dp[i] is the minimum cost to climb to the top starting from the ith staircase.",
"Assuming we have n staircase labeled from 0 to n - 1 and assuming the top is n, then dp[n] = 0, marking that if you are at the top, the cost is 0.",
"Now, looping from n - 1 to 0, the dp[i] = cost[i] + min(dp[i + 1], dp[i + 2]). The answer will be the minimum of dp[0] and dp[1]"
] | /**
* @param {number[]} cost
* @return {number}
*/
var minCostClimbingStairs = function(cost) {
}; | You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
Example 1:
Input: cost = [10,15,20]
Output: 15
Explanation: You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
Example 2:
Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6
Explanation: You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
Constraints:
2 <= cost.length <= 1000
0 <= cost[i] <= 999
| Easy | [
"array",
"dynamic-programming"
] | [
"const minCostClimbingStairs = function(cost) {\n let f1 = cost[0];\n let f2 = cost[1];\n for (let i = 2; i < cost.length; i++) {\n let f_cur = cost[i] + Math.min(f1, f2);\n f1 = f2;\n f2 = f_cur;\n }\n return Math.min(f1, f2);\n};"
] |
|
747 | largest-number-at-least-twice-of-others | [
"Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.\r\n\r\nScan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.\r\n\r\nOtherwise, we should return `maxIndex`."
] | /**
* @param {number[]} nums
* @return {number}
*/
var dominantIndex = function(nums) {
}; | You are given an integer array nums where the largest integer is unique.
Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.
Example 1:
Input: nums = [3,6,1,0]
Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
Example 2:
Input: nums = [1,2,3,4]
Output: -1
Explanation: 4 is less than twice the value of 3, so we return -1.
Constraints:
2 <= nums.length <= 50
0 <= nums[i] <= 100
The largest element in nums is unique.
| Easy | [
"array",
"sorting"
] | [
"const dominantIndex = function(nums) {\n let max = -Infinity\n let idx = -1\n for(let i = 0, len = nums.length; i < len; i++) {\n if(nums[i] > max) {\n max = nums[i]\n idx = i\n }\n }\n for(let i = 0, len = nums.length; i < len; i++) {\n if(nums[i] !== max && max < nums[i] * 2) return -1\n }\n return idx\n};"
] |
|
748 | shortest-completing-word | [
"Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet."
] | /**
* @param {string} licensePlate
* @param {string[]} words
* @return {string}
*/
var shortestCompletingWord = function(licensePlate, words) {
}; | Given a string licensePlate and an array of strings words, find the shortest completing word in words.
A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.
For example, if licensePlate = "aBc 12c", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are "abccdef", "caaacab", and "cbca".
Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.
Example 1:
Input: licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"]
Output: "steps"
Explanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step" contains 't' and 'p', but only contains 1 's'.
"steps" contains 't', 'p', and both 's' characters.
"stripe" is missing an 's'.
"stepple" is missing an 's'.
Since "steps" is the only word containing all the letters, that is the answer.
Example 2:
Input: licensePlate = "1s3 456", words = ["looks","pest","stew","show"]
Output: "pest"
Explanation: licensePlate only contains the letter 's'. All the words contain 's', but among these "pest", "stew", and "show" are shortest. The answer is "pest" because it is the word that appears earliest of the 3.
Constraints:
1 <= licensePlate.length <= 7
licensePlate contains digits, letters (uppercase or lowercase), or space ' '.
1 <= words.length <= 1000
1 <= words[i].length <= 15
words[i] consists of lower case English letters.
| Easy | [
"array",
"hash-table",
"string"
] | [
"const shortestCompletingWord = function(licensePlate, words) {\n const letters = licensePlate\n .replace(/\\d/g, '')\n .replace(/ /g, '')\n .toLowerCase()\n .split('')\n let matchingWords = words.filter(word => {\n let completingWord = true\n letters.forEach(letter => {\n let letterIndex = word.indexOf(letter)\n if (letterIndex > -1) {\n let re = new RegExp(letter)\n word = word.replace(re, '')\n } else {\n completingWord = false\n }\n })\n return completingWord\n })\n const wordLengths = matchingWords.map(word => word.length)\n return matchingWords[wordLengths.indexOf(Math.min.apply(Math, wordLengths))]\n}",
"const shortestCompletingWord = function(licensePlate, words) {\n licensePlate = licensePlate.toLowerCase()\n const plateCount = Array(26).fill(0)\n let plateLength = 0\n for (let i = 0; i < licensePlate.length; i += 1) {\n const code = licensePlate.charCodeAt(i)\n if (code < 97 || code > 122) {\n continue\n }\n plateCount[code - 97] += 1\n plateLength += 1\n }\n const longerOrEqualWords = words.filter(word => word.length >= plateLength)\n return longerOrEqualWords.reduce((shortest, word) => {\n if (shortest && shortest.length <= word.length) {\n return shortest\n }\n const wordCount = Array(26).fill(0)\n for (let i = 0; i < word.length; i += 1) {\n const code = word.charCodeAt(i)\n wordCount[code - 97] += 1\n }\n for (let i = 0; i < 26; i += 1) {\n if (wordCount[i] - plateCount[i] < 0) {\n return shortest\n }\n }\n return word\n }, null)\n}"
] |
|
749 | contain-virus | [
"The implementation is long - we want to perfrom the following steps:\r\n\r\n* Find all viral regions (connected components), additionally for each region keeping track of the frontier (neighboring uncontaminated cells), and the perimeter of the region.\r\n\r\n* Disinfect the most viral region, adding it's perimeter to the answer.\r\n\r\n* Spread the virus in the remaining regions outward by 1 square."
] | /**
* @param {number[][]} isInfected
* @return {number}
*/
var containVirus = function(isInfected) {
}; | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie.
Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.
Example 1:
Input: isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]
Output: 10
Explanation: There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
Example 2:
Input: isInfected = [[1,1,1],[1,0,1],[1,1,1]]
Output: 4
Explanation: Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
Example 3:
Input: isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]
Output: 13
Explanation: The region on the left only builds two new walls.
Constraints:
m == isInfected.length
n == isInfected[i].length
1 <= m, n <= 50
isInfected[i][j] is either 0 or 1.
There is always a contiguous viral region throughout the described process that will infect strictly more uncontaminated squares in the next round.
| Hard | [
"array",
"depth-first-search",
"breadth-first-search",
"matrix",
"simulation"
] | [
"const containVirus = function (grid) {\n let ans = 0\n while (true) {\n const walls = model(grid)\n if (walls === 0) break\n ans += walls\n }\n return ans\n function model(grid) {\n const m = grid.length,\n n = grid[0].length\n const virus = [],\n toInfect = []\n const visited = Array.from({ length: m }, () => Array(n).fill(0))\n const walls = []\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 1 && visited[i][j] === 0) {\n virus.push(new Set())\n toInfect.push(new Set())\n walls.push([0])\n dfs(\n grid,\n visited,\n virus[virus.length - 1],\n toInfect[toInfect.length - 1],\n walls[walls.length - 1],\n i,\n j\n )\n }\n }\n }\n let maxArea = 0,\n idx = -1\n for (let i = 0; i < toInfect.length; i++) {\n if (toInfect[i].size > maxArea) {\n maxArea = toInfect[i].size\n idx = i\n }\n }\n if (idx === -1) return 0\n for (let i = 0; i < toInfect.length; i++) {\n if (i !== idx) {\n for (let key of toInfect[i]) grid[(key / n) >> 0][key % n] = 1\n } else {\n for (let key of virus[i]) grid[(key / n) >> 0][key % n] = -1\n }\n }\n return walls[idx][0]\n }\n function dfs(grid, visited, virus, toInfect, wall, row, col) {\n const m = grid.length,\n n = grid[0].length\n if (row < 0 || row >= m || col < 0 || col >= n || visited[row][col] === 1)\n return\n if (grid[row][col] === 1) {\n visited[row][col] = 1\n virus.add(row * n + col)\n const dir = [0, -1, 0, 1, 0]\n for (let i = 0; i < 4; i++)\n dfs(\n grid,\n visited,\n virus,\n toInfect,\n wall,\n row + dir[i],\n col + dir[i + 1]\n )\n } else if (grid[row][col] === 0) {\n wall[0]++\n toInfect.add(row * n + col)\n }\n }\n}",
"const containVirus = (grid) => {\n const m = grid.length;\n const n = grid[0].length;\n let ans = 0;\n while (true) {\n // list of regions can spread virus\n const regions = [];\n const visited = Array.from({ length: m }, () => Array(n).fill(false));\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 1 && !visited[i][j]) {\n const region = new Region();\n dfs(grid, i, j, region, visited);\n if (region.uninfected.size > 0) regions.push(region);\n }\n }\n }\n\n if (regions.length === 0) break;\n regions.sort((a, b) => a.uninfected.size - b.uninfected.size);\n let idx = -1, wall = -Infinity\n for(let i = 0, len = regions.length; i < len; i++) {\n if(regions[i].uninfected.size > wall) {\n wall = regions[i].uninfected.size\n idx = i\n }\n }\n const mostToBeInfected = regions[idx]\n ans += mostToBeInfected.wallNeeded\n regions.splice(idx, 1)\n for (let x of mostToBeInfected.infected) {\n let i = (x / n) >> 0,\n j = x % n;\n grid[i][j] = 2;\n }\n\n for (let region of regions) {\n for (let x of region.uninfected) {\n let i = (x / n) >> 0,\n j = x % n;\n grid[i][j] = 1;\n }\n }\n }\n\n return ans;\n function dfs(grid, i, j, region, visited) {\n if (i < 0 || i == m || j < 0 || j == n) return;\n \n if (grid[i][j] === 1 && !visited[i][j]) {\n visited[i][j] = true;\n region.infected.add(i * n + j);\n dfs(grid, i - 1, j, region, visited);\n dfs(grid, i + 1, j, region, visited);\n dfs(grid, i, j - 1, region, visited);\n dfs(grid, i, j + 1, region, visited);\n } else if (grid[i][j] === 0) {\n region.wallNeeded += 1;\n region.uninfected.add(i * n + j);\n }\n }\n};\nclass Region {\n constructor() {\n this.wallNeeded = 0;\n this.infected = new Set();\n this.uninfected = new Set();\n }\n}",
"const containVirus = function (grid) {\n const infected = 1\n const healthy = 0\n const quarantined = 2\n const directions = [\n [1, 0],\n [-1, 0],\n [0, 1],\n [0, -1],\n ]\n const mod = 100\n const encode = (row, col) => row + col * mod\n const decode = (num) => [num % mod, Math.floor(num / mod)]\n const disjointSet = {}\n for (let row = 0; row < grid.length; row++) {\n for (let col = 0; col < grid[row].length; col++) {\n const coord = encode(row, col)\n disjointSet[coord] = coord\n if (grid[row][col] === 0) continue\n if (grid[row][col - 1] === 1) union(coord, encode(row, col - 1))\n if (row > 0 && grid[row - 1][col] === 1)\n union(coord, encode(row - 1, col))\n }\n }\n let numWalls = 0\n while (true) {\n const impact = quarantineAndContaminate()\n if (impact === 0) return numWalls\n numWalls += impact\n spreadVirus()\n }\n function find(coord) {\n return (disjointSet[coord] =\n disjointSet[coord] === coord ? coord : find(disjointSet[coord]))\n }\n function union(coord, toCoord) {\n return (disjointSet[find(coord)] = find(toCoord))\n }\n function quarantineAndContaminate() {\n const impact = new Map()\n for (let row = 0; row < grid.length; row++) {\n for (let col = 0; col < grid[row].length; col++) {\n if (grid[row][col] !== infected) continue\n const root = find(encode(row, col))\n if (!impact.has(root)) impact.set(root, new Set())\n for (let [down, right] of directions) {\n if (grid[row + down] && grid[row + down][col + right] === healthy) {\n impact.get(root).add(encode(row + down, col + right))\n }\n }\n }\n }\n let impactedCoords = new Set()\n let root = null\n for (let [node, coords] of impact) {\n if (impactedCoords.size < coords.size) {\n impactedCoords = coords\n root = node\n }\n }\n if (impactedCoords.size === 0) return 0\n return quarantine(...decode(root))\n }\n function quarantine(row, col) {\n if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length)\n return 0\n if (grid[row][col] === 2) return 0\n if (grid[row][col] === 0) return 1\n let totalWalls = 0\n grid[row][col] = 2\n for (let [down, right] of directions) {\n totalWalls += quarantine(row + down, col + right)\n }\n return totalWalls\n }\n function spreadVirus() {\n const infectedCoords = new Set()\n for (let row = 0; row < grid.length; row++) {\n for (let col = 0; col < grid[row].length; col++) {\n if (grid[row][col] !== healthy) continue\n for (let [down, right] of directions) {\n if (grid[row + down] && grid[row + down][col + right] === infected) {\n infectedCoords.add(encode(row, col))\n }\n }\n }\n }\n for (let coord of infectedCoords) {\n const [row, col] = decode(coord)\n grid[row][col] = 1\n for (let [down, right] of directions) {\n if (grid[row + down] && grid[row + down][col + right] === 1) {\n union(coord, encode(row + down, col + right))\n }\n }\n }\n }\n}"
] |
|
752 | open-the-lock | [
"We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`."
] | /**
* @param {string[]} deadends
* @param {string} target
* @return {number}
*/
var openLock = function(deadends, target) {
}; | You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.
The lock initially starts at '0000', a string representing the state of the 4 wheels.
You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
Example 1:
Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
Output: 6
Explanation:
A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end "0102".
Example 2:
Input: deadends = ["8888"], target = "0009"
Output: 1
Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009".
Example 3:
Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
Output: -1
Explanation: We cannot reach the target without getting stuck.
Constraints:
1 <= deadends.length <= 500
deadends[i].length == 4
target.length == 4
target will not be in the list deadends.
target and deadends[i] consist of digits only.
| Medium | [
"array",
"hash-table",
"string",
"breadth-first-search"
] | [
"const openLock = function(deadends, target, count = 0) {\n let deadSet = new Set(deadends);\n let visited = new Set();\n if (deadSet.has(\"0000\")) {\n return -1;\n }\n\n let q = [];\n q.push(\"0000\");\n visited.add(\"0000\");\n\n let steps = 0;\n while (q.length > 0) {\n let len = q.length;\n\n for (let j = 0; j < len; j++) {\n let cur = q.shift();\n\n for (let i = 0; i < 4; i++) {\n let slot = parseInt(cur[i]);\n let before = cur.substr(0, i);\n let after = cur.substr(i + 1);\n\n let left = (10 + slot - 1) % 10;\n let leftCode = before + left + after;\n if (!visited.has(leftCode) && !deadSet.has(leftCode)) {\n if (leftCode === target) {\n return steps + 1;\n }\n\n visited.add(leftCode);\n q.push(leftCode);\n }\n\n let right = (10 + slot + 1) % 10;\n let rightCode = before + right + after;\n if (!visited.has(rightCode) && !deadSet.has(rightCode)) {\n if (rightCode === target) {\n return steps + 1;\n }\n\n visited.add(rightCode);\n q.push(rightCode);\n }\n }\n }\n steps++;\n }\n\n return -1;\n};"
] |
|
753 | cracking-the-safe | [
"We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)\r\n\r\nWe should visit each node in \"post-order\" so as to not get stuck in the graph prematurely."
] | /**
* @param {number} n
* @param {number} k
* @return {string}
*/
var crackSafe = function(n, k) {
}; | There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1].
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit.
For example, the correct password is "345" and you enter in "012345":
After typing 0, the most recent 3 digits is "0", which is incorrect.
After typing 1, the most recent 3 digits is "01", which is incorrect.
After typing 2, the most recent 3 digits is "012", which is incorrect.
After typing 3, the most recent 3 digits is "123", which is incorrect.
After typing 4, the most recent 3 digits is "234", which is incorrect.
After typing 5, the most recent 3 digits is "345", which is correct and the safe unlocks.
Return any string of minimum length that will unlock the safe at some point of entering it.
Example 1:
Input: n = 1, k = 2
Output: "10"
Explanation: The password is a single digit, so enter each digit. "01" would also unlock the safe.
Example 2:
Input: n = 2, k = 2
Output: "01100"
Explanation: For each possible password:
- "00" is typed in starting from the 4th digit.
- "01" is typed in starting from the 1st digit.
- "10" is typed in starting from the 3rd digit.
- "11" is typed in starting from the 2nd digit.
Thus "01100" will unlock the safe. "10011", and "11001" would also unlock the safe.
Constraints:
1 <= n <= 4
1 <= k <= 10
1 <= kn <= 4096
| Hard | [
"depth-first-search",
"graph",
"eulerian-circuit"
] | null | [] |
754 | reach-a-number | [] | /**
* @param {number} target
* @return {number}
*/
var reachNumber = function(target) {
}; | You are standing at position 0 on an infinite number line. There is a destination at position target.
You can make some number of moves numMoves so that:
On each move, you can either go left or right.
During the ith move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction.
Given the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to reach the destination.
Example 1:
Input: target = 2
Output: 3
Explanation:
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
Example 2:
Input: target = 3
Output: 2
Explanation:
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
Constraints:
-109 <= target <= 109
target != 0
| Medium | [
"math",
"binary-search"
] | [
"const reachNumber = function(target) {\n const tar = Math.abs(target);\n let step = 0;\n let sum = 0;\n while (sum < tar) {\n step++;\n sum += step;\n }\n while ((sum - tar) % 2 !== 0) {\n step++;\n sum += step;\n }\n return step;\n};"
] |
|
756 | pyramid-transition-matrix | [] | /**
* @param {string} bottom
* @param {string[]} allowed
* @return {boolean}
*/
var pyramidTransition = function(bottom, allowed) {
}; | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given as a list of three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.
For example, "ABC" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from "BAC" where 'B' is on the left bottom and 'A' is on the right bottom.
You start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid.
Given bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise.
Example 1:
Input: bottom = "BCD", allowed = ["BCC","CDE","CEA","FFF"]
Output: true
Explanation: The allowed triangular patterns are shown on the right.
Starting from the bottom (level 3), we can build "CE" on level 2 and then build "A" on level 1.
There are three triangular patterns in the pyramid, which are "BCC", "CDE", and "CEA". All are allowed.
Example 2:
Input: bottom = "AAAA", allowed = ["AAB","AAC","BCD","BBE","DEF"]
Output: false
Explanation: The allowed triangular patterns are shown on the right.
Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.
Constraints:
2 <= bottom.length <= 6
0 <= allowed.length <= 216
allowed[i].length == 3
The letters in all input strings are from the set {'A', 'B', 'C', 'D', 'E', 'F'}.
All the values of allowed are unique.
| Medium | [
"bit-manipulation",
"depth-first-search",
"breadth-first-search"
] | [
"const pyramidTransition = function (bottom, allowed) {\n const m = new Map()\n for (let e of allowed) {\n const p = e.slice(0, 2)\n if (!m.has(p)) m.set(p, new Set())\n m.get(p).add(e[2])\n }\n return dfs(bottom, '', m, 0)\n}\n\nfunction dfs(row, next, m, i) {\n if (row.length === 1) return true\n if (next.length + 1 === row.length) return dfs(next, '', m, 0)\n for (let c of m.get(row.slice(i, i + 2)) || new Set())\n if (dfs(row, next + c, m, i + 1)) return true\n return false\n}"
] |
|
757 | set-intersection-size-at-least-two | [] | /**
* @param {number[][]} intervals
* @return {number}
*/
var intersectionSizeTwo = function(intervals) {
}; | You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively.
A containing set is an array nums where each interval from intervals has at least two integers in nums.
For example, if intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [2,3,4,8,9] are containing sets.
Return the minimum possible size of a containing set.
Example 1:
Input: intervals = [[1,3],[3,7],[8,9]]
Output: 5
Explanation: let nums = [2, 3, 4, 8, 9].
It can be shown that there cannot be any containing array of size 4.
Example 2:
Input: intervals = [[1,3],[1,4],[2,5],[3,5]]
Output: 3
Explanation: let nums = [2, 3, 4].
It can be shown that there cannot be any containing array of size 2.
Example 3:
Input: intervals = [[1,2],[2,3],[2,4],[4,5]]
Output: 5
Explanation: let nums = [1, 2, 3, 4, 5].
It can be shown that there cannot be any containing array of size 4.
Constraints:
1 <= intervals.length <= 3000
intervals[i].length == 2
0 <= starti < endi <= 108
| Hard | [
"array",
"greedy",
"sorting"
] | [
"const intersectionSizeTwo = function(intervals) {\n let highest = Number.NEGATIVE_INFINITY;\n let secondHighest = Number.NEGATIVE_INFINITY;\n return intervals\n .sort((a, b) => a[1] - b[1])\n .reduce((sum, interval) => {\n if (interval[0] > secondHighest) {\n secondHighest = interval[1];\n highest = interval[1] - 1;\n return sum + 2;\n }\n else if (interval[0] > highest) {\n highest = secondHighest;\n secondHighest = interval[1];\n return sum + 1;\n }\n return sum;\n }, 0);\n};",
"const intersectionSizeTwo = function(intervals) {\n intervals.sort((a, b) => a[1] - b[1]);\n\n let n = intervals.length;\n if (n === 0) return 0;\n\n let count = 2;\n let last = intervals[0][1];\n let sec_last = intervals[0][1] - 1;\n\n for (let i = 1; i < n; i++) {\n if (intervals[i][0] <= sec_last) continue;\n else if (intervals[i][0] <= last) {\n sec_last = last;\n last = intervals[i][1];\n count++;\n } else {\n last = intervals[i][1];\n sec_last = intervals[i][1] - 1;\n count += 2;\n }\n }\n return count;\n};",
"const intersectionSizeTwo = function (intervals) {\n if (intervals.length === 1) return 2\n intervals.sort((a, b) => (a[1] !== b[1] ? a[1] - b[1] : b[0] - a[0]))\n let right = intervals[0][1]\n let left = right - 1\n let result = 2\n for (let i = 1, len = intervals.length; i < len; i++) {\n const curr = intervals[i]\n if (curr[0] <= right && curr[0] > left) {\n result++\n left = right\n right = curr[1]\n } else if (curr[0] > right) {\n result += 2\n left = curr[1] - 1\n right = curr[1]\n }\n }\n\n return result\n}"
] |
|
761 | special-binary-string | [
"Draw a line from (x, y) to (x+1, y+1) if we see a \"1\", else to (x+1, y-1).\r\nA special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached.\r\nCall a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached.\r\nIf F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is:\r\nreverse_sorted(F(M1), F(M2), ..., F(Mk)).\r\nHowever, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100."
] | /**
* @param {string} s
* @return {string}
*/
var makeLargestSpecial = function(s) {
}; | Special binary strings are binary strings with the following two properties:
The number of 0's is equal to the number of 1's.
Every prefix of the binary string has at least as many 1's as 0's.
You are given a special binary string s.
A move consists of choosing two consecutive, non-empty, special substrings of s, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.
Return the lexicographically largest resulting string possible after applying the mentioned operations on the string.
Example 1:
Input: s = "11011000"
Output: "11100100"
Explanation: The strings "10" [occuring at s[1]] and "1100" [at s[3]] are swapped.
This is the lexicographically largest string possible after some number of swaps.
Example 2:
Input: s = "10"
Output: "10"
Constraints:
1 <= s.length <= 50
s[i] is either '0' or '1'.
s is a special binary string.
| Hard | [
"string",
"recursion"
] | [
"const makeLargestSpecial = function(S) {\n let count = 0, i = 0\n const res = []\n for(let j = 0, len = S.length; i < len; j++) {\n if(S.charAt(j) === '1') count++\n else count--\n if(count === 0) {\n res.push('1' + makeLargestSpecial(S.substring(i + 1, j)) + '0')\n i = j + 1\n }\n }\n return res.sort().reverse().join('')\n};"
] |
|
762 | prime-number-of-set-bits-in-binary-representation | [
"Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19."
] | /**
* @param {number} left
* @param {number} right
* @return {number}
*/
var countPrimeSetBits = function(left, right) {
}; | Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation.
Recall that the number of set bits an integer has is the number of 1's present when written in binary.
For example, 21 written in binary is 10101, which has 3 set bits.
Example 1:
Input: left = 6, right = 10
Output: 4
Explanation:
6 -> 110 (2 set bits, 2 is prime)
7 -> 111 (3 set bits, 3 is prime)
8 -> 1000 (1 set bit, 1 is not prime)
9 -> 1001 (2 set bits, 2 is prime)
10 -> 1010 (2 set bits, 2 is prime)
4 numbers have a prime number of set bits.
Example 2:
Input: left = 10, right = 15
Output: 5
Explanation:
10 -> 1010 (2 set bits, 2 is prime)
11 -> 1011 (3 set bits, 3 is prime)
12 -> 1100 (2 set bits, 2 is prime)
13 -> 1101 (3 set bits, 3 is prime)
14 -> 1110 (3 set bits, 3 is prime)
15 -> 1111 (4 set bits, 4 is not prime)
5 numbers have a prime number of set bits.
Constraints:
1 <= left <= right <= 106
0 <= right - left <= 104
| Easy | [
"math",
"bit-manipulation"
] | [
"const countPrimeSetBits = function(L, R) {\n let res = 0;\n for (let i = L; i <= R; i++) {\n if (chkPrime(i)) {\n res += 1;\n }\n }\n return res;\n};\n\nfunction chkPrime(num) {\n const str = bin(num);\n const snum = setNum(str);\n return isPrime(snum);\n}\n\nfunction setNum(str) {\n let num = 0;\n for (let i = 0; i < str.length; i++) {\n if (str.charAt(i) === \"1\") {\n num += 1;\n }\n }\n return num;\n}\n\nfunction bin(num) {\n return (num >>> 0).toString(2);\n}\nfunction isPrime(num) {\n for (let i = 2; i < num; i++) {\n if (num % i === 0) return false;\n }\n return num !== 1;\n}"
] |
|
763 | partition-labels | [
"Try to greedily choose the smallest partition that includes the first letter. If you have something like \"abaccbdeffed\", then you might need to add b. You can use an map like \"last['b'] = 5\" to help you expand the width of your partition."
] | /**
* @param {string} s
* @return {number[]}
*/
var partitionLabels = function(s) {
}; | You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
Return a list of integers representing the size of these parts.
Example 1:
Input: s = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.
Example 2:
Input: s = "eccbbbbdec"
Output: [10]
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters.
| Medium | [
"hash-table",
"two-pointers",
"string",
"greedy"
] | [
"const partitionLabels = function (S) {\n if (S == null || S.length === 0) {\n return null\n }\n const list = []\n // record the last index of the each char\n const map = new Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n for (let i = 0, len = S.length; i < len; i++) {\n map[S.charCodeAt(i) - a] = i\n }\n // record the end index of the current sub string\n let last = 0\n let start = 0\n for (let i = 0, len = S.length; i < len; i++) {\n last = Math.max(last, map[S.charCodeAt(i) - a])\n if (last === i) {\n list.push(last - start + 1)\n start = last + 1\n }\n }\n return list\n}"
] |
|
764 | largest-plus-sign | [
"For each direction such as \"left\", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc."
] | /**
* @param {number} n
* @param {number[][]} mines
* @return {number}
*/
var orderOfLargestPlusSign = function(n, mines) {
}; | You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0.
Return the order of the largest axis-aligned plus sign of 1's contained in grid. If there is none, return 0.
An axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1's.
Example 1:
Input: n = 5, mines = [[4,2]]
Output: 2
Explanation: In the above grid, the largest plus sign can only be of order 2. One of them is shown.
Example 2:
Input: n = 1, mines = [[0,0]]
Output: 0
Explanation: There is no plus sign, so return 0.
Constraints:
1 <= n <= 500
1 <= mines.length <= 5000
0 <= xi, yi < n
All the pairs (xi, yi) are unique.
| Medium | [
"array",
"dynamic-programming"
] | [
"const orderOfLargestPlusSign = function (N, mines) {\n const dp = [...Array(N)].map((_) => Array(N).fill(N))\n mines.map((m) => {\n dp[m[0]][m[1]] = 0\n })\n for (let i = 0; i < N; i++) {\n for (let j = 0, k = N - 1, l = (r = u = d = 0); j < N; j++, k--) {\n dp[i][j] = Math.min(dp[i][j], (l = dp[i][j] == 0 ? 0 : l + 1))\n dp[i][k] = Math.min(dp[i][k], (r = dp[i][k] == 0 ? 0 : r + 1))\n dp[j][i] = Math.min(dp[j][i], (d = dp[j][i] == 0 ? 0 : d + 1))\n dp[k][i] = Math.min(dp[k][i], (u = dp[k][i] == 0 ? 0 : u + 1))\n }\n }\n let max = 0\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < N; j++) {\n max = Math.max(dp[i][j], max)\n }\n }\n return max\n}"
] |
|
765 | couples-holding-hands | [
"Say there are N two-seat couches. For each couple, draw an edge from the couch of one partner to the couch of the other partner."
] | /**
* @param {number[]} row
* @return {number}
*/
var minSwapsCouples = function(row) {
}; | There are n couples sitting in 2n seats arranged in a row and want to hold hands.
The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1).
Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.
Example 1:
Input: row = [0,2,1,3]
Output: 1
Explanation: We only need to swap the second (row[1]) and third (row[2]) person.
Example 2:
Input: row = [3,2,0,1]
Output: 0
Explanation: All couples are already seated side by side.
Constraints:
2n == row.length
2 <= n <= 30
n is even.
0 <= row[i] < 2n
All the elements of row are unique.
| Hard | [
"greedy",
"depth-first-search",
"breadth-first-search",
"union-find",
"graph"
] | [
"const minSwapsCouples = function (row) {\n let res = 0,\n N = row.length\n const ptn = new Array(N).fill(0)\n const pos = new Array(N).fill(0)\n for (let i = 0; i < N; i++) {\n ptn[i] = i % 2 === 0 ? i + 1 : i - 1\n pos[row[i]] = i\n }\n for (let i = 0; i < N; i++) {\n for (let j = ptn[pos[ptn[row[i]]]]; i !== j; j = ptn[pos[ptn[row[i]]]]) {\n swap(row, i, j)\n swap(pos, row[i], row[j])\n res++\n }\n }\n return res\n}\n\nfunction swap(arr, i, j) {\n ;[arr[i], arr[j]] = [arr[j], arr[i]]\n}",
"const minSwapsCouples = function (row) {\n const parents = Array.from({ length: row.length / 2 }, (_, i) => i)\n const positions = new Map()\n for (let i = 0; i < row.length / 2; i++) {\n const left = Math.floor(row[i * 2] / 2)\n const right = Math.floor(row[i * 2 + 1] / 2)\n if (positions.has(left)) {\n union(i, positions.get(left))\n } else {\n positions.set(left, i)\n }\n if (positions.has(right)) {\n union(i, positions.get(right))\n } else {\n positions.set(right, i)\n }\n }\n\n const uniqueRoots = new Set()\n for (const parent of parents) {\n uniqueRoots.add(find(parent))\n }\n return parents.length - uniqueRoots.size\n\n function union(a, b) {\n const aRoot = find(a)\n const bRoot = find(b)\n parents[aRoot] = bRoot\n }\n function root(x) {\n while (x !== parents[x]) {\n parents[x] = parents[parents[x]]\n x = parents[x]\n }\n return x\n }\n function find(node) {\n return root(node)\n }\n}",
"const minSwapsCouples = function (row) {\n let res = 0\n const n = row.length\n const ptn = Array(n).fill(0), pos = Array(n).fill(0)\n \n for(let i = 0; i < n; i++) {\n ptn[i] = (i % 2 === 0 ? i + 1 : i - 1)\n pos[row[i]] = i\n }\n\n for (let i = 0; i < n ;i++) {\n for (let j = ptn[pos[ptn[row[i]]]]; i != j; j = ptn[pos[ptn[row[i]]]]) {\n\t\t\tswap(row, i, j);\n\t\t\tswap(pos, row[i], row[j]);\n\t\t\tres++;\n\t\t}\n }\n \n return res\n\n function swap(arr, i, j) {\n const val = arr[i]\n arr[i] = arr[j]\n arr[j] = val\n }\n}"
] |
|
766 | toeplitz-matrix | [
"Check whether each value is equal to the value of it's top-left neighbor."
] | /**
* @param {number[][]} matrix
* @return {boolean}
*/
var isToeplitzMatrix = function(matrix) {
}; | Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.
Example 1:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.
Example 2:
Input: matrix = [[1,2],[2,2]]
Output: false
Explanation:
The diagonal "[1, 2]" has different elements.
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 20
0 <= matrix[i][j] <= 99
Follow up:
What if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
What if the matrix is so large that you can only load up a partial row into the memory at once?
| Easy | [
"array",
"matrix"
] | [
"const isToeplitzMatrix = function(matrix) {\n for (let r = 0; r < matrix.length; r++) {\n for (let c = 0; c < matrix[0].length; c++) {\n if (r > 0 && c > 0 && matrix[r - 1][c - 1] !== matrix[r][c]) {\n return false;\n }\n }\n }\n return true;\n};\n\nconsole.log(isToeplitzMatrix([[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]));\n\nconsole.log(isToeplitzMatrix([[1, 2], [2, 2]]));"
] |
|
767 | reorganize-string | [
"Alternate placing the most common letters."
] | /**
* @param {string} s
* @return {string}
*/
var reorganizeString = function(s) {
}; | Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
Return any possible rearrangement of s or return "" if not possible.
Example 1:
Input: s = "aab"
Output: "aba"
Example 2:
Input: s = "aaab"
Output: ""
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters.
| Medium | [
"hash-table",
"string",
"greedy",
"sorting",
"heap-priority-queue",
"counting"
] | [
"const reorganizeString = function (s) {\n const freq = Array(26).fill(0)\n const a = 'a'.charCodeAt(0), n = s.length\n for(const e of s) {\n freq[e.charCodeAt(0) - a]++\n }\n let max = 0, maxIdx = 0\n for(let i = 0; i < 26; i++) {\n if(freq[i] > max) {\n max = freq[i]\n maxIdx = i\n }\n }\n\n if(max > (n + 1) / 2) return ''\n\n const res = Array(n)\n\n let idx = 0\n while(freq[maxIdx]) {\n res[idx] = String.fromCharCode(a + maxIdx)\n idx += 2\n freq[maxIdx]--\n }\n\n for(let i = 0; i < 26; i++) {\n while(freq[i]) {\n if(idx >= n) idx = 1\n res[idx] = String.fromCharCode(i + a)\n idx += 2\n freq[i]--\n }\n }\n\n return res.join('')\n}",
"const reorganizeString = function(S) {\n if (!S || S.length <= 1) {\n return S;\n }\n const freqs = Array(26).fill(0);\n const acode = 'a'.charCodeAt(0);\n for (let i = 0, n = S.length; i < n; i++) {\n const index = S.charCodeAt(i) - acode;\n freqs[index]++;\n if (freqs[index] > Math.ceil(n / 2)) {\n return '';\n }\n }\n const list = [];\n for (let i = 0, n = S.length; i < 26; i++) {\n if (freqs[i] === 0) {\n continue;\n }\n list.push({ch: String.fromCharCode(i + acode), freq: freqs[i]});\n }\n list.sort((l1, l2) => l2.freq - l1.freq);\n const parts = [];\n for (let i = 0, n = list[0].freq; i < n; i++) {\n parts.push(list[0].ch);\n }\n let idx = 0;\n for (let i = 1, n = list.length; i < n; i++) {\n for (let j = 0, m = list[i].freq; j < m; j++) {\n idx %= list[0].freq;\n parts[idx++] += list[i].ch;\n }\n }\n return parts.join('');\n};",
"const reorganizeString = function(s) {\n const arr = Array(26).fill(0), a = 'a'.charCodeAt(0)\n for(let ch of s) arr[ch.charCodeAt(0) - a]++\n let max = 0, idx = -1\n for(let i = 0; i < 26; i++) {\n if(arr[i] > max) {\n max = arr[i]\n idx = i\n }\n }\n const n = s.length\n const res = Array(n)\n if(max > (n + 1) / 2) return ''\n\n let i = 0\n while(arr[idx] > 0) {\n res[i] = String.fromCharCode(a + idx)\n i += 2\n arr[idx]--\n }\n \n for(let j = 0; j < 26; j++) {\n while(arr[j]) {\n if(i >= n) i = 1\n res[i] = String.fromCharCode(a + j)\n i += 2\n arr[j]--\n }\n }\n return res.join('')\n};"
] |
|
768 | max-chunks-to-make-sorted-ii | [
"Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk."
] | /**
* @param {number[]} arr
* @return {number}
*/
var maxChunksToSorted = function(arr) {
}; | You are given an integer array arr.
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
Example 1:
Input: arr = [5,4,3,2,1]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
Example 2:
Input: arr = [2,1,3,4,4]
Output: 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
Constraints:
1 <= arr.length <= 2000
0 <= arr[i] <= 108
| Hard | [
"array",
"stack",
"greedy",
"sorting",
"monotonic-stack"
] | [
"const maxChunksToSorted = function(arr) {\n const clonedArr = arr.slice(0);\n let sum1 = 0;\n let sum2 = 0;\n let res = 0;\n clonedArr.sort((a, b) => a - b);\n for (let i = 0; i < arr.length; i++) {\n sum1 += arr[i];\n sum2 += clonedArr[i];\n if (sum1 === sum2) res += 1;\n }\n return res;\n};"
] |
|
769 | max-chunks-to-make-sorted | [
"The first chunk can be found as the smallest k for which A[:k+1] == [0, 1, 2, ...k]; then we repeat this process."
] | /**
* @param {number[]} arr
* @return {number}
*/
var maxChunksToSorted = function(arr) {
}; | You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
Example 1:
Input: arr = [4,3,2,1,0]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.
Example 2:
Input: arr = [1,0,2,3,4]
Output: 4
Explanation:
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
Constraints:
n == arr.length
1 <= n <= 10
0 <= arr[i] < n
All the elements of arr are unique.
| Medium | [
"array",
"stack",
"greedy",
"sorting",
"monotonic-stack"
] | [
"const maxChunksToSorted = function(arr) {\n let res = 0;\n let max = 0;\n for (let i = 0; i < arr.length; i++) {\n max = Math.max(max, arr[i]);\n if (max === i) res += 1;\n }\n return res;\n};"
] |
|
770 | basic-calculator-iv | [
"One way is with a Polynomial class. For example,\r\n\r\n* `Poly:add(this, that)` returns the result of `this + that`.\r\n* `Poly:sub(this, that)` returns the result of `this - that`.\r\n* `Poly:mul(this, that)` returns the result of `this * that`.\r\n* `Poly:evaluate(this, evalmap)` returns the polynomial after replacing all free variables with constants as specified by `evalmap`.\r\n* `Poly:toList(this)` returns the polynomial in the correct output format.\r\n\r\n* `Solution::combine(left, right, symbol)` returns the result of applying the binary operator represented by `symbol` to `left` and `right`.\r\n* `Solution::make(expr)` makes a new `Poly` represented by either the constant or free variable specified by `expr`.\r\n* `Solution::parse(expr)` parses an expression into a new `Poly`."
] | /**
* @param {string} expression
* @param {string[]} evalvars
* @param {number[]} evalints
* @return {string[]}
*/
var basicCalculatorIV = function(expression, evalvars, evalints) {
}; | Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as ["-1*a","14"]
An expression alternates chunks and symbols, with a space separating each chunk and symbol.
A chunk is either an expression in parentheses, a variable, or a non-negative integer.
A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like "2x" or "-x".
Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.
For example, expression = "1 + 2 * 3" has an answer of ["7"].
The format of the output is as follows:
For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically.
For example, we would never write a term like "b*a*c", only "a*b*c".
Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
For example, "a*a*b*c" has degree 4.
The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.
An example of a well-formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"].
Terms (including constant terms) with coefficient 0 are not included.
For example, an expression of "0" has an output of [].
Note: You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].
Example 1:
Input: expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
Output: ["-1*a","14"]
Example 2:
Input: expression = "e - 8 + temperature - pressure", evalvars = ["e", "temperature"], evalints = [1, 12]
Output: ["-1*pressure","5"]
Example 3:
Input: expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
Output: ["1*e*e","-64"]
Constraints:
1 <= expression.length <= 250
expression consists of lowercase English letters, digits, '+', '-', '*', '(', ')', ' '.
expression does not contain any leading or trailing spaces.
All the tokens in expression are separated by a single space.
0 <= evalvars.length <= 100
1 <= evalvars[i].length <= 20
evalvars[i] consists of lowercase English letters.
evalints.length == evalvars.length
-100 <= evalints[i] <= 100
| Hard | [
"hash-table",
"math",
"string",
"stack",
"recursion"
] | [
"const basicCalculatorIV = function (expression, evalvars, evalints) {\n // Tokenise and get list of unresolved variable names\n let [variables, it] = (function () {\n let variables = []\n let evalMap = new Map(evalvars.map((name, i) => [name, evalints[i]]))\n let tokens = expression.match(/\\w+|\\d+|\\S/g)\n // Resolve occurrences of eval vars\n for (let i = 0; i < tokens.length; i++) {\n let token = tokens[i]\n if (token[0] >= 'A') {\n let num = evalMap.get(token)\n if (num !== undefined) {\n tokens[i] = num\n } else {\n variables.push(tokens[i])\n }\n }\n }\n return [[...new Set(variables)].sort(), tokens.values()] // array & iterator\n })()\n // Map each unknown variable to a sequential ID:\n let variableMap = new Map(variables.map((name, i) => [name, i]))\n\n // Parse tokens into Polynomial instance, and get output in required format\n return (function parse(sign = 1) {\n function parseTerm(sign = 1) {\n let token = it.next().value\n if (token === '(') return parse(sign)\n let term = new Term(sign)\n if (typeof token === 'string' && token >= 'A') {\n term.setVar(variableMap.get(token))\n } else {\n term.setCoefficient(+token)\n }\n return new Polynomial([term])\n }\n\n let polynomial = new Polynomial()\n let term = parseTerm(sign)\n for (let token; (token = it.next().value) && token !== ')'; ) {\n if (token === '*') {\n term.mul(parseTerm(1))\n } else {\n polynomial.add(term)\n term = parseTerm(token === '+' ? sign : -sign)\n }\n }\n return polynomial.add(term)\n })().output(variables)\n}\nclass Term {\n constructor(coefficient, variables = [], degree = 0) {\n this.variables = variables\n this.coefficient = coefficient\n this.degree = degree\n }\n setVar(id) {\n while (this.variables.length <= id) this.variables.push(0)\n this.variables[id]++\n this.degree++\n }\n setCoefficient(coefficient) {\n this.coefficient *= coefficient\n }\n clone() {\n return new Term(this.coefficient, [...this.variables], this.degree)\n }\n mul(term) {\n let n = term.variables.length\n while (this.variables.length < n) this.variables.push(0)\n for (let i = 0; i < n; i++) {\n this.variables[i] += term.variables[i]\n }\n this.degree += term.degree\n this.coefficient *= term.coefficient\n return this\n }\n cmp(term) {\n let diff = term.degree - this.degree\n if (diff) return Math.sign(diff)\n for (let i = 0; i < this.variables.length; i++) {\n diff = term.variables[i] - this.variables[i]\n if (diff) return Math.sign(diff)\n }\n return 0\n }\n format(variableNames) {\n return !this.coefficient\n ? ''\n : this.coefficient +\n this.variables.map((count, i) =>\n ('*' + variableNames[i]).repeat(count)\n ).join``\n }\n}\n\nclass Polynomial {\n constructor(terms = []) {\n this.terms = terms\n }\n addTerm(term) {\n let terms = this.terms\n // binary search\n let low = 0\n let high = terms.length\n while (low < high) {\n let mid = (low + high) >> 1\n let diff = terms[mid].cmp(term)\n if (diff === 0) {\n terms[mid].coefficient += term.coefficient\n return this\n } else if (diff < 0) {\n low = mid + 1\n } else {\n high = mid\n }\n }\n terms.splice(low, 0, term)\n return this\n }\n add(polynomial) {\n for (let term of polynomial.terms) {\n this.addTerm(term)\n }\n return this\n }\n mul(polynomial) {\n let orig = new Polynomial(this.terms)\n this.terms = [] // clear\n for (let term1 of polynomial.terms) {\n for (let term2 of orig.terms) {\n this.addTerm(term1.clone().mul(term2))\n }\n }\n return this\n }\n output(variableNames) {\n return this.terms.map((term) => term.format(variableNames)).filter(Boolean)\n }\n}"
] |
|
771 | jewels-and-stones | [
"For each stone, check if it is a jewel."
] | /**
* @param {string} jewels
* @param {string} stones
* @return {number}
*/
var numJewelsInStones = function(jewels, stones) {
}; | You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so "a" is considered a different type of stone from "A".
Example 1:
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
Example 2:
Input: jewels = "z", stones = "ZZ"
Output: 0
Constraints:
1 <= jewels.length, stones.length <= 50
jewels and stones consist of only English letters.
All the characters of jewels are unique.
| Easy | [
"hash-table",
"string"
] | [
"const numJewelsInStones = function(J, S) {\n if(J == null || J === '' || S == null || S === '') return 0\n const m = new Set(J)\n let res = 0\n for(let e of S) {\n if(m.has(e)) res++\n }\n return res\n};"
] |
|
773 | sliding-puzzle | [
"Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move."
] | /**
* @param {number[][]} board
* @return {number}
*/
var slidingPuzzle = function(board) {
}; | On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.
Example 1:
Input: board = [[1,2,3],[4,0,5]]
Output: 1
Explanation: Swap the 0 and the 5 in one move.
Example 2:
Input: board = [[1,2,3],[5,4,0]]
Output: -1
Explanation: No number of moves will make the board solved.
Example 3:
Input: board = [[4,1,2],[5,0,3]]
Output: 5
Explanation: 5 is the smallest number of moves that solves the board.
An example path:
After move 0: [[4,1,2],[5,0,3]]
After move 1: [[4,1,2],[0,5,3]]
After move 2: [[0,1,2],[4,5,3]]
After move 3: [[1,0,2],[4,5,3]]
After move 4: [[1,2,0],[4,5,3]]
After move 5: [[1,2,3],[4,5,0]]
Constraints:
board.length == 2
board[i].length == 3
0 <= board[i][j] <= 5
Each value board[i][j] is unique.
| Hard | [
"array",
"breadth-first-search",
"matrix"
] | [
"const slidingPuzzle = function(board) {\n const target = \"123450\";\n let start = \"\";\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[0].length; j++) {\n start += board[i][j];\n }\n }\n const visited = {};\n // all the positions 0 can be swapped to\n const dirs = [[1, 3], [0, 2, 4], [1, 5], [0, 4], [1, 3, 5], [2, 4]];\n const queue = [];\n queue.push(start);\n visited[start] = true;\n let res = 0;\n while (queue.length !== 0) {\n // level count, has to use size control here, otherwise not needed\n let size = queue.length;\n for (let i = 0; i < size; i++) {\n let cur = queue.shift();\n if (cur === target) {\n return res;\n }\n let zero = cur.indexOf(\"0\");\n // swap if possible\n for (let dir of dirs[zero]) {\n let next = swap(cur, zero, dir);\n if (visited.hasOwnProperty(next)) {\n continue;\n }\n visited[next] = true;\n queue.push(next);\n }\n }\n res++;\n }\n return -1;\n};\n\nfunction swap(str, i, j) {\n const arr = str.split(\"\");\n const ic = str[i];\n const jc = str[j];\n arr.splice(i, 1, jc);\n arr.splice(j, 1, ic);\n return arr.join(\"\");\n}"
] |
|
775 | global-and-local-inversions | [
"Where can the 0 be placed in an ideal permutation? What about the 1?"
] | /**
* @param {number[]} nums
* @return {boolean}
*/
var isIdealPermutation = function(nums) {
}; | You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1].
The number of global inversions is the number of the different pairs (i, j) where:
0 <= i < j < n
nums[i] > nums[j]
The number of local inversions is the number of indices i where:
0 <= i < n - 1
nums[i] > nums[i + 1]
Return true if the number of global inversions is equal to the number of local inversions.
Example 1:
Input: nums = [1,0,2]
Output: true
Explanation: There is 1 global inversion and 1 local inversion.
Example 2:
Input: nums = [1,2,0]
Output: false
Explanation: There are 2 global inversions and 1 local inversion.
Constraints:
n == nums.length
1 <= n <= 105
0 <= nums[i] < n
All the integers of nums are unique.
nums is a permutation of all the numbers in the range [0, n - 1].
| Medium | [
"array",
"math"
] | [
"const isIdealPermutation = function(A) {\n if(A.length === 1 || A.length === 2) return true\n let max = A[0]\n for(let i = 0, len = A.length; i < len - 2; i++) {\n max = Math.max(max, A[i])\n if(max > A[i + 2]) return false\n }\n return true;\n};",
"const isIdealPermutation = function(A) {\n if(A.length === 1 || A.length === 2) return true\n for(let i = 0, len = A.length; i < len; i++) {\n if(Math.abs(A[i] - i) > 1) return false\n }\n return true;\n};"
] |
|
777 | swap-adjacent-in-lr-string | [
"Think of the L and R's as people on a horizontal line, where X is a space. The people can't cross each other, and also you can't go from XRX to RXX."
] | /**
* @param {string} start
* @param {string} end
* @return {boolean}
*/
var canTransform = function(start, end) {
}; | In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.
Example 1:
Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: true
Explanation: We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX
Example 2:
Input: start = "X", end = "L"
Output: false
Constraints:
1 <= start.length <= 104
start.length == end.length
Both start and end will only consist of characters in 'L', 'R', and 'X'.
| Medium | [
"two-pointers",
"string"
] | [
"const canTransform = function(start, end) {\n let r = 0, l = 0;\n for (let i = 0; i < start.length; i++){\n if (start.charAt(i) === 'R'){ r++; l = 0;}\n if (end.charAt(i) === 'R') { r--; l = 0;}\n if (end.charAt(i) === 'L') { l++; r = 0;}\n if (start.charAt(i) === 'L') { l--; r = 0;}\n if (l < 0 || r < 0) return false;\n }\n\n if (l != 0 || r != 0) return false;\n return true; \n};"
] |
|
778 | swim-in-rising-water | [
"Use either Dijkstra's, or binary search for the best time T for which you can reach the end if you only step on squares at most T."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var swimInWater = function(grid) {
}; | You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).
The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.
Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0).
Example 1:
Input: grid = [[0,2],[1,3]]
Output: 3
Explanation:
At time 0, you are in grid location (0, 0).
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
You cannot reach point (1, 1) until time 3.
When the depth of water is 3, we can swim anywhere inside the grid.
Example 2:
Input: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
Output: 16
Explanation: The final route is shown.
We need to wait until time 16 so that (0, 0) and (4, 4) are connected.
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 50
0 <= grid[i][j] < n2
Each value grid[i][j] is unique.
| Hard | [
"array",
"binary-search",
"depth-first-search",
"breadth-first-search",
"union-find",
"heap-priority-queue",
"matrix"
] | [
"const swimInWater = function(grid) {\n let n = grid.length;\n let low = grid[0][0],\n hi = n * n - 1;\n while (low < hi) {\n let mid = low + Math.floor((hi - low) / 2);\n if (valid(grid, mid)) hi = mid;\n else low = mid + 1;\n }\n return low;\n};\n\nfunction valid(grid, waterHeight) {\n let n = grid.length;\n const visited = Array.from(new Array(n), el => new Array(n).fill(0));\n const dir = [-1, 0, 1, 0, -1];\n return dfs(grid, visited, dir, waterHeight, 0, 0, n);\n}\nfunction dfs(grid, visited, dir, waterHeight, row, col, n) {\n visited[row][col] = 1;\n for (let i = 0; i < 4; ++i) {\n let r = row + dir[i],\n c = col + dir[i + 1];\n if (\n r >= 0 &&\n r < n &&\n c >= 0 &&\n c < n &&\n visited[r][c] == 0 &&\n grid[r][c] <= waterHeight\n ) {\n if (r == n - 1 && c == n - 1) return true;\n if (dfs(grid, visited, dir, waterHeight, r, c, n)) return true;\n }\n }\n return false;\n}",
"const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]];\nconst swimInWater = grid => {\n let time = 0;\n let N = grid.length;\n const visited = new Set();\n while (!visited.has(N * N - 1)) {\n visited.clear();\n dfs(grid, 0, 0, time, visited);\n time++;\n }\n return time - 1;\n};\n\nfunction dfs(grid, i, j, time, visited) {\n if (\n i < 0 ||\n i > grid.length - 1 ||\n j < 0 ||\n j > grid[0].length - 1 ||\n grid[i][j] > time ||\n visited.has(i * grid.length + j)\n )\n return;\n visited.add(i * grid.length + j);\n for (let dir of dirs) {\n dfs(grid, i + dir[0], j + dir[1], time, visited);\n }\n}",
"class UnionFind {\n constructor(N) {\n this.id = [];\n for (let i = 0; i < N; i++) {\n this.id[i] = i;\n }\n }\n\n root(i) {\n while (i != this.id[i]) {\n this.id[i] = this.id[this.id[i]];\n i = this.id[i];\n }\n return i;\n }\n isConnected(p, q) {\n return this.root(p) === this.root(q);\n }\n union(p, q) {\n if (this.isConnected(p, q)) return;\n this.id[this.root(p)] = this.root(q);\n }\n}\nconst swimInWater = grid => {\n const N = grid.length;\n const uf = new UnionFind(N * N);\n let time = 0;\n while (!uf.isConnected(0, N * N - 1)) {\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < N; j++) {\n if (grid[i][j] > time) continue;\n if (i < N - 1 && grid[i + 1][j] <= time)\n uf.union(i * N + j, i * N + j + N);\n if (j < N - 1 && grid[i][j + 1] <= time)\n uf.union(i * N + j, i * N + j + 1);\n }\n }\n time++;\n }\n return time - 1;\n};"
] |
|
779 | k-th-symbol-in-grammar | [
"Try to represent the current (N, K) in terms of some (N-1, prevK). What is prevK ?"
] | /**
* @param {number} n
* @param {number} k
* @return {number}
*/
var kthGrammar = function(n, k) {
}; | We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.
Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.
Example 1:
Input: n = 1, k = 1
Output: 0
Explanation: row 1: 0
Example 2:
Input: n = 2, k = 1
Output: 0
Explanation:
row 1: 0
row 2: 01
Example 3:
Input: n = 2, k = 2
Output: 1
Explanation:
row 1: 0
row 2: 01
Constraints:
1 <= n <= 30
1 <= k <= 2n - 1
| Medium | [
"math",
"bit-manipulation",
"recursion"
] | [
"const kthGrammar = function(N, K) {\n\tif (N === 1) return 0;\n\tif (K % 2 === 0) return (kthGrammar(N - 1, K / 2) === 0) ? 1 : 0;\n\telse return (kthGrammar(N - 1, (K + 1) / 2) === 0) ? 0 : 1;\n};\n\n\n\n*/"
] |
|
780 | reaching-points | [] | /**
* @param {number} sx
* @param {number} sy
* @param {number} tx
* @param {number} ty
* @return {boolean}
*/
var reachingPoints = function(sx, sy, tx, ty) {
}; | Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise.
The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).
Example 1:
Input: sx = 1, sy = 1, tx = 3, ty = 5
Output: true
Explanation:
One series of moves that transforms the starting point to the target is:
(1, 1) -> (1, 2)
(1, 2) -> (3, 2)
(3, 2) -> (3, 5)
Example 2:
Input: sx = 1, sy = 1, tx = 2, ty = 2
Output: false
Example 3:
Input: sx = 1, sy = 1, tx = 1, ty = 1
Output: true
Constraints:
1 <= sx, sy, tx, ty <= 109
| Hard | [
"math"
] | [
"const reachingPoints = function(sx, sy, tx, ty) {\n while (tx >= sx && ty >= sy) {\n if (tx === ty) break;\n if (tx > ty) {\n if (ty > sy) tx %= ty;\n else return (tx - sx) % ty === 0;\n } else {\n if (tx > sx) ty %= tx;\n else return (ty - sy) % tx === 0;\n }\n }\n return tx === sx && ty === sy;\n};"
] |
|
781 | rabbits-in-forest | [] | /**
* @param {number[]} answers
* @return {number}
*/
var numRabbits = function(answers) {
}; | There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have the same color as you?" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.
Given the array answers, return the minimum number of rabbits that could be in the forest.
Example 1:
Input: answers = [1,1,2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit that answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
Example 2:
Input: answers = [10,10,10]
Output: 11
Constraints:
1 <= answers.length <= 1000
0 <= answers[i] < 1000
| Medium | [
"array",
"hash-table",
"math",
"greedy"
] | null | [] |
782 | transform-to-chessboard | [] | /**
* @param {number[][]} board
* @return {number}
*/
var movesToChessboard = function(board) {
}; | You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.
Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.
A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.
Example 1:
Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
Output: 2
Explanation: One potential sequence of moves is shown.
The first move swaps the first and second column.
The second move swaps the second and third row.
Example 2:
Input: board = [[0,1],[1,0]]
Output: 0
Explanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.
Example 3:
Input: board = [[1,0],[1,0]]
Output: -1
Explanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.
Constraints:
n == board.length
n == board[i].length
2 <= n <= 30
board[i][j] is either 0 or 1.
| Hard | [
"array",
"math",
"bit-manipulation",
"matrix"
] | [
"const movesToChessboard = function (b) {\n let N = b.length,\n rowSum = 0,\n colSum = 0,\n rowSwap = 0,\n colSwap = 0;\n for (let i = 0; i < N; ++i)\n for (let j = 0; j < N; ++j)\n if ((b[0][0] ^ b[i][0] ^ b[0][j] ^ b[i][j]) === 1) return -1;\n for (let i = 0; i < N; ++i) {\n rowSum += b[0][i];\n colSum += b[i][0];\n if (b[i][0] === i % 2) rowSwap++;\n if (b[0][i] === i % 2) colSwap++;\n }\n if (rowSum !== ((N / 2) >> 0) && rowSum !== ((N + 1) / 2)>>0 ) return -1;\n if (colSum !== ((N / 2) >> 0) && colSum !== ((N + 1) / 2)>>0 ) return -1;\n if (N % 2 === 1) {\n if (colSwap % 2 === 1) colSwap = N - colSwap;\n if (rowSwap % 2 === 1) rowSwap = N - rowSwap;\n } else {\n colSwap = Math.min(N - colSwap, colSwap);\n rowSwap = Math.min(N - rowSwap, rowSwap);\n }\n return (colSwap + rowSwap) / 2;\n};"
] |
|
783 | minimum-distance-between-bst-nodes | [] | /**
* 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 minDiffInBST = function(root) {
}; | Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
Example 1:
Input: root = [4,2,6,1,3]
Output: 1
Example 2:
Input: root = [1,0,48,null,null,12,49]
Output: 1
Constraints:
The number of nodes in the tree is in the range [2, 100].
0 <= Node.val <= 105
Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/
| Easy | [
"tree",
"depth-first-search",
"breadth-first-search",
"binary-search-tree",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const minDiffInBST = function(root) {\n if (root === null) return 0;\n let min = Number.MAX_SAFE_INTEGER,\n res = [];\n const bst = (node, res) => {\n if (!node) return;\n bst(node.left, res);\n res.push(node.val);\n bst(node.right, res);\n };\n bst(root, res);\n for (let i = 1; i < res.length; i++) {\n min = Math.min(min, res[i] - res[i - 1]);\n }\n return min;\n};"
] |
784 | letter-case-permutation | [] | /**
* @param {string} s
* @return {string[]}
*/
var letterCasePermutation = function(s) {
}; | Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create. Return the output in any order.
Example 1:
Input: s = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]
Example 2:
Input: s = "3z4"
Output: ["3z4","3Z4"]
Constraints:
1 <= s.length <= 12
s consists of lowercase English letters, uppercase English letters, and digits.
| Medium | [
"string",
"backtracking",
"bit-manipulation"
] | [
"const letterCasePermutation = function(S) {\n let res = []\n backtrack(res, \"\", 0, S)\n return res\n};\n\nconst backtrack = (res, sol, depth, S) => {\n if (depth == S.length) {\n res.push(sol)\n return\n }\n const c = S[depth]\n if (\"1234567890\".indexOf(c) != - 1) {\n backtrack(res, sol+c, depth + 1, S)\n } else {\n backtrack(res, sol+c.toLowerCase(), depth + 1, S)\n backtrack(res, sol+c.toUpperCase(), depth + 1, S)\n }\n}\n\nconsole.log(letterCasePermutation(\"a1b2\")) \nconsole.log(letterCasePermutation(\"3z4\")) \nconsole.log(letterCasePermutation(\"12345\")) "
] |
|
785 | is-graph-bipartite | [] | /**
* @param {number[][]} graph
* @return {boolean}
*/
var isBipartite = function(graph) {
}; | There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:
There are no self-edges (graph[u] does not contain u).
There are no parallel edges (graph[u] does not contain duplicate values).
If v is in graph[u], then u is in graph[v] (the graph is undirected).
The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.
A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.
Return true if and only if it is bipartite.
Example 1:
Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
Output: false
Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
Example 2:
Input: graph = [[1,3],[0,2],[1,3],[0,2]]
Output: true
Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.
Constraints:
graph.length == n
1 <= n <= 100
0 <= graph[u].length < n
0 <= graph[u][i] <= n - 1
graph[u] does not contain u.
All the values of graph[u] are unique.
If graph[u] contains v, then graph[v] contains u.
| Medium | [
"depth-first-search",
"breadth-first-search",
"union-find",
"graph"
] | [
"const isBipartite = function (graph) {\n const visited = Array(graph.length).fill(0);\n for (let i = 0; i < graph.length; i++) {\n if (visited[i] !== 0) {\n continue;\n }\n const queue = [];\n queue.push(i);\n visited[i] = 1;\n while (queue.length > 0) {\n const index = queue.shift();\n for (let j = 0; j < graph[index].length; j++) {\n const temp = graph[index][j];\n if (visited[temp] === 0) {\n visited[temp] = visited[index] * -1;\n queue.push(temp);\n } else {\n if (visited[temp] === visited[index]) return false;\n }\n }\n }\n }\n return true;\n};"
] |
|
786 | k-th-smallest-prime-fraction | [] | /**
* @param {number[]} arr
* @param {number} k
* @return {number[]}
*/
var kthSmallestPrimeFraction = function(arr, k) {
}; | You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.
For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].
Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].
Example 1:
Input: arr = [1,2,3,5], k = 3
Output: [2,5]
Explanation: The fractions to be considered in sorted order are:
1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.
The third fraction is 2/5.
Example 2:
Input: arr = [1,7], k = 1
Output: [1,7]
Constraints:
2 <= arr.length <= 1000
1 <= arr[i] <= 3 * 104
arr[0] == 1
arr[i] is a prime number for i > 0.
All the numbers of arr are unique and sorted in strictly increasing order.
1 <= k <= arr.length * (arr.length - 1) / 2
Follow up: Can you solve the problem with better than O(n2) complexity? | Medium | [
"array",
"binary-search",
"sorting",
"heap-priority-queue"
] | [
"const kthSmallestPrimeFraction = function(A, K) {\n let ans = []\n let left = 0.0\n let right = 1.0\n while (right - left > 1e-9) {\n const mid = left + (right - left) / 2\n const { count, p, q } = maxUnder(mid, A)\n if (count >= K) {\n ans = [p, q]\n right = mid\n } else {\n left = mid\n }\n }\n return ans\n\n function maxUnder(x, primes) {\n let [p, q] = [0, 1]\n let count = 0\n let l = -1\n for (let r = 1; r < primes.length; r++) {\n while (primes[l + 1] < primes[r] * x) {\n l += 1\n }\n count += l + 1\n if (l >= 0 && p * primes[r] < q * primes[l]) {\n ;[p, q] = [primes[l], primes[r]]\n }\n }\n return { count, p, q }\n }\n}"
] |
|
787 | cheapest-flights-within-k-stops | [] | /**
* @param {number} n
* @param {number[][]} flights
* @param {number} src
* @param {number} dst
* @param {number} k
* @return {number}
*/
var findCheapestPrice = function(n, flights, src, dst, k) {
}; | There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.
You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.
Example 1:
Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
Output: 700
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.
Example 2:
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
Example 3:
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
Constraints:
1 <= n <= 100
0 <= flights.length <= (n * (n - 1) / 2)
flights[i].length == 3
0 <= fromi, toi < n
fromi != toi
1 <= pricei <= 104
There will not be any multiple flights between two cities.
0 <= src, dst, k < n
src != dst
| Medium | [
"dynamic-programming",
"depth-first-search",
"breadth-first-search",
"graph",
"heap-priority-queue",
"shortest-path"
] | [
"const findCheapestPrice = function(n, flights, src, dst, K) {\n let mn = new Array(n + 1).fill(Infinity);\n mn[src] = 0;\n for(let k = 0; k < K + 1; k++){\n let newmn = [].concat(mn);\n for(let i = 0; i < flights.length; i++){\n let f = flights[i], a = f[0], b = f[1], c = f[2];\n newmn[b] = Math.min(newmn[b], mn[a] + c);\n }\n mn = [].concat(newmn);\n }\n return mn[dst] != Infinity ? mn[dst] : -1\n}",
"const findCheapestPrice = function(n, flights, src, dst, K) {\n const map = [];\n flights.forEach(([s, d, p]) => {\n map[s] = map[s] || [];\n map[s][d] = p;\n });\n let min = Infinity;\n const p = find(src, 0, 0);\n return p === Infinity ? -1 : p;\n \n function find(s, p, c) {\n if (s === dst) {\n return p;\n }\n const l = map[s];\n if (c > K || p > min || !l) {\n return Infinity;\n }\n l.forEach((p1, d) => {\n min = Math.min(min, find(d, p + p1, c + 1));\n });\n return min;\n }\n};"
] |
|
788 | rotated-digits | [] | /**
* @param {number} n
* @return {number}
*/
var rotatedDigits = function(n) {
}; | An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone.
A number is valid if each digit remains a digit after rotation. For example:
0, 1, and 8 rotate to themselves,
2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored),
6 and 9 rotate to each other, and
the rest of the numbers do not rotate to any other number and become invalid.
Given an integer n, return the number of good integers in the range [1, n].
Example 1:
Input: n = 10
Output: 4
Explanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.
Example 2:
Input: n = 1
Output: 0
Example 3:
Input: n = 2
Output: 1
Constraints:
1 <= n <= 104
| Medium | [
"math",
"dynamic-programming"
] | [
"const rotatedDigits = function(n) {\n const dp = new Array(n + 1).fill(0);\n let count = 0;\n for(let i = 0; i <= n; i++){\n if(i < 10){\n if(i == 0 || i == 1 || i == 8) dp[i] = 1;\n else if(i == 2 || i == 5 || i == 6 || i == 9){\n dp[i] = 2;\n count++;\n }\n } else {\n let a = dp[~~(i / 10)], b = dp[i % 10];\n if(a == 1 && b == 1) dp[i] = 1;\n else if(a >= 1 && b >= 1){\n dp[i] = 2;\n count++;\n }\n }\n }\n return count; \n};"
] |
|
789 | escape-the-ghosts | [] | /**
* @param {number[][]} ghosts
* @param {number[]} target
* @return {boolean}
*/
var escapeGhosts = function(ghosts, target) {
}; | You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget] that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array ghosts, where ghosts[i] = [xi, yi] represents the starting position of the ith ghost. All inputs are integral coordinates.
Each turn, you and all the ghosts may independently choose to either move 1 unit in any of the four cardinal directions: north, east, south, or west, or stay still. All actions happen simultaneously.
You escape if and only if you can reach the target before any ghost reaches you. If you reach any square (including the target) at the same time as a ghost, it does not count as an escape.
Return true if it is possible to escape regardless of how the ghosts move, otherwise return false.
Example 1:
Input: ghosts = [[1,0],[0,3]], target = [0,1]
Output: true
Explanation: You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you.
Example 2:
Input: ghosts = [[1,0]], target = [2,0]
Output: false
Explanation: You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.
Example 3:
Input: ghosts = [[2,0]], target = [1,0]
Output: false
Explanation: The ghost can reach the target at the same time as you.
Constraints:
1 <= ghosts.length <= 100
ghosts[i].length == 2
-104 <= xi, yi <= 104
There can be multiple ghosts in the same location.
target.length == 2
-104 <= xtarget, ytarget <= 104
| Medium | [
"array",
"math"
] | [
"var escapeGhosts = function(ghosts, target) {\n let res = true \n const { abs } = Math, steps = abs(target[0]) + abs(target[1])\n const [tx, ty] = target\n for(const [x, y] of ghosts) {\n if(abs(tx - x) + abs(ty - y) <= steps) return false\n }\n \n return res\n};"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.