QID
int64 1
2.85k
| titleSlug
stringlengths 3
77
| Hints
sequence | Code
stringlengths 80
1.34k
| Body
stringlengths 190
4.55k
| Difficulty
stringclasses 3
values | Topics
sequence | Definitions
stringclasses 14
values | Solutions
sequence |
---|---|---|---|---|---|---|---|---|
1,144 | decrease-elements-to-make-array-zigzag | [
"Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors."
] | /**
* @param {number[]} nums
* @return {number}
*/
var movesToMakeZigzag = function(nums) {
}; | Given an array nums of integers, a move consists of choosing any element and decreasing it by 1.
An array A is a zigzag array if either:
Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...
OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ...
Return the minimum number of moves to transform the given array nums into a zigzag array.
Example 1:
Input: nums = [1,2,3]
Output: 2
Explanation: We can decrease 2 to 0 or 3 to 1.
Example 2:
Input: nums = [9,6,1,6,2]
Output: 4
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 1000
| Medium | [
"array",
"greedy"
] | null | [] |
1,145 | binary-tree-coloring-game | [
"The best move y must be immediately adjacent to x, since it locks out that subtree.",
"Can you count each of (up to) 3 different subtrees neighboring x?"
] | /**
* 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} n
* @param {number} x
* @return {boolean}
*/
var btreeGameWinningMove = function(root, n, x) {
}; | Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n.
Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x. The first player colors the node with value x red, and the second player colors the node with value y blue.
Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.)
If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes.
You are the second player. If it is possible to choose such a y to ensure you win the game, return true. If it is not possible, return false.
Example 1:
Input: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3
Output: true
Explanation: The second player can choose the node with value 2.
Example 2:
Input: root = [1,2,3], n = 3, x = 1
Output: false
Constraints:
The number of nodes in the tree is n.
1 <= x <= n <= 100
n is odd.
1 <= Node.val <= n
All the values of the tree are unique.
| Medium | [
"tree",
"depth-first-search",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const btreeGameWinningMove = function(root, n, x) {\n let tl, tr;\n function dfs(node) {\n if (node == null) return 0;\n let l = dfs(node.left),\n r = dfs(node.right);\n if (node.val == x) (tl = l), (tr = r);\n return l + r + 1;\n }\n dfs(root);\n return Math.max(tl, tr, n - tl - tr - 1) > n / 2;\n};"
] |
1,146 | snapshot-array | [
"Use a list of lists, adding both the element and the snap_id to each index."
] | /**
* @param {number} length
*/
var SnapshotArray = function(length) {
};
/**
* @param {number} index
* @param {number} val
* @return {void}
*/
SnapshotArray.prototype.set = function(index, val) {
};
/**
* @return {number}
*/
SnapshotArray.prototype.snap = function() {
};
/**
* @param {number} index
* @param {number} snap_id
* @return {number}
*/
SnapshotArray.prototype.get = function(index, snap_id) {
};
/**
* Your SnapshotArray object will be instantiated and called as such:
* var obj = new SnapshotArray(length)
* obj.set(index,val)
* var param_2 = obj.snap()
* var param_3 = obj.get(index,snap_id)
*/ | Implement a SnapshotArray that supports the following interface:
SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0.
void set(index, val) sets the element at the given index to be equal to val.
int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.
int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id
Example 1:
Input: ["SnapshotArray","set","snap","set","get"]
[[3],[0,5],[],[0,6],[0,0]]
Output: [null,null,0,null,5]
Explanation:
SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3
snapshotArr.set(0,5); // Set array[0] = 5
snapshotArr.snap(); // Take a snapshot, return snap_id = 0
snapshotArr.set(0,6);
snapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5
Constraints:
1 <= length <= 5 * 104
0 <= index < length
0 <= val <= 109
0 <= snap_id < (the total number of times we call snap())
At most 5 * 104 calls will be made to set, snap, and get.
| Medium | [
"array",
"hash-table",
"binary-search",
"design"
] | [
"const SnapshotArray = function(length) {\n this.snaps = Array(length)\n this.snapId = 0\n};\n\n\nSnapshotArray.prototype.set = function(index, val) {\n if(this.snaps[index] == null) {\n this.snaps[index] = {}\n }\n this.snaps[index][this.snapId] = val\n};\n\n\nSnapshotArray.prototype.snap = function() {\n return this.snapId++\n};\n\n\nSnapshotArray.prototype.get = function(index, snap_id) {\n let res = 0\n let id = snap_id\n while(id >= 0) {\n if(this.snaps[index] == null || this.snaps[index][id] == null) id--\n else {\n res = this.snaps[index][id]\n break\n }\n }\n \n return res\n};",
"const binarySearch = function (nums, target, comparator) {\n let low = 0;\n let high = nums.length - 1;\n while (low <= high) {\n let mid = low + ((high - low) >>> 1);\n let midValue = nums[mid];\n let cmp = comparator(midValue, target);\n if (cmp < 0) low = mid + 1;\n else if (cmp > 0) high = mid - 1;\n else return mid;\n }\n return -(low + 1);\n};\n\n\nconst SnapshotArray = function (length) {\n this.count = 0;\n this.arr = Array.from({ length: length }, () => [[0, 0]]);\n};\n\n\nSnapshotArray.prototype.set = function (index, val) {\n const arr = this.arr,\n count = this.count;\n if (arr[index][arr[index].length - 1][0] === count) {\n arr[index][arr[index].length - 1][1] = val;\n } else {\n arr[index].push([count, val]);\n }\n};\n\n\nSnapshotArray.prototype.snap = function () {\n return this.count++;\n};\n\n\nSnapshotArray.prototype.get = function (index, snap_id) {\n let idx = binarySearch(this.arr[index], [snap_id, 0], (a, b) => a[0] - b[0]);\n if (idx < 0) idx = -idx - 2;\n return this.arr[index][idx][1];\n};",
"const SnapshotArray = function(length) {\n this.arr = new Array(length).fill(0);\n this.snaps = new Array(length);\n this.count = 0;\n};\n\n\nSnapshotArray.prototype.set = function(index, val) {\n if (this.snaps[index] == undefined) {\n this.snaps[index] = {};\n }\n\n this.snaps[index][this.count] = val;\n};\n\n\nSnapshotArray.prototype.snap = function() {\n return this.count++;\n};\n\n\nSnapshotArray.prototype.get = function(index, snap_id) {\n if (this.snaps[index] == undefined) return 0;\n\n let res = 0;\n while (snap_id >= 0) {\n if (this.snaps[index][snap_id] == undefined) {\n snap_id--;\n } else {\n res = this.snaps[index][snap_id];\n snap_id = -1;\n }\n }\n\n return res;\n};"
] |
|
1,147 | longest-chunked-palindrome-decomposition | [
"Using a rolling hash, we can quickly check whether two strings are equal.",
"Use that as the basis of a dp."
] | /**
* @param {string} text
* @return {number}
*/
var longestDecomposition = function(text) {
}; | You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that:
subtexti is a non-empty string.
The concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2 + ... + subtextk == text).
subtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k).
Return the largest possible value of k.
Example 1:
Input: text = "ghiabcdefhelloadamhelloabcdefghi"
Output: 7
Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)".
Example 2:
Input: text = "merchant"
Output: 1
Explanation: We can split the string on "(merchant)".
Example 3:
Input: text = "antaprezatepzapreanta"
Output: 11
Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)".
Constraints:
1 <= text.length <= 1000
text consists only of lowercase English characters.
| Hard | [
"two-pointers",
"string",
"dynamic-programming",
"greedy",
"rolling-hash",
"hash-function"
] | [
"const longestDecomposition = function(text) {\n let res = 0,\n n = text.length\n let l = '',\n r = ''\n for (let i = 0; i < n; ++i) {\n l = l + text.charAt(i)\n r = text.charAt(n - i - 1) + r\n if (l === r) {\n ++res\n l = ''\n r = ''\n }\n }\n return res\n}",
"const longestDecomposition = function(text) {\n let n = text.length\n for (let i = 0; i < Math.floor(n / 2); i++)\n if (text.slice(0, i + 1) === text.slice(n - 1 - i, n))\n return 2 + longestDecomposition(text.slice(i + 1, n - 1 - i))\n return n === 0 ? 0 : 1\n}"
] |
|
1,154 | day-of-the-year | [
"Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one)."
] | /**
* @param {string} date
* @return {number}
*/
var dayOfYear = function(date) {
}; | Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.
Example 1:
Input: date = "2019-01-09"
Output: 9
Explanation: Given date is the 9th day of the year in 2019.
Example 2:
Input: date = "2019-02-10"
Output: 41
Constraints:
date.length == 10
date[4] == date[7] == '-', and all other date[i]'s are digits
date represents a calendar date between Jan 1st, 1900 and Dec 31th, 2019.
| Easy | [
"math",
"string"
] | [
"const dayOfYear = function(date) {\n const [year, month, day] = date.split('-').map(s => +s),\n months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],\n isLeapYear = !(year % 4) && month > 2 && (!!(year % 100) || !(year % 400))\n return months.splice(0, month - 1).reduce((a, b) => a + b, day + +isLeapYear)\n}"
] |
|
1,155 | number-of-dice-rolls-with-target-sum | [
"Use dynamic programming. The states are how many dice are remaining, and what sum total you have rolled so far."
] | /**
* @param {number} n
* @param {number} k
* @param {number} target
* @return {number}
*/
var numRollsToTarget = function(n, k, target) {
}; | You have n dice, and each die has k faces numbered from 1 to k.
Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice, so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: n = 1, k = 6, target = 3
Output: 1
Explanation: You throw one die with 6 faces.
There is only one way to get a sum of 3.
Example 2:
Input: n = 2, k = 6, target = 7
Output: 6
Explanation: You throw two dice, each with 6 faces.
There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.
Example 3:
Input: n = 30, k = 30, target = 500
Output: 222616187
Explanation: The answer must be returned modulo 109 + 7.
Constraints:
1 <= n, k <= 30
1 <= target <= 1000
| Medium | [
"dynamic-programming"
] | [
"const numRollsToTarget = function(d, f, target) {\n const mod = 10 ** 9 + 7\n if (target > d * f || target < d) {\n return 0\n }\n const dp = new Array(target + 1).fill(0)\n for (let i = 1; i < Math.min(f + 1, target + 1); i++) {\n dp[i] = 1\n }\n for (let i = 2; i < d + 1; i++) {\n for (let j = Math.min(target, i * f); j > i - 1; j--) {\n dp[j] = 0\n for (let k = Math.max(i - 1, j - f); k < j; k++) {\n dp[j] = (dp[j] + dp[k]) % mod\n }\n }\n }\n\n return dp[target]\n}",
"const numRollsToTarget = function(d, f, target) {\n const MOD = 10 ** 9 + 7;\n const dp = Array.from({ length: d + 1 }, () => new Array(target + 1).fill(0));\n dp[0][0] = 1;\n for (let i = 1; i <= d; i++) {\n for (let j = 1; j <= target; j++) {\n if (j > i * f) {\n continue;\n } else {\n for (let k = 1; k <= f && k <= j; k++) {\n dp[i][j] = (dp[i][j] + dp[i - 1][j - k]) % MOD;\n }\n }\n }\n }\n return dp[d][target];\n};"
] |
|
1,156 | swap-for-longest-repeated-character-substring | [
"There are two cases: a block of characters, or two blocks of characters between one different character. \r\n By keeping a run-length encoded version of the string, we can easily check these cases."
] | /**
* @param {string} text
* @return {number}
*/
var maxRepOpt1 = function(text) {
}; | You are given a string text. You can swap two of the characters in the text.
Return the length of the longest substring with repeated characters.
Example 1:
Input: text = "ababa"
Output: 3
Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3.
Example 2:
Input: text = "aaabaaa"
Output: 6
Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6.
Example 3:
Input: text = "aaaaa"
Output: 5
Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5.
Constraints:
1 <= text.length <= 2 * 104
text consist of lowercase English characters only.
| Medium | [
"hash-table",
"string",
"sliding-window"
] | [
"const maxRepOpt1 = function(text) {\n const count = [...text].reduce((a, c) => {\n a[c] = a[c] || 0;\n a[c]++;\n return a;\n }, {});\n let ans = 0;\n let i = 0;\n while (i < text.length) {\n let j = i;\n const c = text.charAt(i);\n while (j < text.length && text.charAt(j) === c) j++;\n if (j - i < count[c]) {\n let k = j + 1;\n while (k < text.length && text.charAt(k) === c && k - i < count[c]) k++;\n ans = Math.max(k - i, ans);\n } else ans = Math.max(j - i, ans);\n i = j;\n }\n return ans;\n};"
] |
|
1,157 | online-majority-element-in-subarray | [
"What's special about a majority element ?",
"A majority element appears more than half the length of the array number of times.",
"If we tried a random index of the array, what's the probability that this index has a majority element ?",
"It's more than 50% if that array has a majority element.",
"Try a random index for a proper number of times so that the probability of not finding the answer tends to zero."
] | /**
* @param {number[]} arr
*/
var MajorityChecker = function(arr) {
};
/**
* @param {number} left
* @param {number} right
* @param {number} threshold
* @return {number}
*/
MajorityChecker.prototype.query = function(left, right, threshold) {
};
/**
* Your MajorityChecker object will be instantiated and called as such:
* var obj = new MajorityChecker(arr)
* var param_1 = obj.query(left,right,threshold)
*/ | Design a data structure that efficiently finds the majority element of a given subarray.
The majority element of a subarray is an element that occurs threshold times or more in the subarray.
Implementing the MajorityChecker class:
MajorityChecker(int[] arr) Initializes the instance of the class with the given array arr.
int query(int left, int right, int threshold) returns the element in the subarray arr[left...right] that occurs at least threshold times, or -1 if no such element exists.
Example 1:
Input
["MajorityChecker", "query", "query", "query"]
[[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]]
Output
[null, 1, -1, 2]
Explanation
MajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]);
majorityChecker.query(0, 5, 4); // return 1
majorityChecker.query(0, 3, 3); // return -1
majorityChecker.query(2, 3, 2); // return 2
Constraints:
1 <= arr.length <= 2 * 104
1 <= arr[i] <= 2 * 104
0 <= left <= right < arr.length
threshold <= right - left + 1
2 * threshold > right - left + 1
At most 104 calls will be made to query.
| Hard | [
"array",
"binary-search",
"design",
"binary-indexed-tree",
"segment-tree"
] | [
"function Bisect() {\n return { insort_right, insort_left, bisect_left, bisect_right }\n function insort_right(a, x, lo = 0, hi = null) {\n lo = bisect_right(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_right(a, x, lo = 0, hi = null) {\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = (lo + hi) >> 1\n x < a[mid] ? (hi = mid) : (lo = mid + 1)\n }\n return lo\n }\n function insort_left(a, x, lo = 0, hi = null) {\n lo = bisect_left(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_left(a, x, lo = 0, hi = null) {\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = (lo + hi) >> 1\n a[mid] < x ? (lo = mid + 1) : (hi = mid)\n }\n return lo\n }\n}\n\nfunction SegmentTreeRQ(m, A, n) {\n let bisect = new Bisect()\n let h = Math.ceil(Math.log2(n))\n const MAX = 2 * 2 ** h - 1\n let tree = Array(MAX).fill(-1)\n let a = [...A]\n build(1, 0, n - 1)\n return {\n query,\n }\n\n function build(vi, tl, tr) {\n if (tl == tr) {\n tree[vi] = a[tl]\n return\n }\n let mid = getMid(tl, tr)\n build(vi * 2, tl, mid)\n build(vi * 2 + 1, mid + 1, tr)\n if (\n tree[vi * 2] != -1 &&\n get_occurrence(tree[vi * 2], tl, tr) * 2 > tr - tl + 1\n ) {\n tree[vi] = tree[vi * 2]\n } else if (\n tree[vi * 2 + 1] != -1 &&\n get_occurrence(tree[vi * 2 + 1], tl, tr) * 2 > tr - tl + 1\n ) {\n tree[vi] = tree[vi * 2 + 1]\n }\n }\n\n function query(vi, l, r, tl, tr) {\n if (l > tr || r < tl) {\n return {\n first: -1,\n second: -1,\n }\n }\n if (tl <= l && r <= tr) {\n if (tree[vi] == -1)\n return {\n first: -1,\n second: -1,\n }\n let occ = get_occurrence(tree[vi], tl, tr)\n if (occ * 2 > tr - tl + 1) {\n return {\n first: tree[vi],\n second: occ,\n }\n } else {\n return {\n first: -1,\n second: -1,\n }\n }\n }\n let mid = getMid(l, r)\n let resL = query(vi * 2, l, mid, tl, tr)\n if (resL.first > -1) return resL\n let resR = query(vi * 2 + 1, mid + 1, r, tl, tr)\n if (resR.first > -1) return resR\n return {\n first: -1,\n second: -1,\n }\n }\n\n function get_occurrence(num, l, r) {\n // only difference\n if (!m.has(num)) return 0\n let a = m.get(num)\n let lbv = bisect.bisect_left(a, l) //lower_bound\n if (lbv == a.length) return 0\n let ubv = bisect.bisect_right(a, r) // upper_bound\n return ubv - lbv\n }\n\n function getMid(low, high) {\n return low + ((high - low) >> 1)\n }\n}\n\nfunction MajorityChecker(a) {\n let m = new Map()\n let n = a.length\n for (let i = 0; i < n; i++) {\n if (!m.has(a[i])) m.set(a[i], [])\n m.get(a[i]).push(i)\n }\n let st = new SegmentTreeRQ(m, a, n)\n return {\n query,\n }\n\n function query(left, right, threshold) {\n let res = st.query(1, 0, n - 1, left, right)\n if (res.second >= threshold) {\n return res.first\n }\n return -1\n }\n}",
"const MajorityChecker = function(arr) {\n const map = new Map()\n for (let i = 0; i < arr.length; i++) {\n if (!map.has(arr[i])) map.set(arr[i], [i])\n else map.get(arr[i]).push(i)\n }\n this.pos = map\n this.arr = arr\n}\n\nfunction lbs(arr, val) {\n let lo = 0\n let hi = arr.length - 1\n if (arr[0] >= val) return 0\n else if (arr[hi] < val) return Infinity\n let mid\n while (hi - lo > 1) {\n mid = (hi + lo) >> 1\n if (arr[mid] === val) return mid\n else if (arr[mid] < val) lo = mid\n else if (arr[mid] > val) hi = mid\n }\n return hi\n}\n\nfunction rbs(arr, val) {\n let lo = 0\n let hi = arr.length - 1\n if (arr[hi] <= val) return hi\n else if (arr[lo] > val) return -Infinity\n let mid\n while (hi - lo > 1) {\n mid = (hi + lo) >> 1\n if (arr[mid] === val) return mid\n else if (arr[mid] < val) lo = mid\n else if (arr[mid] > val) hi = mid\n }\n return lo\n}\n\n\nMajorityChecker.prototype.query = function(left, right, threshold) {\n const { arr, pos } = this\n let c = 20\n while (c--) {\n const idx = left + Math.floor(Math.random() * (right - left + 1))\n const sort = pos.get(arr[idx])\n const lidx = lbs(sort, left)\n const ridx = rbs(sort, right)\n if (ridx - lidx + 1 >= threshold) return arr[idx]\n }\n return -1\n}"
] |
|
1,160 | find-words-that-can-be-formed-by-characters | [
"Solve the problem for each string in <code>words</code> independently.",
"Now try to think in frequency of letters.",
"Count how many times each character occurs in string <code>chars</code>.",
"To form a string using characters from <code>chars</code>, the frequency of each character in <code>chars</code> must be greater than or equal the frequency of that character in the string to be formed."
] | /**
* @param {string[]} words
* @param {string} chars
* @return {number}
*/
var countCharacters = function(words, chars) {
}; | You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in words.
Example 1:
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Example 2:
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
Constraints:
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
words[i] and chars consist of lowercase English letters.
| Easy | [
"array",
"hash-table",
"string"
] | [
"const countCharacters = function(words, chars) {\n let letters = new Array(26).fill(0),\n a = 'a'.charCodeAt(0),\n z = 'z'.charCodeAt(0)\n let count = 0\n for (let i = 0; i < chars.length; i++) {\n let l = chars[i].charCodeAt(0) - a\n letters[l]++\n }\n for (let i = 0; i < words.length; i++) {\n let word = words[i]\n let tmp = letters.slice()\n let tCount = 0\n for (let j = 0; j < word.length; j++) {\n let l = word[j].charCodeAt(0) - a\n tmp[l]--\n if (tmp[l] < 0) {\n break\n } else {\n tCount++\n }\n }\n if (tCount == word.length) {\n count += word.length\n }\n }\n return count\n}"
] |
|
1,161 | maximum-level-sum-of-a-binary-tree | [
"Calculate the sum for each level then find the level with the maximum sum.",
"How can you traverse the tree ?",
"How can you sum up the values for every level ?",
"Use DFS or BFS to traverse the tree keeping the level of each node, and sum up those values with a map or a frequency array."
] | /**
* 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 maxLevelSum = function(root) {
}; | Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
Return the smallest level x such that the sum of all the values of nodes at level x is maximal.
Example 1:
Input: root = [1,7,0,7,-8,null,null]
Output: 2
Explanation:
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.
Example 2:
Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]
Output: 2
Constraints:
The number of nodes in the tree is in the range [1, 104].
-105 <= Node.val <= 105
| Medium | [
"tree",
"depth-first-search",
"breadth-first-search",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const maxLevelSum = function(root) {\n if (root == null) return 0\n let res = 1\n let cur = [root]\n let next = []\n let max = Number.MIN_SAFE_INTEGER\n let sum = 0\n let level = 1\n while (cur.length) {\n let node = cur.pop()\n if (node.left) next.push(node.left)\n if (node.right) next.push(node.right)\n sum += node.val\n if (cur.length === 0) {\n cur = next\n next = []\n if (sum > max) {\n res = level\n max = sum\n }\n sum = 0\n level++\n }\n }\n\n return res\n}\n\n// DFS\n\nconst maxLevelSum = function(root) {\n let result = {};\n let recursion = function(root, level) {\n if (result[level] !== undefined) {\n result[level] += root.val;\n } else {\n result[level] = root.val;\n }\n if (root.left !== null) {\n recursion(root.left, level + 1);\n }\n if (root.right !== null) {\n recursion(root.right, level + 1);\n }\n };\n recursion(root, 1);\n let resultkey = 1;\n let max = Number.MIN_VALUE;\n for (let key of Object.keys(result)) {\n if (result[key] > max) {\n max = result[key];\n resultkey = key;\n }\n }\n return Number(resultkey);\n};"
] |
1,162 | as-far-from-land-as-possible | [
"Can you think of this problem in a backwards way ?",
"Imagine expanding outward from each land cell. What kind of search does that ?",
"Use BFS starting from all land cells in the same time.",
"When do you reach the furthest water cell?"
] | /**
* @param {number[][]} grid
* @return {number}
*/
var maxDistance = function(grid) {
}; | Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.
The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.
Example 1:
Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.
Example 2:
Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 100
grid[i][j] is 0 or 1
| Medium | [
"array",
"dynamic-programming",
"breadth-first-search",
"matrix"
] | [
"const maxDistance = function(grid) {\n let m = grid.length\n let n = m === 0 ? 0 : grid[0].length\n let dp = new Array(m + 2)\n for (let i = 0; i < m + 2; i++) {\n dp[i] = new Array(n + 2).fill(Number.POSITIVE_INFINITY)\n }\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n if (grid[i - 1][j - 1] === 0) {\n dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1\n } else {\n dp[i][j] = 0\n }\n }\n }\n let res = Number.NEGATIVE_INFINITY\n for (let i = m; i >= 1; i--) {\n for (let j = n; j >= 1; j--) {\n if (grid[i - 1][j - 1] === 0) {\n dp[i][j] = Math.min(dp[i][j], Math.min(dp[i + 1][j], dp[i][j + 1]) + 1)\n res = Math.max(res, dp[i][j])\n }\n }\n }\n return isFinite(res) ? res : -1\n}"
] |
|
1,163 | last-substring-in-lexicographical-order | [
"Assume that the answer is a sub-string from index i to j. If you add the character at index j+1 you get a better answer.",
"The answer is always a suffix of the given string.",
"Since the limits are high, we need an efficient data structure.",
"Use suffix array."
] | /**
* @param {string} s
* @return {string}
*/
var lastSubstring = function(s) {
}; | Given a string s, return the last substring of s in lexicographical order.
Example 1:
Input: s = "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
Example 2:
Input: s = "leetcode"
Output: "tcode"
Constraints:
1 <= s.length <= 4 * 105
s contains only lowercase English letters.
| Hard | [
"two-pointers",
"string"
] | [
"const lastSubstring = function(s) {\n let ans = '',\n max = 'a'\n for (let i = 0; i < s.length; ) {\n let j = i,\n sub = s.slice(i)\n if (max < s[i] || ans < sub) {\n max = s[i]\n ans = sub\n }\n while (i < s.length && s[i + 1] === s[i]) {\n i++\n }\n if (j === i) {\n i++\n }\n }\n return ans\n}"
] |
|
1,169 | invalid-transactions | [
"Split each string into four arrays.",
"For each transaction check if it's invalid, you can do this with just a loop with help of the four arrays generated on step 1.",
"At the end you perform O(N ^ 2) operations."
] | /**
* @param {string[]} transactions
* @return {string[]}
*/
var invalidTransactions = function(transactions) {
}; | A transaction is possibly invalid if:
the amount exceeds $1000, or;
if it occurs within (and including) 60 minutes of another transaction with the same name in a different city.
You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.
Return a list of transactions that are possibly invalid. You may return the answer in any order.
Example 1:
Input: transactions = ["alice,20,800,mtv","alice,50,100,beijing"]
Output: ["alice,20,800,mtv","alice,50,100,beijing"]
Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.
Example 2:
Input: transactions = ["alice,20,800,mtv","alice,50,1200,mtv"]
Output: ["alice,50,1200,mtv"]
Example 3:
Input: transactions = ["alice,20,800,mtv","bob,50,1200,mtv"]
Output: ["bob,50,1200,mtv"]
Constraints:
transactions.length <= 1000
Each transactions[i] takes the form "{name},{time},{amount},{city}"
Each {name} and {city} consist of lowercase English letters, and have lengths between 1 and 10.
Each {time} consist of digits, and represent an integer between 0 and 1000.
Each {amount} consist of digits, and represent an integer between 0 and 2000.
| Medium | [
"array",
"hash-table",
"string",
"sorting"
] | null | [] |
1,170 | compare-strings-by-frequency-of-the-smallest-character | [
"For each string from words calculate the leading count and store it in an array, then sort the integer array.",
"For each string from queries calculate the leading count \"p\" and in base of the sorted array calculated on the step 1 do a binary search to count the number of items greater than \"p\"."
] | /**
* @param {string[]} queries
* @param {string[]} words
* @return {number[]}
*/
var numSmallerByFrequency = function(queries, words) {
}; | Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = "dcce" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.
You are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each W in words.
Return an integer array answer, where each answer[i] is the answer to the ith query.
Example 1:
Input: queries = ["cbd"], words = ["zaaaz"]
Output: [1]
Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").
Example 2:
Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
Output: [1,2]
Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").
Constraints:
1 <= queries.length <= 2000
1 <= words.length <= 2000
1 <= queries[i].length, words[i].length <= 10
queries[i][j], words[i][j] consist of lowercase English letters.
| Medium | [
"array",
"hash-table",
"string",
"binary-search",
"sorting"
] | [
"const numSmallerByFrequency = function(queries, words) {\n const qArr = []\n for(let i = 0, len = queries.length; i < len; i++) {\n let sm = 'z'\n let hash = {}\n let cur = queries[i]\n for(let char of cur) {\n if(hash[char] == null) hash[char] = 0\n hash[char]++\n if(char < sm) sm = char\n }\n qArr.push(hash[sm])\n }\n const wArr = []\n for(let i = 0, len = words.length; i < len; i++) {\n let sm = 'z'\n let hash = {}\n let cur = words[i]\n for(let char of cur) {\n if(hash[char] == null) hash[char] = 0\n hash[char]++\n if(char < sm) sm = char\n }\n wArr.push(hash[sm])\n }\n const res = []\n for(let i = 0, len = queries.length; i < len; i++) {\n let cur = 0\n for(let j = 0, wlen = words.length; j < wlen; j++) {\n if(qArr[i] < wArr[j]) cur++\n }\n res.push(cur)\n }\n return res\n};"
] |
|
1,171 | remove-zero-sum-consecutive-nodes-from-linked-list | [
"Convert the linked list into an array.",
"While you can find a non-empty subarray with sum = 0, erase it.",
"Convert the array into a linked list."
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var removeZeroSumSublists = function(head) {
}; | Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of ListNode objects.)
Example 1:
Input: head = [1,2,-3,3,1]
Output: [3,1]
Note: The answer [1,2,1] would also be accepted.
Example 2:
Input: head = [1,2,3,-3,4]
Output: [1,2,4]
Example 3:
Input: head = [1,2,3,-3,-2]
Output: [1]
Constraints:
The given linked list will contain between 1 and 1000 nodes.
Each node in the linked list has -1000 <= node.val <= 1000.
| Medium | [
"hash-table",
"linked-list"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const removeZeroSumSublists = function(head) {\n let dummy = new ListNode(0), cur = dummy;\n dummy.next = head;\n let prefix = 0;\n let m = new Map();\n while (cur != null) {\n prefix += cur.val;\n if (m.has(prefix)) {\n cur = m.get(prefix).next;\n let p = prefix + cur.val;\n while (p != prefix) {\n m.delete(p);\n cur = cur.next;\n p += cur.val;\n }\n m.get(prefix).next = cur.next;\n } else {\n m.set(prefix, cur);\n }\n cur = cur.next;\n }\n return dummy.next;\n};"
] |
1,172 | dinner-plate-stacks | [
"Use a data structure to save the plate status. You may need to operate the exact index. Maintain the leftmost vacant stack and the rightmost non-empty stack.",
"Use a list of stack to store the plate status. Use heap to maintain the leftmost and rightmost valid stack."
] | /**
* @param {number} capacity
*/
var DinnerPlates = function(capacity) {
};
/**
* @param {number} val
* @return {void}
*/
DinnerPlates.prototype.push = function(val) {
};
/**
* @return {number}
*/
DinnerPlates.prototype.pop = function() {
};
/**
* @param {number} index
* @return {number}
*/
DinnerPlates.prototype.popAtStack = function(index) {
};
/**
* Your DinnerPlates object will be instantiated and called as such:
* var obj = new DinnerPlates(capacity)
* obj.push(val)
* var param_2 = obj.pop()
* var param_3 = obj.popAtStack(index)
*/ | You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity.
Implement the DinnerPlates class:
DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity.
void push(int val) Pushes the given integer val into the leftmost stack with a size less than capacity.
int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all the stacks are empty.
int popAtStack(int index) Returns the value at the top of the stack with the given index index and removes it from that stack or returns -1 if the stack with that given index is empty.
Example 1:
Input
["DinnerPlates", "push", "push", "push", "push", "push", "popAtStack", "push", "push", "popAtStack", "popAtStack", "pop", "pop", "pop", "pop", "pop"]
[[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []]
Output
[null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1]
Explanation:
DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2
D.push(1);
D.push(2);
D.push(3);
D.push(4);
D.push(5); // The stacks are now: 2 4
1 3 5
﹈ ﹈ ﹈
D.popAtStack(0); // Returns 2. The stacks are now: 4
1 3 5
﹈ ﹈ ﹈
D.push(20); // The stacks are now: 20 4
1 3 5
﹈ ﹈ ﹈
D.push(21); // The stacks are now: 20 4 21
1 3 5
﹈ ﹈ ﹈
D.popAtStack(0); // Returns 20. The stacks are now: 4 21
1 3 5
﹈ ﹈ ﹈
D.popAtStack(2); // Returns 21. The stacks are now: 4
1 3 5
﹈ ﹈ ﹈
D.pop() // Returns 5. The stacks are now: 4
1 3
﹈ ﹈
D.pop() // Returns 4. The stacks are now: 1 3
﹈ ﹈
D.pop() // Returns 3. The stacks are now: 1
﹈
D.pop() // Returns 1. There are no stacks.
D.pop() // Returns -1. There are still no stacks.
Constraints:
1 <= capacity <= 2 * 104
1 <= val <= 2 * 104
0 <= index <= 105
At most 2 * 105 calls will be made to push, pop, and popAtStack.
| Hard | [
"hash-table",
"stack",
"design",
"heap-priority-queue"
] | [
"const DinnerPlates = function (capacity) {\n this.capacity = capacity\n this.stacks = []\n this.pq = new PriorityQueue()\n}\n\n\nDinnerPlates.prototype.push = function (val) {\n if (this.pq.isEmpty()) {\n if (\n this.stacks.length > 0 &&\n this.stacks[this.stacks.length - 1].length < this.capacity\n ) {\n this.stacks[this.stacks.length - 1].push(val)\n } else {\n this.stacks.push([])\n this.stacks[this.stacks.length - 1].push(val)\n }\n } else {\n const num = this.pq.pop()\n this.stacks[num].push(val)\n }\n}\n\n\nDinnerPlates.prototype.pop = function () {\n while (\n this.stacks.length > 0 &&\n this.stacks[this.stacks.length - 1].length === 0\n ) {\n const len = this.stacks.length - 1\n while (!this.pq.isEmpty() && this.pq.peek() >= len) {\n this.pq.pop()\n }\n this.stacks.pop()\n }\n if (this.stacks.length === 0) {\n return -1\n } else {\n return this.stacks[this.stacks.length - 1].pop()\n }\n}\n\n\nDinnerPlates.prototype.popAtStack = function (index) {\n const st = this.stacks[index]\n\n if (st && st.length > 0) {\n this.pq.push(index)\n return st.pop()\n }\n\n return -1\n}\n\n\nclass PriorityQueue {\n constructor(len, compare) {\n this.compare = (a, b) => {\n return a < b\n }\n this.last = 0\n this.arr = []\n }\n push(val) {\n this.last++\n this.arr[this.last] = val\n this.up(this.last)\n }\n pop() {\n if (this.isEmpty()) {\n return null\n }\n const res = this.arr[1]\n this.swap(1, this.last)\n this.last--\n this.down(1)\n return res\n }\n up(lo) {\n while (lo > 1) {\n const currEl = this.arr[lo]\n const parent = Math.floor(lo / 2)\n const parentEl = this.arr[parent]\n if (this.compare(currEl, parentEl)) {\n this.swap(lo, parent)\n } else {\n break\n }\n lo = parent\n }\n }\n down(hi) {\n while (hi * 2 <= this.last) {\n const currEl = this.arr[hi]\n let nextEl = this.arr[hi * 2]\n let nextIndex = hi * 2\n if (\n hi * 2 + 1 <= this.last &&\n this.compare(this.arr[hi * 2 + 1], nextEl)\n ) {\n nextIndex = hi * 2 + 1\n nextEl = this.arr[nextIndex]\n }\n if (this.compare(nextEl, currEl)) {\n this.swap(hi, nextIndex)\n } else {\n break\n }\n hi = nextIndex\n }\n }\n swap(i, j) {\n const temp = this.arr[i]\n this.arr[i] = this.arr[j]\n this.arr[j] = temp\n }\n peek() {\n if (this.isEmpty()) {\n return null\n }\n return this.arr[1]\n }\n isEmpty() {\n return this.last < 1\n }\n}",
"const DinnerPlates = function (capacity) {\n this.pushIndex = 0\n this.popIndex = 0\n this.capacity = capacity\n this.stacks = [[]]\n}\n\n\nDinnerPlates.prototype.push = function (val) {\n while (\n this.pushIndex < this.stacks.length &&\n this.stacks[this.pushIndex].length === this.capacity\n ) {\n this.pushIndex++\n }\n if (this.stacks.length === this.pushIndex) {\n this.stacks[this.pushIndex] = [val]\n } else {\n this.stacks[this.pushIndex].push(val)\n }\n if (this.popIndex < this.pushIndex) {\n this.popIndex = this.pushIndex\n }\n}\n\n\nDinnerPlates.prototype.pop = function () {\n while (this.stacks[this.popIndex].length === 0) {\n if (this.popIndex > 0) {\n this.popIndex--\n } else {\n return -1\n }\n }\n const valueAtIndex = this.stacks[this.popIndex].pop()\n if (this.pushIndex > this.popIndex) {\n this.pushIndex = this.popIndex\n }\n return valueAtIndex\n}\n\n\nDinnerPlates.prototype.popAtStack = function (index) {\n if (index >= this.stacks.length) return -1\n if (index < this.pushIndex) this.pushIndex = index\n return this.stacks[index].length > 0 ? this.stacks[index].pop() : -1\n}"
] |
|
1,175 | prime-arrangements | [
"Solve the problem for prime numbers and composite numbers separately.",
"Multiply the number of permutations of prime numbers over prime indices with the number of permutations of composite numbers over composite indices.",
"The number of permutations equals the factorial."
] | /**
* @param {number} n
* @return {number}
*/
var numPrimeArrangements = function(n) {
}; | Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)
(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)
Since the answer may be large, return the answer modulo 10^9 + 7.
Example 1:
Input: n = 5
Output: 12
Explanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.
Example 2:
Input: n = 100
Output: 682289015
Constraints:
1 <= n <= 100
| Easy | [
"math"
] | [
"function isPrime(n) {\n // Corner case\n if (n <= 1) return false\n // Check from 2 to n-1\n for (let i = 2; i < n; i++) if (n % i == 0) return false\n return true\n}\n\nconst numPrimeArrangements = function(n) {\n let primes = 0 // # of primes.\n let result = 1\n const mod = 10 ** 9 + 7\n for (let i = 2; i <= n; i++) if (isPrime(i)) primes++\n // Calculate factorials and multiply.\n for (let i = primes; i >= 1; i--) result = (i * result) % mod\n for (let i = n - primes; i >= 1; i--) result = (i * result) % mod\n return result // result of multiplying factorial(primes) with factorial(non-primes)\n}"
] |
|
1,177 | can-make-palindrome-from-substring | [
"Since we can rearrange the substring, all we care about is the frequency of each character in that substring.",
"How to find the character frequencies efficiently ?",
"As a preprocess, calculate the accumulate frequency of all characters for all prefixes of the string.",
"How to check if a substring can be changed to a palindrome given its characters frequency ?",
"Count the number of odd frequencies, there can be at most one odd frequency in a palindrome."
] | /**
* @param {string} s
* @param {number[][]} queries
* @return {boolean[]}
*/
var canMakePaliQueries = function(s, queries) {
}; | You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter.
If the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false.
Return a boolean array answer where answer[i] is the result of the ith query queries[i].
Note that each letter is counted individually for replacement, so if, for example s[lefti...righti] = "aaa", and ki = 2, we can only replace two of the letters. Also, note that no query modifies the initial string s.
Example :
Input: s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]
Output: [true,false,false,true,true]
Explanation:
queries[0]: substring = "d", is palidrome.
queries[1]: substring = "bc", is not palidrome.
queries[2]: substring = "abcd", is not palidrome after replacing only 1 character.
queries[3]: substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab".
queries[4]: substring = "abcda", could be changed to "abcba" which is palidrome.
Example 2:
Input: s = "lyb", queries = [[0,1,0],[2,2,1]]
Output: [false,true]
Constraints:
1 <= s.length, queries.length <= 105
0 <= lefti <= righti < s.length
0 <= ki <= s.length
s consists of lowercase English letters.
| Medium | [
"array",
"hash-table",
"string",
"bit-manipulation",
"prefix-sum"
] | [
"const canMakePaliQueries = function(s, queries) {\n const code = ch => ch.charCodeAt(0) - 'a'.charCodeAt(0)\n const preCount = [...s].reduce(\n (a, c) => {\n let nc = a[a.length - 1]\n nc ^= 1 << code(c) //NOT on one bit\n a.push(nc)\n return a\n },\n [0]\n )\n return queries.map(q => {\n let subCount = preCount[q[1] + 1] ^ preCount[q[0]]\n let oddChs = 0\n while (subCount > 0) {\n oddChs += subCount & 1\n subCount >>= 1\n }\n return Math.floor(oddChs / 2) <= q[2]\n })\n}"
] |
|
1,178 | number-of-valid-words-for-each-puzzle | [
"Exploit the fact that the length of the puzzle is only 7.",
"Use bit-masks to represent the word and puzzle strings.",
"For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask."
] | /**
* @param {string[]} words
* @param {string[]} puzzles
* @return {number[]}
*/
var findNumOfValidWords = function(words, puzzles) {
}; | With respect to a given puzzle string, a word is valid if both the following conditions are satisfied:
word contains the first letter of puzzle.
For each letter in word, that letter is in puzzle.
For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage", while
invalid words are "beefed" (does not include 'a') and "based" (includes 's' which is not in the puzzle).
Return an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i].
Example 1:
Input: words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
Output: [1,1,3,2,4,0]
Explanation:
1 valid word for "aboveyz" : "aaaa"
1 valid word for "abrodyz" : "aaaa"
3 valid words for "abslute" : "aaaa", "asas", "able"
2 valid words for "absoryz" : "aaaa", "asas"
4 valid words for "actresz" : "aaaa", "asas", "actt", "access"
There are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.
Example 2:
Input: words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"]
Output: [0,1,3,2,0]
Constraints:
1 <= words.length <= 105
4 <= words[i].length <= 50
1 <= puzzles.length <= 104
puzzles[i].length == 7
words[i] and puzzles[i] consist of lowercase English letters.
Each puzzles[i] does not contain repeated characters.
| Hard | [
"array",
"hash-table",
"string",
"bit-manipulation",
"trie"
] | [
"const findNumOfValidWords = function(words, puzzles) {\n let n = puzzles.length,\n offset = 'a'.charCodeAt()\n let res = new Array(n).fill(0)\n let cnt = {}\n\n for (let w of words) {\n let mask = 0\n for (let c of w) {\n mask |= 1 << (c.charCodeAt() - offset)\n }\n cnt[mask] = ~~cnt[mask] + 1\n }\n for (let i = 0; i < n; i++) {\n let s = puzzles[i],\n len = s.length\n for (let k = 0; k < 1 << (len - 1); k++) {\n let mask = 1 << (s[0].charCodeAt() - offset)\n for (let j = 0; j < len - 1; j++) {\n if (k & (1 << j)) {\n mask |= 1 << (s[j + 1].charCodeAt() - offset)\n }\n }\n res[i] += ~~cnt[mask]\n }\n }\n return res\n}"
] |
|
1,184 | distance-between-bus-stops | [
"Find the distance between the two stops if the bus moved in clockwise or counterclockwise directions."
] | /**
* @param {number[]} distance
* @param {number} start
* @param {number} destination
* @return {number}
*/
var distanceBetweenBusStops = function(distance, start, destination) {
}; | A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given start and destination stops.
Example 1:
Input: distance = [1,2,3,4], start = 0, destination = 1
Output: 1
Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
Example 2:
Input: distance = [1,2,3,4], start = 0, destination = 2
Output: 3
Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.
Example 3:
Input: distance = [1,2,3,4], start = 0, destination = 3
Output: 4
Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.
Constraints:
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
| Easy | [
"array"
] | [
"const distanceBetweenBusStops = function(distance, start, destination) {\n if (start > destination) {\n let temp = start\n start = destination\n destination = temp\n }\n let res = 0,\n total = 0\n for (let i = 0; i < distance.length; i++) {\n if (i >= start && i < destination) {\n res += distance[i]\n }\n total += distance[i]\n }\n return Math.min(res, total - res)\n}"
] |
|
1,185 | day-of-the-week | [
"Sum up the number of days for the years before the given year.",
"Handle the case of a leap year.",
"Find the number of days for each month of the given year."
] | /**
* @param {number} day
* @param {number} month
* @param {number} year
* @return {string}
*/
var dayOfTheWeek = function(day, month, year) {
}; | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the day, month and year respectively.
Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.
Example 1:
Input: day = 31, month = 8, year = 2019
Output: "Saturday"
Example 2:
Input: day = 18, month = 7, year = 1999
Output: "Sunday"
Example 3:
Input: day = 15, month = 8, year = 1993
Output: "Sunday"
Constraints:
The given dates are valid dates between the years 1971 and 2100.
| Easy | [
"math"
] | [
"const dayOfTheWeek = function(day, month, year) {\n const weekdays = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n const date = new Date(year,month-1,day).getDay();\n return weekdays[date];\n};"
] |
|
1,186 | maximum-subarray-sum-with-one-deletion | [
"How to solve this problem if no deletions are allowed ?",
"Try deleting each element and find the maximum subarray sum to both sides of that element.",
"To do that efficiently, use the idea of Kadane's algorithm."
] | /**
* @param {number[]} arr
* @return {number}
*/
var maximumSum = function(arr) {
}; | Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be non-empty after deleting one element.
Example 1:
Input: arr = [1,-2,0,3]
Output: 4
Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.
Example 2:
Input: arr = [1,-2,-2,3]
Output: 3
Explanation: We just choose [3] and it's the maximum sum.
Example 3:
Input: arr = [-1,-1,-1,-1]
Output: -1
Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
Constraints:
1 <= arr.length <= 105
-104 <= arr[i] <= 104
| Medium | [
"array",
"dynamic-programming"
] | [
"const maximumSum = function (arr) {\n const n = arr.length\n let oneDel = 0, noDel = arr[0], res = arr[0]\n\n for(let i = 1; i < n; i++) {\n oneDel = Math.max(noDel, oneDel + arr[i])\n noDel = Math.max(arr[i], noDel + arr[i])\n res = Math.max(res, oneDel, noDel)\n }\n\n return res\n}",
"const maximumSum = function (arr) {\n const n = arr.length\n let max = arr[0]\n const maxEndAt = Array(n), maxStartAt = Array(n)\n maxEndAt[0] = arr[0]\n for(let i = 1; i < n; i++) {\n maxEndAt[i] = Math.max(arr[i], maxEndAt[i - 1] + arr[i])\n max = Math.max(max, maxEndAt[i])\n }\n maxStartAt[n - 1] = arr[n - 1]\n for(let i = n - 2; i >= 0; i--) {\n maxStartAt[i] = Math.max(arr[i], maxStartAt[i + 1] + arr[i])\n }\n let res = Math.max(maxStartAt[0], maxEndAt[n - 1])\n for(let i = 1; i < n - 1; i++) {\n res = Math.max(max, res, maxEndAt[i - 1] + maxStartAt[i + 1])\n }\n return res\n}"
] |
|
1,187 | make-array-strictly-increasing | [
"Use dynamic programming.",
"The state would be the index in arr1 and the index of the previous element in arr2 after sorting it and removing duplicates."
] | /**
* @param {number[]} arr1
* @param {number[]} arr2
* @return {number}
*/
var makeArrayIncreasing = function(arr1, arr2) {
}; | Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing.
In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j].
If there is no way to make arr1 strictly increasing, return -1.
Example 1:
Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
Output: 1
Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7].
Example 2:
Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1]
Output: 2
Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7].
Example 3:
Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
Output: -1
Explanation: You can't make arr1 strictly increasing.
Constraints:
1 <= arr1.length, arr2.length <= 2000
0 <= arr1[i], arr2[i] <= 10^9
| Hard | [
"array",
"binary-search",
"dynamic-programming",
"sorting"
] | [
"const makeArrayIncreasing = function(arr1, arr2) {\n arr2.sort((a, b) => a - b)\n let arr3 = [arr2[0]]\n for (let i = 1; i < arr2.length; i++) {\n if (arr2[i] > arr2[i - 1]) {\n arr3.push(arr2[i])\n }\n }\n arr2 = arr3\n let n = arr1.length\n let indexMap = new Array(n * 2 + 2)\n for (let i = 0; i < n; i++) {\n let ai = arr1[i]\n let li = findLarger(arr2, ai)\n indexMap[i * 2] = li\n indexMap[i * 2 + 1] = arr2[li - 1] === ai ? li - 2 : li - 1\n }\n indexMap[n * 2] = arr2.length\n indexMap[n * 2 + 1] = arr2.length - 1\n let dp = new Array(n + 1)\n let MaxNum = 1000000000 + 1\n dp[0] = 0\n for (let i = 1; i < n + 1; i++) {\n let min = i\n let ai = i === n ? MaxNum : arr1[i]\n for (let j = 0; j < i; j++) {\n if (dp[j] == -1 || ai <= arr1[j]) {\n continue\n }\n if (indexMap[i * 2 + 1] - indexMap[j * 2] + 1 < i - j - 1) continue\n min = Math.min(min, dp[j] + i - j - 1)\n }\n if (min === i) {\n if (indexMap[i * 2 + 1] + 1 < i) {\n min = -1\n }\n }\n dp[i] = min\n }\n return dp[n]\n}\nconst findLarger = function(arr, a) {\n if (a > arr[arr.length - 1]) return arr.length\n let l = 0\n let r = arr.length - 1\n while (l < r) {\n let mid = (l + r) >> 1\n if (arr[mid] <= a) {\n l = mid + 1\n } else {\n r = mid\n }\n }\n return l\n}"
] |
|
1,189 | maximum-number-of-balloons | [
"Count the frequency of letters in the given string.",
"Find the letter than can make the minimum number of instances of the word \"balloon\"."
] | /**
* @param {string} text
* @return {number}
*/
var maxNumberOfBalloons = function(text) {
}; | Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
Example 1:
Input: text = "nlaebolko"
Output: 1
Example 2:
Input: text = "loonbalxballpoon"
Output: 2
Example 3:
Input: text = "leetcode"
Output: 0
Constraints:
1 <= text.length <= 104
text consists of lower case English letters only.
| Easy | [
"hash-table",
"string",
"counting"
] | [
"const maxNumberOfBalloons = function(text) {\n const cnt = [...text].reduce((A, ch) => {\n A[ch] = (A[ch] || 0) + 1;\n return A;\n }, {});\n const ans = Math.min(cnt['b'], cnt['a'], cnt['l'] / 2, cnt['o'] / 2, cnt['n']);\n return ans ? Math.floor(ans) : 0;\n};"
] |
|
1,190 | reverse-substrings-between-each-pair-of-parentheses | [
"Find all brackets in the string.",
"Does the order of the reverse matter ?",
"The order does not matter."
] | /**
* @param {string} s
* @return {string}
*/
var reverseParentheses = function(s) {
}; | You are given a string s that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
Your result should not contain any brackets.
Example 1:
Input: s = "(abcd)"
Output: "dcba"
Example 2:
Input: s = "(u(love)i)"
Output: "iloveu"
Explanation: The substring "love" is reversed first, then the whole string is reversed.
Example 3:
Input: s = "(ed(et(oc))el)"
Output: "leetcode"
Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.
Constraints:
1 <= s.length <= 2000
s only contains lower case English characters and parentheses.
It is guaranteed that all parentheses are balanced.
| Medium | [
"string",
"stack"
] | [
"const reverseParentheses = function(s) {\n const res = ['']\n let control = 0\n let order = 1\n for (let i = 0; i < s.length; i++) {\n if (s[i] === '(') {\n control++\n order = order ? 0 : 1\n res.push('')\n } else if (s[i] === ')') {\n if (order) res[control - 1] = res.pop() + res[control - 1]\n else res[control - 1] = res[control - 1] + res.pop()\n order = order ? 0 : 1\n control--\n } else {\n if (order) res[control] = res[control] + s[i]\n else res[control] = s[i] + res[control]\n }\n }\n return res[0]\n}",
"const reverseParentheses = function(s) {\n const n = s.length\n const stack = []\n const pair = []\n for(let i = 0; i < n; i++) {\n if(s[i] === '(') stack.push(i)\n else if(s[i] === ')') {\n const tmp = stack.pop()\n pair[i] = tmp\n pair[tmp] = i\n }\n }\n let res = ''\n for(let i = 0, d = 1; i < n; i += d) {\n if(s[i] === '(' || s[i] ===')') {\n i = pair[i]\n d = -d\n } else {\n res += s[i]\n }\n }\n return res\n}"
] |
|
1,191 | k-concatenation-maximum-sum | [
"How to solve the problem for k=1 ?",
"Use Kadane's algorithm for k=1.",
"What are the possible cases for the answer ?",
"The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1."
] | /**
* @param {number[]} arr
* @param {number} k
* @return {number}
*/
var kConcatenationMaxSum = function(arr, k) {
}; | Given an integer array arr and an integer k, modify the array by repeating it k times.
For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].
Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.
As the answer can be very large, return the answer modulo 109 + 7.
Example 1:
Input: arr = [1,2], k = 3
Output: 9
Example 2:
Input: arr = [1,-2,1], k = 5
Output: 2
Example 3:
Input: arr = [-1,-2], k = 7
Output: 0
Constraints:
1 <= arr.length <= 105
1 <= k <= 105
-104 <= arr[i] <= 104
| Medium | [
"array",
"dynamic-programming"
] | [
"const kConcatenationMaxSum = function(arr, k) {\n const MOD = 1e9 + 7,\n INF = 1e4 + 1;\n const kadane = (A, sum = 0, ans = -INF) => {\n for (let x of A) {\n sum = Math.max(0, sum + x);\n ans = Math.max(ans, sum);\n }\n return [sum, ans];\n };\n const [sum1, ans1] = kadane(arr);\n const [sum2, ans2] = kadane(arr, sum1);\n const [sum3, ans3] = kadane(arr, sum2);\n const delta1 = ans2 - ans1,\n delta2 = ans3 - ans2;\n return k == 1 || delta1 == 0\n ? ans1\n : delta2 == 0\n ? ans2\n : ans1 + ((delta1 * (k - 1)) % MOD);\n};"
] |
|
1,192 | critical-connections-in-a-network | [
"Use Tarjan's algorithm."
] | /**
* @param {number} n
* @param {number[][]} connections
* @return {number[][]}
*/
var criticalConnections = function(n, connections) {
}; | There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network.
A critical connection is a connection that, if removed, will make some servers unable to reach some other server.
Return all critical connections in the network in any order.
Example 1:
Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
Output: [[1,3]]
Explanation: [[3,1]] is also accepted.
Example 2:
Input: n = 2, connections = [[0,1]]
Output: [[0,1]]
Constraints:
2 <= n <= 105
n - 1 <= connections.length <= 105
0 <= ai, bi <= n - 1
ai != bi
There are no repeated connections.
| Hard | [
"depth-first-search",
"graph",
"biconnected-component"
] | [
"const criticalConnections = function(n, connections) {\n const g = [],\n low = Array(n),\n res = []\n low.fill(0)\n for (let con of connections) {\n g[con[0]] = g[con[0]] || []\n g[con[1]] = g[con[1]] || []\n g[con[0]].push(con[1])\n g[con[1]].push(con[0])\n }\n const dfs = function(cur, v, p) {\n let dfn = cur\n low[v] = cur\n for (let i of g[v]) {\n if (i != p) {\n if (low[i] == 0) {\n cur++\n dfs(cur, i, v)\n if (low[i] > dfn) {\n res.push([i, v])\n }\n }\n low[v] = Math.min(low[v], low[i])\n }\n }\n }\n dfs(1, 0, -1)\n return res\n}"
] |
|
1,200 | minimum-absolute-difference | [
"Find the minimum absolute difference between two elements in the array.",
"The minimum absolute difference must be a difference between two consecutive elements in the sorted array."
] | /**
* @param {number[]} arr
* @return {number[][]}
*/
var minimumAbsDifference = function(arr) {
}; | Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows
a, b are from arr
a < b
b - a equals to the minimum absolute difference of any two elements in arr
Example 1:
Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
Example 2:
Input: arr = [1,3,6,10,15]
Output: [[1,3]]
Example 3:
Input: arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]
Constraints:
2 <= arr.length <= 105
-106 <= arr[i] <= 106
| Easy | [
"array",
"sorting"
] | [
"const minimumAbsDifference = function(arr) {\n arr.sort((a, b) => a - b)\n let min = Number.MAX_VALUE\n for(let i = 1, len = arr.length; i < len; i++) {\n if(arr[i] - arr[i - 1] < min) min = arr[i] - arr[i - 1]\n }\n const res = []\n for(let i = 1, len = arr.length; i < len; i++) {\n if(arr[i] - arr[i - 1] === min) res.push([arr[i - 1], arr[i]])\n }\n return res\n};"
] |
|
1,201 | ugly-number-iii | [
"Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search.",
"Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result."
] | /**
* @param {number} n
* @param {number} a
* @param {number} b
* @param {number} c
* @return {number}
*/
var nthUglyNumber = function(n, a, b, c) {
}; | An ugly number is a positive integer that is divisible by a, b, or c.
Given four integers n, a, b, and c, return the nth ugly number.
Example 1:
Input: n = 3, a = 2, b = 3, c = 5
Output: 4
Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.
Example 2:
Input: n = 4, a = 2, b = 3, c = 4
Output: 6
Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6.
Example 3:
Input: n = 5, a = 2, b = 11, c = 13
Output: 10
Explanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.
Constraints:
1 <= n, a, b, c <= 109
1 <= a * b * c <= 1018
It is guaranteed that the result will be in range [1, 2 * 109].
| Medium | [
"math",
"binary-search",
"number-theory"
] | [
"const nthUglyNumber = function(n, a, b, c) {\n let lo = 1, hi = 2 * 1e9;\n const { floor: f } = Math\n let ab = a * b / gcd(a, b);\n let bc = b * c / gcd(b, c);\n let ac = a * c / gcd(a, c);\n let abc = a * bc / gcd(a, bc);\n while(lo < hi) {\n let mid = lo + Math.floor((hi - lo) / 2);\n if(valid(mid)) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n\n function valid(mid) {\n let res = f(mid / a) + f(mid / b) + f(mid / c) - f(mid / ab) - f(mid / bc) - f(mid / ac) + f(mid / abc)\n return res >= n\n }\n\n function gcd(a, b) {\n return b === 0 ? a : gcd(b, a % b)\n }\n};"
] |
|
1,202 | smallest-string-with-swaps | [
"Think of it as a graph problem.",
"Consider the pairs as connected nodes in the graph, what can you do with a connected component of indices ?",
"We can sort each connected component alone to get the lexicographically minimum string."
] | /**
* @param {string} s
* @param {number[][]} pairs
* @return {string}
*/
var smallestStringWithSwaps = function(s, pairs) {
}; | You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smallest string that s can be changed to after using the swaps.
Example 1:
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"
Example 2:
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"
Example 3:
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explaination:
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"
Constraints:
1 <= s.length <= 10^5
0 <= pairs.length <= 10^5
0 <= pairs[i][0], pairs[i][1] < s.length
s only contains lower case English letters.
| Medium | [
"array",
"hash-table",
"string",
"depth-first-search",
"breadth-first-search",
"union-find",
"sorting"
] | [
"const smallestStringWithSwaps = function(s, pairs) {\n let set = Array(s.length).fill(-1)\n function union(a, b) {\n let root1 = find(a)\n let root2 = find(b)\n if (root1 !== root2) {\n set[root2] = root1\n }\n }\n function find(a) {\n if (set[a] < 0) {\n return a\n } else {\n return (set[a] = find(set[a]))\n }\n }\n for (let pair of pairs) {\n union(pair[0], pair[1])\n }\n let groups = []\n for (let i = 0; i < s.length; i++) {\n groups[i] = []\n }\n for (let i = 0; i < s.length; i++) {\n groups[find(i)].push(i)\n }\n let sArr = s.split('')\n for (let i = 0; i < s.length; i++) {\n if (groups[i].length > 1) {\n let chars = groups[i].map(idx => s[idx])\n chars.sort()\n for (let k = 0; k < groups[i].length; k++) {\n sArr[groups[i][k]] = chars[k]\n }\n }\n }\n return sArr.join('')\n}"
] |
|
1,203 | sort-items-by-groups-respecting-dependencies | [
"Think of it as a graph problem.",
"We need to find a topological order on the dependency graph.",
"Build two graphs, one for the groups and another for the items."
] | /**
* @param {number} n
* @param {number} m
* @param {number[]} group
* @param {number[][]} beforeItems
* @return {number[]}
*/
var sortItems = function(n, m, group, beforeItems) {
}; | There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that:
The items that belong to the same group are next to each other in the sorted list.
There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item).
Return any solution if there is more than one solution and return an empty list if there is no solution.
Example 1:
Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]
Output: [6,3,4,1,5,2,0,7]
Example 2:
Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]
Output: []
Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.
Constraints:
1 <= m <= n <= 3 * 104
group.length == beforeItems.length == n
-1 <= group[i] <= m - 1
0 <= beforeItems[i].length <= n - 1
0 <= beforeItems[i][j] <= n - 1
i != beforeItems[i][j]
beforeItems[i] does not contain duplicates elements.
| Hard | [
"depth-first-search",
"breadth-first-search",
"graph",
"topological-sort"
] | [
"const sortItems = function (n, m, group, beforeItems) {\n const graph = Array.from({ length: m + n }, () => [])\n const indegree = Array(n + m).fill(0)\n for (let i = 0; i < group.length; i++) {\n if (group[i] == -1) continue\n graph[n + group[i]].push(i)\n indegree[i]++\n }\n for (let i = 0; i < beforeItems.length; i++) {\n for (const e of beforeItems[i]) {\n const a = group[e] === -1 ? e : n + group[e]\n const b = group[i] === -1 ? i : n + group[i]\n if (a === b) {\n // same group, ingroup order\n graph[e].push(i)\n indegree[i]++\n } else {\n // outgoup order\n graph[a].push(b)\n indegree[b]++\n }\n }\n }\n const res = []\n for (let i = 0; i < n + m; i++) {\n if (indegree[i] === 0) dfs(res, graph, indegree, n, i)\n }\n return res.length === n ? res : []\n\n function dfs(ans, graph, indegree, n, cur) {\n if (cur < n) ans.push(cur)\n indegree[cur] = -1 // mark it visited\n for (let next of graph[cur] || []) {\n indegree[next]--\n if (indegree[next] === 0) dfs(ans, graph, indegree, n, next)\n }\n }\n}",
"const sortItems = function (n, m, group, beforeItems) {\n const vertexs = new Map()\n const groupVertexs = new Map()\n let groupNo = m\n for (let i = 0; i < n; i++) {\n vertexs.set(i, {\n neighbors: new Set(),\n indegree: 0,\n })\n if (group[i] === -1) {\n group[i] = groupNo++\n }\n if (!groupVertexs.has(group[i])) {\n groupVertexs.set(group[i], {\n v: new Set(),\n neighbors: new Set(),\n indegree: 0,\n })\n }\n groupVertexs.get(group[i]).v.add(i)\n }\n\n for (let i = 0; i < n; i++) {\n for (const before of beforeItems[i]) {\n if (!vertexs.get(before).neighbors.has(i)) {\n vertexs.get(i).indegree += 1\n }\n vertexs.get(before).neighbors.add(i)\n\n const groupOfBefore = group[before]\n if (groupOfBefore === group[i]) continue\n if (!groupVertexs.get(groupOfBefore).neighbors.has(group[i])) {\n groupVertexs.get(group[i]).indegree += 1\n }\n groupVertexs.get(groupOfBefore).neighbors.add(group[i])\n }\n }\n\n const zeroGroup = []\n for (const group of groupVertexs) {\n if (group[1].indegree === 0) {\n zeroGroup.push(group[0])\n }\n }\n const result = []\n let cntGroup = 0\n let cntV = 0\n const groupTotal = groupVertexs.size\n\n while (zeroGroup.length) {\n const top = zeroGroup.pop()\n cntGroup += 1\n const v = groupVertexs.get(top).v\n const total = v.size\n const zero = []\n\n for (const i of v) {\n if (vertexs.get(i).indegree === 0) {\n zero.push(i)\n }\n }\n while (zero.length) {\n const it = zero.pop()\n result.push(it)\n for (const n of vertexs.get(it).neighbors) {\n vertexs.get(n).indegree -= 1\n if (v.has(n) && vertexs.get(n).indegree === 0) {\n zero.push(n)\n }\n }\n }\n if (result.length - cntV !== total) {\n return []\n }\n cntV = result.length\n\n for (const groupneigbor of groupVertexs.get(top).neighbors) {\n groupVertexs.get(groupneigbor).indegree -= 1\n if (groupVertexs.get(groupneigbor).indegree === 0) {\n zeroGroup.push(groupneigbor)\n }\n }\n }\n\n return cntGroup === groupTotal ? result : []\n}"
] |
|
1,206 | design-skiplist | [] |
var Skiplist = function() {
};
/**
* @param {number} target
* @return {boolean}
*/
Skiplist.prototype.search = function(target) {
};
/**
* @param {number} num
* @return {void}
*/
Skiplist.prototype.add = function(num) {
};
/**
* @param {number} num
* @return {boolean}
*/
Skiplist.prototype.erase = function(num) {
};
/**
* Your Skiplist object will be instantiated and called as such:
* var obj = new Skiplist()
* var param_1 = obj.search(target)
* obj.add(num)
* var param_3 = obj.erase(num)
*/ | Design a Skiplist without using any built-in libraries.
A skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists.
For example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way:
Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons
You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).
See more about Skiplist: https://en.wikipedia.org/wiki/Skip_list
Implement the Skiplist class:
Skiplist() Initializes the object of the skiplist.
bool search(int target) Returns true if the integer target exists in the Skiplist or false otherwise.
void add(int num) Inserts the value num into the SkipList.
bool erase(int num) Removes the value num from the Skiplist and returns true. If num does not exist in the Skiplist, do nothing and return false. If there exist multiple num values, removing any one of them is fine.
Note that duplicates may exist in the Skiplist, your code needs to handle this situation.
Example 1:
Input
["Skiplist", "add", "add", "add", "search", "add", "search", "erase", "erase", "search"]
[[], [1], [2], [3], [0], [4], [1], [0], [1], [1]]
Output
[null, null, null, null, false, null, true, false, true, false]
Explanation
Skiplist skiplist = new Skiplist();
skiplist.add(1);
skiplist.add(2);
skiplist.add(3);
skiplist.search(0); // return False
skiplist.add(4);
skiplist.search(1); // return True
skiplist.erase(0); // return False, 0 is not in skiplist.
skiplist.erase(1); // return True
skiplist.search(1); // return False, 1 has already been erased.
Constraints:
0 <= num, target <= 2 * 104
At most 5 * 104 calls will be made to search, add, and erase.
| Hard | [
"linked-list",
"design"
] | [
"class Skiplist {\n constructor() {\n this.head = { down: null, right: null, val: -Infinity }\n }\n search(val) {\n let curr = this.head\n while (curr) {\n while (curr.right && curr.right.val <= val) {\n curr = curr.right\n }\n if (curr.val == val) {\n return true\n }\n curr = curr.down\n }\n return false\n }\n add(val) {\n let curr = this.head\n const insertion_positions = []\n while (curr) {\n while (curr.right && curr.right.val < val) {\n curr = curr.right\n }\n insertion_positions.push(curr)\n curr = curr.down\n }\n let insert = true\n let down = null\n while (insert && insertion_positions.length) {\n const position = insertion_positions.pop()\n const node = { down, val, right: position.right }\n position.right = node\n down = node\n insert = Math.random() < 0.5\n }\n if (insert) {\n const node = { val, down }\n this.head = { val: -Infinity, right: node, down: this.head }\n }\n }\n erase(val) {\n let curr = this.head\n const erase_positions = []\n while (curr) {\n while (curr.right && curr.right.val < val) {\n curr = curr.right\n }\n if (curr.right && curr.right.val == val) {\n erase_positions.push(curr)\n }\n curr = curr.down\n }\n const seen = erase_positions.length > 0\n for (const position of erase_positions) {\n position.right = position.right && position.right.right\n }\n return seen\n }\n}",
"const Skiplist = function () {\n this.maxLvl = ~~Math.log2(20000)\n this.levels = [...Array(this.maxLvl)].map(() => new Node(-1))\n for (let i = this.maxLvl - 1; i > 0; i--) {\n this.levels[i].down = this.levels[i - 1]\n }\n this.head = this.levels[this.maxLvl - 1]\n}\n\n\nSkiplist.prototype.search = function (target) {\n const pre = this.iter(target)\n return !pre[0].next ? false : pre[0].next.val === target\n}\n\nSkiplist.prototype.iter = function (target) {\n let cur = this.head\n const pre = []\n for (let i = this.maxLvl - 1; i >= 0; i--) {\n while (cur.next && cur.next.val < target) cur = cur.next\n pre[i] = cur\n cur = cur.down\n }\n return pre\n}\n\n\nSkiplist.prototype.add = function (num) {\n const pre = this.iter(num)\n const lvs = decideLevels(this.maxLvl)\n for (let i = 0; i < lvs; i++) {\n const next = pre[i].next\n pre[i].next = new Node(num)\n pre[i].next.next = next\n if (i > 0) pre[i].next.down = pre[i - 1].next\n }\n}\n\n\nSkiplist.prototype.erase = function (num) {\n const pre = this.iter(num)\n let ret\n if (!pre[0].next || pre[0].next.val !== num) return false\n for (let i = this.maxLvl - 1; i >= 0; i--) {\n if (pre[i].next && pre[i].next.val === num) {\n const toBeDeleted = pre[i].next\n pre[i].next = toBeDeleted.next\n toBeDeleted.next = null\n toBeDeleted.down = null\n }\n }\n return true\n}\n\n\n\nconst decideLevels = (max) => {\n let ans = 1\n while (Math.random() > 0.5 && ans < max) ans++\n return ans\n}\n\nconst Node = function (val) {\n this.val = val\n this.next = null\n this.down = null\n}"
] |
|
1,207 | unique-number-of-occurrences | [
"Find the number of occurrences of each element in the array using a hash map.",
"Iterate through the hash map and check if there is a repeated value."
] | /**
* @param {number[]} arr
* @return {boolean}
*/
var uniqueOccurrences = function(arr) {
}; | Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.
Example 1:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example 2:
Input: arr = [1,2]
Output: false
Example 3:
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true
Constraints:
1 <= arr.length <= 1000
-1000 <= arr[i] <= 1000
| Easy | [
"array",
"hash-table"
] | [
"const uniqueOccurrences = function(arr) {\n const hash = {}\n for(let e of arr) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n const ks = new Set(Object.keys(hash)), vs = new Set(Object.values(hash))\n return ks.size === vs.size\n};"
] |
|
1,208 | get-equal-substrings-within-budget | [
"Calculate the differences between a[i] and b[i].",
"Use a sliding window to track the longest valid substring."
] | /**
* @param {string} s
* @param {string} t
* @param {number} maxCost
* @return {number}
*/
var equalSubstring = function(s, t, maxCost) {
}; | You are given two strings s and t of the same length and an integer maxCost.
You want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters).
Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0.
Example 1:
Input: s = "abcd", t = "bcdf", maxCost = 3
Output: 3
Explanation: "abc" of s can change to "bcd".
That costs 3, so the maximum length is 3.
Example 2:
Input: s = "abcd", t = "cdef", maxCost = 3
Output: 1
Explanation: Each character in s costs 2 to change to character in t, so the maximum length is 1.
Example 3:
Input: s = "abcd", t = "acde", maxCost = 0
Output: 1
Explanation: You cannot make any change, so the maximum length is 1.
Constraints:
1 <= s.length <= 105
t.length == s.length
0 <= maxCost <= 106
s and t consist of only lowercase English letters.
| Medium | [
"string",
"binary-search",
"sliding-window",
"prefix-sum"
] | null | [] |
1,209 | remove-all-adjacent-duplicates-in-string-ii | [
"Use a stack to store the characters, when there are k same characters, delete them.",
"To make it more efficient, use a pair to store the value and the count of each character."
] | /**
* @param {string} s
* @param {number} k
* @return {string}
*/
var removeDuplicates = function(s, k) {
}; | You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 105
2 <= k <= 104
s only contains lowercase English letters.
| Medium | [
"string",
"stack"
] | [
"const removeDuplicates = function (s, k) {\n const stack = [];\n const arr = s.split('')\n for(let i = 0; i < arr.length; i++) {\n if(i === 0 || arr[i] !== arr[i - 1]) {\n stack.push(1)\n } else {\n stack[stack.length - 1]++\n if(stack[stack.length - 1] === k) {\n stack.pop()\n arr.splice(i - k + 1, k)\n i -= k\n }\n }\n \n }\n return arr.join('')\n};",
"const removeDuplicates = function (s, k) {\n const stack = [];\n s = s.split('');\n for (let i = 0; i < s.length;) {\n if (i === 0 || s[i] !== s[i - 1]) {\n stack.push(1);\n i++\n } else {\n stack[stack.length - 1]++;\n if (stack[stack.length - 1] === k) {\n stack.pop();\n s.splice(i - k + 1, k);\n i = i - k + 1;\n } else {\n i++\n }\n }\n }\n return s.join('');\n};"
] |
|
1,210 | minimum-moves-to-reach-target-with-rotations | [
"Use BFS to find the answer.",
"The state of the BFS is the position (x, y) along with a binary value that specifies if the position is horizontal or vertical."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var minimumMoves = function(grid) {
}; | In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1).
In one move the snake can:
Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.
Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.
Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c).
Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1).
Return the minimum number of moves to reach the target.
If there is no way to reach the target, return -1.
Example 1:
Input: grid = [[0,0,0,0,0,1],
[1,1,0,0,1,0],
[0,0,0,0,1,1],
[0,0,1,0,1,0],
[0,1,1,0,0,0],
[0,1,1,0,0,0]]
Output: 11
Explanation:
One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].
Example 2:
Input: grid = [[0,0,1,1,1,1],
[0,0,0,0,1,1],
[1,1,0,0,0,1],
[1,1,1,0,0,1],
[1,1,1,0,0,1],
[1,1,1,0,0,0]]
Output: 9
Constraints:
2 <= n <= 100
0 <= grid[i][j] <= 1
It is guaranteed that the snake starts at empty cells.
| Hard | [
"array",
"breadth-first-search",
"matrix"
] | [
"const minimumMoves = function (grid) {\n const n = grid.length;\n const start = [0, 0, 0, 1].join(',');\n const end = [n - 1, n - 2, n - 1, n - 1].join(\",\");\n let curr_level = new Set([start]);\n let moves = 0;\n const visited = new Set();\n while (curr_level.size) {\n const next_level = new Set();\n for (let pos of curr_level) {\n visited.add(pos);\n let [r1, c1, r2, c2] = pos.split(\",\").map((e) => +e);\n if (\n c1 + 1 < n &&\n grid[r1][c1 + 1] == 0 &&\n c2 + 1 < n &&\n grid[r2][c2 + 1] == 0\n ) {\n const coord = [r1, c1 + 1, r2, c2 + 1].join(\",\");\n if (!visited.has(coord)) {\n next_level.add(coord);\n }\n }\n if (\n r1 + 1 < n &&\n grid[r1 + 1][c1] == 0 &&\n r2 + 1 < n &&\n grid[r2 + 1][c2] == 0\n ) {\n const coord = [r1 + 1, c1, r2 + 1, c2].join(\",\");\n if (!visited.has(coord)) {\n next_level.add(coord);\n }\n }\n if (\n r1 == r2 &&\n c2 == c1 + 1 &&\n r1 + 1 < n &&\n grid[r1 + 1][c1] + grid[r1 + 1][c1 + 1] == 0\n ) {\n const coord = [r1, c1, r1 + 1, c1].join(\",\");\n if (!visited.has(coord)) {\n next_level.add(coord);\n }\n }\n if (\n c1 == c2 &&\n r2 == r1 + 1 &&\n c1 + 1 < n &&\n grid[r1][c1 + 1] + grid[r1 + 1][c1 + 1] == 0\n ) {\n const coord = [r1, c1, r1, c1 + 1].join(\",\");\n if (!visited.has(coord)) {\n next_level.add(coord);\n }\n }\n }\n if (next_level.has(end)) {\n return moves + 1;\n }\n curr_level = next_level;\n moves += 1;\n }\n return -1;\n};"
] |
|
1,217 | minimum-cost-to-move-chips-to-the-same-position | [
"The first move keeps the parity of the element as it is.",
"The second move changes the parity of the element.",
"Since the first move is free, if all the numbers have the same parity, the answer would be zero.",
"Find the minimum cost to make all the numbers have the same parity."
] | /**
* @param {number[]} position
* @return {number}
*/
var minCostToMoveChips = function(position) {
}; | We have n chips, where the position of the ith chip is position[i].
We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:
position[i] + 2 or position[i] - 2 with cost = 0.
position[i] + 1 or position[i] - 1 with cost = 1.
Return the minimum cost needed to move all the chips to the same position.
Example 1:
Input: position = [1,2,3]
Output: 1
Explanation: First step: Move the chip at position 3 to position 1 with cost = 0.
Second step: Move the chip at position 2 to position 1 with cost = 1.
Total cost is 1.
Example 2:
Input: position = [2,2,2,3,3]
Output: 2
Explanation: We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2.
Example 3:
Input: position = [1,1000000000]
Output: 1
Constraints:
1 <= position.length <= 100
1 <= position[i] <= 10^9
| Easy | [
"array",
"math",
"greedy"
] | [
"const minCostToMoveChips = function(position) {\n let oddSum = 0, evenSum = 0\n for(let i = 0; i < position.length; i++) {\n if(position[i] % 2 === 0) evenSum++\n else oddSum++\n }\n return Math.min(oddSum, evenSum)\n};"
] |
|
1,218 | longest-arithmetic-subsequence-of-given-difference | [
"Use dynamic programming.",
"Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i.",
"dp[i] = 1 + dp[i-k]"
] | /**
* @param {number[]} arr
* @param {number} difference
* @return {number}
*/
var longestSubsequence = function(arr, difference) {
}; | Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.
A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].
Example 2:
Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The longest arithmetic subsequence is any single element.
Example 3:
Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
Explanation: The longest arithmetic subsequence is [7,5,3,1].
Constraints:
1 <= arr.length <= 105
-104 <= arr[i], difference <= 104
| Medium | [
"array",
"hash-table",
"dynamic-programming"
] | null | [] |
1,219 | path-with-maximum-gold | [
"Use recursion to try all such paths and find the one with the maximum value."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var getMaximumGold = function(grid) {
}; | In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.
Return the maximum amount of gold you can collect under the conditions:
Every time you are located in a cell you will collect all the gold in that cell.
From your position, you can walk one step to the left, right, up, or down.
You can't visit the same cell more than once.
Never visit a cell with 0 gold.
You can start and stop collecting gold from any position in the grid that has some gold.
Example 1:
Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24
Explanation:
[[0,6,0],
[5,8,7],
[0,9,0]]
Path to get the maximum gold, 9 -> 8 -> 7.
Example 2:
Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
Output: 28
Explanation:
[[1,0,7],
[2,0,6],
[3,4,5],
[0,3,0],
[9,0,20]]
Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 15
0 <= grid[i][j] <= 100
There are at most 25 cells containing gold.
| Medium | [
"array",
"backtracking",
"matrix"
] | [
"const getMaximumGold = function(grid) {\n const m = grid.length, n = grid[0].length\n const arr = []\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n const visited = new Set()\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j] !== 0) arr.push([i, j])\n }\n }\n let res = 0\n \n for(const [i, j] of arr) {\n visited.clear()\n visited.add(`${i},${j}`)\n dfs(i, j, grid[i][j])\n }\n \n return res\n \n function dfs(i, j, cur) {\n\n res = Math.max(res, cur)\n for(const [dx, dy] of dirs) {\n const nx = i + dx\n const ny = j + dy\n const key = `${nx},${ny}`\n if(nx >= 0 && nx < m && ny >= 0 && ny < n && !visited.has(key) && grid[nx][ny] !== 0) {\n visited.add(key)\n dfs(nx, ny, cur + grid[nx][ny])\n visited.delete(key)\n }\n }\n }\n \n};",
"var getMaximumGold = function (grid) {\n const m = grid.length\n const n = grid[0].length\n let max = 0\n\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] != 0) {\n const sum = backtrack(grid, i, j, m, n)\n max = Math.max(sum, max)\n }\n }\n }\n\n return max\n}\n\nfunction backtrack(grid, row, col, m, n) {\n if (outOfBound(row, col, m, n) || grid[row][col] === 0) return 0\n\n let sum = grid[row][col]\n grid[row][col] = 0 // mark as being visited already\n\n const top = backtrack(grid, row - 1, col, m, n)\n const right = backtrack(grid, row, col + 1, m, n)\n const bot = backtrack(grid, row + 1, col, m, n)\n const left = backtrack(grid, row, col - 1, m, n)\n\n grid[row][col] = sum // backtrack to the original form\n\n return sum + Math.max(top, right, bot, left)\n}\n\nfunction outOfBound(row, col, m, n) {\n return row < 0 || col < 0 || row >= m || col >= n\n}"
] |
|
1,220 | count-vowels-permutation | [
"Use dynamic programming.",
"Let dp[i][j] be the number of strings of length i that ends with the j-th vowel.",
"Deduce the recurrence from the given relations between vowels."
] | /**
* @param {number} n
* @return {number}
*/
var countVowelPermutation = function(n) {
}; | Given an integer n, your task is to count how many strings of length n can be formed under the following rules:
Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u')
Each vowel 'a' may only be followed by an 'e'.
Each vowel 'e' may only be followed by an 'a' or an 'i'.
Each vowel 'i' may not be followed by another 'i'.
Each vowel 'o' may only be followed by an 'i' or a 'u'.
Each vowel 'u' may only be followed by an 'a'.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: n = 1
Output: 5
Explanation: All possible strings are: "a", "e", "i" , "o" and "u".
Example 2:
Input: n = 2
Output: 10
Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua".
Example 3:
Input: n = 5
Output: 68
Constraints:
1 <= n <= 2 * 10^4
| Hard | [
"dynamic-programming"
] | [
"const countVowelPermutation = function (n) {\n const mod = 1e9 + 7\n const arr = [\n [0, 1, 1], // a -> e\n [0, 1, 2], // e -> a, i\n [0, 1, 4], // i -> a, e, o, u\n [0, 1, 2], // o -> i, u\n [0, 1, 1], // u -> a\n ]\n for (let i = 3; i <= n; i++) {\n arr[0][i % 3] = arr[1][(i - 1) % 3] % mod\n arr[1][i % 3] = (arr[0][(i - 1) % 3] + arr[2][(i - 1) % 3]) % mod\n arr[2][i % 3] =\n (arr[0][(i - 1) % 3] +\n arr[1][(i - 1) % 3] +\n arr[3][(i - 1) % 3] +\n arr[4][(i - 1) % 3]) %\n mod\n arr[3][i % 3] = (arr[2][(i - 1) % 3] + arr[4][(i - 1) % 3]) % mod\n arr[4][i % 3] = arr[0][(i - 1) % 3] % mod\n }\n return arr.reduce((sum, subArr) => sum + subArr[n % 3], 0) % mod\n}"
] |
|
1,221 | split-a-string-in-balanced-strings | [
"Loop from left to right maintaining a balance variable when it gets an L increase it by one otherwise decrease it by one.",
"Whenever the balance variable reaches zero then we increase the answer by one."
] | /**
* @param {string} s
* @return {number}
*/
var balancedStringSplit = function(s) {
}; | Balanced strings are those that have an equal quantity of 'L' and 'R' characters.
Given a balanced string s, split it into some number of substrings such that:
Each substring is balanced.
Return the maximum number of balanced strings you can obtain.
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Example 2:
Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'.
Note that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2nd and 5th substrings are not balanced.
Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
Constraints:
2 <= s.length <= 1000
s[i] is either 'L' or 'R'.
s is a balanced string.
| Easy | [
"string",
"greedy",
"counting"
] | [
"const balancedStringSplit = function(s) {\n let res = 0, num = 0\n for(let ch of s) {\n num += ch === 'L' ? 1 : -1\n if(num === 0) res++\n }\n return res\n};"
] |
|
1,222 | queens-that-can-attack-the-king | [
"Check 8 directions around the King.",
"Find the nearest queen in each direction."
] | /**
* @param {number[][]} queens
* @param {number[]} king
* @return {number[][]}
*/
var queensAttacktheKing = function(queens, king) {
}; | On a 0-indexed 8 x 8 chessboard, there can be multiple black queens ad one white king.
You are given a 2D integer array queens where queens[i] = [xQueeni, yQueeni] represents the position of the ith black queen on the chessboard. You are also given an integer array king of length 2 where king = [xKing, yKing] represents the position of the white king.
Return the coordinates of the black queens that can directly attack the king. You may return the answer in any order.
Example 1:
Input: queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]
Output: [[0,1],[1,0],[3,3]]
Explanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).
Example 2:
Input: queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]
Output: [[2,2],[3,4],[4,4]]
Explanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).
Constraints:
1 <= queens.length < 64
queens[i].length == king.length == 2
0 <= xQueeni, yQueeni, xKing, yKing < 8
All the given positions are unique.
| Medium | [
"array",
"matrix",
"simulation"
] | null | [] |
1,223 | dice-roll-simulation | [
"Think on Dynamic Programming.",
"DP(pos, last) which means we are at the position pos having as last the last character seen."
] | /**
* @param {number} n
* @param {number[]} rollMax
* @return {number}
*/
var dieSimulator = function(n, rollMax) {
}; | A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.
Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Since the answer may be too large, return it modulo 109 + 7.
Two sequences are considered different if at least one element differs from each other.
Example 1:
Input: n = 2, rollMax = [1,1,2,2,2,3]
Output: 34
Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.
Example 2:
Input: n = 2, rollMax = [1,1,1,1,1,1]
Output: 30
Example 3:
Input: n = 3, rollMax = [1,1,1,2,2,3]
Output: 181
Constraints:
1 <= n <= 5000
rollMax.length == 6
1 <= rollMax[i] <= 15
| Hard | [
"array",
"dynamic-programming"
] | [
"const dieSimulator = function(n, rollMax) {\n const mod = 10 ** 9 + 7\n const faces = rollMax.length\n const dp = Array.from({ length: n + 1 }, () => new Array(faces + 1).fill(0))\n dp[0][faces] = 1\n for(let j = 0; j < faces; j++) {\n dp[1][j] = 1\n }\n dp[1][faces] = faces\n for(let i = 2; i < n + 1; i++) {\n for(let j = 0; j < faces; j++) {\n for(let k = 1; k < rollMax[j] + 1; k++) {\n if(i - k < 0) break\n dp[i][j] += dp[i - k][faces] - dp[i - k][j]\n dp[i][j] %= mod\n }\n }\n dp[i][faces] = dp[i].reduce((ac, e) => ac + e, 0)\n }\n return dp[n][faces] % mod\n};"
] |
|
1,224 | maximum-equal-frequency | [
"Keep track of the min and max frequencies.",
"The number to be eliminated must have a frequency of 1, same as the others or the same +1."
] | /**
* @param {number[]} nums
* @return {number}
*/
var maxEqualFreq = function(nums) {
}; | Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).
Example 1:
Input: nums = [2,2,1,1,5,3,3,5]
Output: 7
Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.
Example 2:
Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]
Output: 13
Constraints:
2 <= nums.length <= 105
1 <= nums[i] <= 105
| Hard | [
"array",
"hash-table"
] | [
"const maxEqualFreq = function (nums) {\n const freqCnt = {}, cnt = {}, { max } = Math\n\n let res = 0, maxF = 0, i = 0\n for(const e of nums) {\n if(cnt[e] == null) cnt[e] = 0\n cnt[e]++\n\n const f = cnt[e]\n\n if(freqCnt[f - 1] == null) freqCnt[f - 1] = 0\n if(freqCnt[f] == null) freqCnt[f] = 0\n \n if(freqCnt[f - 1] > 0) freqCnt[f - 1]--\n freqCnt[f]++\n\n maxF = max(maxF, f)\n\n \n if(\n maxF === 1 ||\n maxF * freqCnt[maxF] === i ||\n (maxF - 1) * (freqCnt[maxF - 1] + 1) === i\n ) {\n res = i + 1\n }\n\n i++\n }\n\n return res\n}",
"const maxEqualFreq = function (nums) {\n const cnt = {},\n freq = {}\n let maxF = 0,\n res = 0\n nums.forEach((num, i) => {\n if (cnt[num] == null) cnt[num] = 0\n cnt[num] += 1\n if (freq[cnt[num] - 1] == null) freq[cnt[num] - 1] = 0\n if (freq[cnt[num]] == null) freq[cnt[num]] = 0\n freq[cnt[num] - 1] -= 1\n freq[cnt[num]] += 1\n maxF = Math.max(maxF, cnt[num])\n if (\n maxF * freq[maxF] === i ||\n (maxF - 1) * (freq[maxF - 1] + 1) === i ||\n maxF === 1\n )\n res = i + 1\n })\n return res\n}"
] |
|
1,227 | airplane-seat-assignment-probability | [
"Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then:\r\n\r\nf(1) = 1 (base case, trivial)\r\nf(2) = 1/2 (also trivial)",
"Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them?\r\nf(i) for i >= 2 will also be 1/2.",
"Try to proof why f(i) = 1/2 for i >= 2."
] | /**
* @param {number} n
* @return {number}
*/
var nthPersonGetsNthSeat = function(n) {
}; | n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
Take their own seat if it is still available, and
Pick other seats randomly when they find their seat occupied
Return the probability that the nth person gets his own seat.
Example 1:
Input: n = 1
Output: 1.00000
Explanation: The first person can only get the first seat.
Example 2:
Input: n = 2
Output: 0.50000
Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
Constraints:
1 <= n <= 105
| Medium | [
"math",
"dynamic-programming",
"brainteaser",
"probability-and-statistics"
] | null | [] |
1,232 | check-if-it-is-a-straight-line | [
"If there're only 2 points, return true.",
"Check if all other points lie on the line defined by the first 2 points.",
"Use cross product to check collinearity."
] | /**
* @param {number[][]} coordinates
* @return {boolean}
*/
var checkStraightLine = function(coordinates) {
}; | You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
Example 2:
Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false
Constraints:
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates contains no duplicate point.
| Easy | [
"array",
"math",
"geometry"
] | [
"const checkStraightLine = function(coordinates) {\n const r = ratio(coordinates[0], coordinates[1])\n for(let i = 1, len = coordinates.length; i < len - 1; i++) {\n if(ratio(coordinates[i], coordinates[i + 1]) !== r) return false\n }\n \n return true\n};\n\nfunction ratio(a, b) {\n return (b[1] - a[1]) / (b[0] - a[0])\n}"
] |
|
1,233 | remove-sub-folders-from-the-filesystem | [
"Sort the folders lexicographically.",
"Insert the current element in an array and then loop until we get rid of all of their subfolders, repeat this until no element is left."
] | /**
* @param {string[]} folder
* @return {string[]}
*/
var removeSubfolders = function(folder) {
}; | Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.
If a folder[i] is located within another folder[j], it is called a sub-folder of it.
The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.
For example, "/leetcode" and "/leetcode/problems" are valid paths while an empty string and "/" are not.
Example 1:
Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
Output: ["/a","/c/d","/c/f"]
Explanation: Folders "/a/b" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem.
Example 2:
Input: folder = ["/a","/a/b/c","/a/b/d"]
Output: ["/a"]
Explanation: Folders "/a/b/c" and "/a/b/d" will be removed because they are subfolders of "/a".
Example 3:
Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"]
Output: ["/a/b/c","/a/b/ca","/a/b/d"]
Constraints:
1 <= folder.length <= 4 * 104
2 <= folder[i].length <= 100
folder[i] contains only lowercase letters and '/'.
folder[i] always starts with the character '/'.
Each folder name is unique.
| Medium | [
"array",
"string",
"depth-first-search",
"trie"
] | null | [] |
1,234 | replace-the-substring-for-balanced-string | [
"Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4.",
"That means you need to count the amount of each letter and make sure the amount is enough."
] | /**
* @param {string} s
* @return {number}
*/
var balancedString = function(s) {
}; | You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'.
A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0.
Example 1:
Input: s = "QWER"
Output: 0
Explanation: s is already balanced.
Example 2:
Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.
Example 3:
Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".
Constraints:
n == s.length
4 <= n <= 105
n is a multiple of 4.
s contains only 'Q', 'W', 'E', and 'R'.
| Medium | [
"string",
"sliding-window"
] | null | [] |
1,235 | maximum-profit-in-job-scheduling | [
"Think on DP.",
"Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i.",
"Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition."
] | /**
* @param {number[]} startTime
* @param {number[]} endTime
* @param {number[]} profit
* @return {number}
*/
var jobScheduling = function(startTime, endTime, profit) {
}; | We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].
You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time X you will be able to start another job that starts at time X.
Example 1:
Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
Output: 120
Explanation: The subset chosen is the first and fourth job.
Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.
Example 2:
Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
Output: 150
Explanation: The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
Example 3:
Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]
Output: 6
Constraints:
1 <= startTime.length == endTime.length == profit.length <= 5 * 104
1 <= startTime[i] < endTime[i] <= 109
1 <= profit[i] <= 104
| Hard | [
"array",
"binary-search",
"dynamic-programming",
"sorting"
] | [
"const jobScheduling = function (startTime, endTime, profit) {\n const n = startTime.length\n const items = Array(n)\n for(let i = 0;i < n; i++) items[i] = [startTime[i], endTime[i], profit[i]]\n items.sort((a, b) => a[1] - b[1])\n const dpEndTime = [0]\n const dpProfit = [0]\n for(const [s, e, p] of items) {\n const prevIdx = binarySearch(dpEndTime, 0, dpEndTime.length - 1, s)\n const curProfit = dpProfit[prevIdx] + p, maxProfit = dpProfit[dpProfit.length - 1]\n if(curProfit > maxProfit) {\n dpProfit.push(curProfit)\n dpEndTime.push(e)\n }\n }\n \n return dpProfit[dpProfit.length - 1]\n}\n\nfunction binarySearch(arr, l, r, x) {\n while (l < r) {\n const mid = r - ((r - l) >> 1)\n if (arr[mid] > x) r = mid - 1\n else l = mid\n }\n return l\n}",
"const jobScheduling = function (startTime, endTime, profit) {\n const n = startTime.length\n const items = Array.from({ length: startTime.length }, () => Array(3).fill(0))\n for (let i = 0; i < startTime.length; i++) {\n items[i] = [startTime[i], endTime[i], profit[i]]\n }\n items.sort((a1, a2) => a1[1] - a2[1])\n const dpProfit = [0]\n for (let i = 0; i < n; i++) {\n const [s, e, p] = items[i]\n let prevIdx = -1\n for(let j = i - 1; j >= 0; j--) {\n if(items[j][1] <= items[i][0]) {\n prevIdx = j\n break\n }\n }\n const curProfit = (prevIdx === -1 ? 0 : dpProfit[prevIdx]) + p\n dpProfit[i] = Math.max(dpProfit[dpProfit.length - 1], curProfit)\n }\n return dpProfit[dpProfit.length - 1]\n}",
"const jobScheduling = function (startTime, endTime, profit) {\n const items = Array.from({ length: startTime.length }, () => Array(3).fill(0))\n for (let i = 0; i < startTime.length; i++) {\n items[i] = [startTime[i], endTime[i], profit[i]]\n }\n items.sort((a1, a2) => a1[1] - a2[1])\n const dpEndTime = []\n const dpProfit = []\n dpEndTime.push(0)\n dpProfit.push(0)\n for (let item of items) {\n const s = item[0],\n e = item[1],\n p = item[2]\n // find previous endTime index\n const prevIdx = binarySearch(dpEndTime, 0, dpEndTime.length - 1, s)\n const currProfit = dpProfit[prevIdx] + p,\n maxProfit = dpProfit[dpProfit.length - 1]\n if (currProfit > maxProfit) {\n dpProfit.push(currProfit)\n dpEndTime.push(e)\n }\n }\n return dpProfit[dpProfit.length - 1]\n}\n\nfunction binarySearch(arr, l, r, x) {\n while (l <= r) {\n const mid = l + ((r - l) >> 1)\n if (arr[mid] > x) r = mid - 1\n else {\n if (mid == arr.length - 1 || arr[mid + 1] > x) return mid\n l = mid + 1\n }\n }\n return -1\n}"
] |
|
1,237 | find-positive-integer-solution-for-a-given-equation | [
"Loop over 1 ≤ x,y ≤ 1000 and check if f(x,y) == z."
] | /**
* // This is the CustomFunction's API interface.
* // You should not implement it, or speculate about its implementation
* function CustomFunction() {
* @param {integer, integer} x, y
* @return {integer}
* this.f = function(x, y) {
* ...
* };
* };
*/
/**
* @param {CustomFunction} customfunction
* @param {integer} z
* @return {integer[][]}
*/
var findSolution = function(customfunction, z) {
}; | Given a callable function f(x, y) with a hidden formula and a value z, reverse engineer the formula and return all positive integer pairs x and y where f(x,y) == z. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
f(x, y) < f(x + 1, y)
f(x, y) < f(x, y + 1)
The function interface is defined like this:
interface CustomFunction {
public:
// Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};
We will judge your solution as follows:
The judge has a list of 9 hidden implementations of CustomFunction, along with a way to generate an answer key of all valid pairs for a specific z.
The judge will receive two inputs: a function_id (to determine which implementation to test your code with), and the target z.
The judge will call your findSolution and compare your results with the answer key.
If your results match the answer key, your solution will be Accepted.
Example 1:
Input: function_id = 1, z = 5
Output: [[1,4],[2,3],[3,2],[4,1]]
Explanation: The hidden formula for function_id = 1 is f(x, y) = x + y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
x=4, y=1 -> f(4, 1) = 4 + 1 = 5.
Example 2:
Input: function_id = 2, z = 5
Output: [[1,5],[5,1]]
Explanation: The hidden formula for function_id = 2 is f(x, y) = x * y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=5 -> f(1, 5) = 1 * 5 = 5.
x=5, y=1 -> f(5, 1) = 5 * 1 = 5.
Constraints:
1 <= function_id <= 9
1 <= z <= 100
It is guaranteed that the solutions of f(x, y) == z will be in the range 1 <= x, y <= 1000.
It is also guaranteed that f(x, y) will fit in 32 bit signed integer if 1 <= x, y <= 1000.
| Medium | [
"math",
"two-pointers",
"binary-search",
"interactive"
] | null | [] |
1,238 | circular-permutation-in-binary-representation | [
"Use gray code to generate a n-bit sequence.",
"Rotate the sequence such that its first element is start."
] | /**
* @param {number} n
* @param {number} start
* @return {number[]}
*/
var circularPermutation = function(n, start) {
}; | Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that :
p[0] = start
p[i] and p[i+1] differ by only one bit in their binary representation.
p[0] and p[2^n -1] must also differ by only one bit in their binary representation.
Example 1:
Input: n = 2, start = 3
Output: [3,2,0,1]
Explanation: The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]
Example 2:
Input: n = 3, start = 2
Output: [2,6,7,5,4,0,1,3]
Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).
Constraints:
1 <= n <= 16
0 <= start < 2 ^ n
| Medium | [
"math",
"backtracking",
"bit-manipulation"
] | null | [] |
1,239 | maximum-length-of-a-concatenated-string-with-unique-characters | [
"You can try all combinations and keep mask of characters you have.",
"You can use DP."
] | /**
* @param {string[]} arr
* @return {number}
*/
var maxLength = function(arr) {
}; | You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.
Return the maximum possible length of s.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All the valid concatenations are:
- ""
- "un"
- "iq"
- "ue"
- "uniq" ("un" + "iq")
- "ique" ("iq" + "ue")
Maximum length is 4.
Example 2:
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers").
Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26
Explanation: The only string in arr has all 26 characters.
Constraints:
1 <= arr.length <= 16
1 <= arr[i].length <= 26
arr[i] contains only lowercase English letters.
| Medium | [
"array",
"string",
"backtracking",
"bit-manipulation"
] | [
"const maxLength = function(arr) {\n let maxLen = 0;\n arr = arr.filter(isUnique);\n const mem = {};\n maxLen = dfs(arr, \"\", 0, maxLen, mem);\n \n return maxLen;\n};\n\nfunction dfs(arr, path, i, maxLen, mem) {\n if (mem[path]) return mem[path];\n let pathIsUnique = isUnique(path);\n if (pathIsUnique) {\n maxLen = Math.max(path.length, maxLen);\n } \n if (i === arr.length || !pathIsUnique) {\n mem[path] = maxLen;\n return maxLen;\n }\n for (let j = i; j < arr.length; j++) {\n maxLen = dfs(arr, path + arr[j], j + 1, maxLen, mem);\n }\n\n\n mem[path] = maxLen;\n return maxLen;\n}\n\nfunction isUnique(str) {\n const map = {}\n for (let i = 0; i < str.length; i++) {\n if (map[str[i]]) return false;\n map[str[i]] = 1;\n }\n \n return true;\n}"
] |
|
1,240 | tiling-a-rectangle-with-the-fewest-squares | [
"Can you use backtracking to solve this problem ?.",
"Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?.",
"The maximum number of squares to be placed will be ≤ max(n,m)."
] | /**
* @param {number} n
* @param {number} m
* @return {number}
*/
var tilingRectangle = function(n, m) {
}; | Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.
Example 1:
Input: n = 2, m = 3
Output: 3
Explanation: 3 squares are necessary to cover the rectangle.
2 (squares of 1x1)
1 (square of 2x2)
Example 2:
Input: n = 5, m = 8
Output: 5
Example 3:
Input: n = 11, m = 13
Output: 6
Constraints:
1 <= n, m <= 13
| Hard | [
"backtracking"
] | [
"const tilingRectangle = function (n, m) {\n if ((n === 11 && m === 13) || (n === 13 && m === 11)) {\n return 6\n }\n\n const dp = Array(n + 1)\n .fill()\n .map((_) => Array(m + 1).fill(0))\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= m; j++) {\n if (i === j) {\n dp[i][j] = 1\n continue\n }\n dp[i][j] = m * n\n for (let k = 1; k <= i / 2; k++) {\n dp[i][j] = Math.min(dp[i][j], dp[i - k][j] + dp[k][j])\n }\n for (let k = 1; k <= j / 2; k++) {\n dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[i][j - k])\n }\n }\n }\n return dp[n][m]\n}"
] |
|
1,247 | minimum-swaps-to-make-strings-equal | [
"First, ignore all the already matched positions, they don't affect the answer at all. For the unmatched positions, there are three basic cases (already given in the examples):",
"(\"xx\", \"yy\") => 1 swap, (\"xy\", \"yx\") => 2 swaps",
"So the strategy is, apply case 1 as much as possible, then apply case 2 if the last two unmatched are in this case, or fall into impossible if only one pair of unmatched left. This can be done via a simple math."
] | /**
* @param {string} s1
* @param {string} s2
* @return {number}
*/
var minimumSwap = function(s1, s2) {
}; | You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation: Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation: Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you cannot swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Constraints:
1 <= s1.length, s2.length <= 1000
s1.length == s2.length
s1, s2 only contain 'x' or 'y'.
| Medium | [
"math",
"string",
"greedy"
] | [
"const minimumSwap = function (s1, s2) {\n let x1 = 0 // number of 'x' in s1 (skip equal chars at same index)\n let y1 = 0 // number of 'y' in s1 (skip equal chars at same index)\n let x2 = 0 // number of 'x' in s2 (skip equal chars at same index)\n let y2 = 0 // number of 'y' in s2 (skip equal chars at same index)\n\n for (let i = 0; i < s1.length; i++) {\n let c1 = s1.charAt(i)\n let c2 = s2.charAt(i)\n if (c1 == c2) {\n // skip chars that are equal at the same index in s1 and s2\n continue\n }\n if (c1 == 'x') {\n x1++\n } else {\n y1++\n }\n if (c2 == 'x') {\n x2++\n } else {\n y2++\n }\n } // end for\n\n // After skip \"c1 == c2\", check the number of 'x' and 'y' left in s1 and s2.\n if ((x1 + x2) % 2 != 0 || (y1 + y2) % 2 != 0) {\n return -1 // if number of 'x' or 'y' is odd, we can not make s1 equals to s2\n }\n\n let swaps = Math.floor(x1 / 2) + Math.floor(y1 / 2) + (x1 % 2) * 2\n // Cases to do 1 swap:\n // \"xx\" => x1 / 2 => how many pairs of 'x' we have ?\n // \"yy\" => y1 / 2 => how many pairs of 'y' we have ?\n //\n // Cases to do 2 swaps:\n // \"xy\" or \"yx\" => x1 % 2\n\n return swaps\n}"
] |
|
1,248 | count-number-of-nice-subarrays | [
"After replacing each even by zero and every odd by one can we use prefix sum to find answer ?",
"Can we use two pointers to count number of sub-arrays ?",
"Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ?"
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var numberOfSubarrays = function(nums, k) {
}; | Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2:
Input: nums = [2,4,6], k = 1
Output: 0
Explanation: There is no odd numbers in the array.
Example 3:
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16
Constraints:
1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length
| Medium | [
"array",
"hash-table",
"math",
"sliding-window"
] | null | [] |
1,249 | minimum-remove-to-make-valid-parentheses | [
"Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix.",
"Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way."
] | /**
* @param {string} s
* @return {string}
*/
var minRemoveToMakeValid = function(s) {
}; | Given a string s of '(' , ')' and lowercase English characters.
Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:
It is the empty string, contains only lowercase characters, or
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
Example 1:
Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
Example 2:
Input: s = "a)b(c)d"
Output: "ab(c)d"
Example 3:
Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.
Constraints:
1 <= s.length <= 105
s[i] is either'(' , ')', or lowercase English letter.
| Medium | [
"string",
"stack"
] | [
" const minRemoveToMakeValid = function(s) {\n const stack = [], n = s.length\n const arr = s.split('')\n let res = ''\n for(let i = 0; i < n; i++) {\n if(s[i] === '(') stack.push(i + 1)\n if(s[i] === ')') {\n if(stack.length && stack[stack.length - 1] >= 0) stack.pop()\n else stack.push(-(i + 1))\n }\n }\n while(stack.length) {\n arr[Math.abs(stack.pop()) - 1] = ''\n }\n return arr.join('')\n};",
"const minRemoveToMakeValid = function(s) {\n let cnt = 0\n let res = s.split('')\n // console.log(res)\n for(let i = 0; i < res.length; ) {\n const ch = res[i]\n if(ch === '(') cnt++\n if(ch === ')') cnt--\n if(cnt < 0) {\n // console.log(res, i)\n res.splice(i, 1)\n cnt++\n } else i++\n }\n // console.log(res)\n let idx = res.length - 1\n while(cnt > 0) {\n if(res[idx] === '(') {\n res.splice(idx, 1)\n cnt--\n } else idx--\n }\n return res.join('')\n};",
"const minRemoveToMakeValid = function(s) {\n const stk = [], arr = s.split(''), n = s.length\n for(let i = 0; i < n; i++) {\n if(s[i] === '(') stk.push(i)\n if(s[i] === ')') {\n if(stk.length && stk[stk.length - 1] >= 0) stk.pop()\n else stk.push(-(i + 1))\n }\n }\n \n while(stk.length) {\n const tmp = stk.pop()\n if(tmp < 0) arr[-tmp - 1] = ''\n else arr[tmp] = ''\n }\n return arr.join('')\n};"
] |
|
1,250 | check-if-it-is-a-good-array | [
"Eq. ax+by=1 has solution x, y if gcd(a,b) = 1.",
"Can you generalize the formula?. Check Bézout's lemma."
] | /**
* @param {number[]} nums
* @return {boolean}
*/
var isGoodArray = function(nums) {
}; | Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand.
Return True if the array is good otherwise return False.
Example 1:
Input: nums = [12,5,7,23]
Output: true
Explanation: Pick numbers 5 and 7.
5*3 + 7*(-2) = 1
Example 2:
Input: nums = [29,6,10]
Output: true
Explanation: Pick numbers 29, 6 and 10.
29*1 + 6*(-3) + 10*(-1) = 1
Example 3:
Input: nums = [3,6]
Output: false
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
| Hard | [
"array",
"math",
"number-theory"
] | null | [] |
1,252 | cells-with-odd-values-in-a-matrix | [
"Simulation : With small constraints, it is possible to apply changes to each row and column and count odd cells after applying it.",
"You can accumulate the number you should add to each row and column and then you can count the number of odd cells."
] | /**
* @param {number} m
* @param {number} n
* @param {number[][]} indices
* @return {number}
*/
var oddCells = function(m, n, indices) {
}; | There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix.
For each location indices[i], do both of the following:
Increment all the cells on row ri.
Increment all the cells on column ci.
Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices.
Example 1:
Input: m = 2, n = 3, indices = [[0,1],[1,1]]
Output: 6
Explanation: Initial matrix = [[0,0,0],[0,0,0]].
After applying first increment it becomes [[1,2,1],[0,1,0]].
The final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.
Example 2:
Input: m = 2, n = 2, indices = [[1,1],[0,0]]
Output: 0
Explanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.
Constraints:
1 <= m, n <= 50
1 <= indices.length <= 100
0 <= ri < m
0 <= ci < n
Follow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space?
| Easy | [
"array",
"math",
"simulation"
] | [
"const oddCells = function (n, m, indices) {\n const oddRows = new BitSet(n),\n oddCols = new BitSet(m)\n let cntRow = 0,\n cntCol = 0\n for (let idx of indices) {\n oddRows.flip(idx[0])\n oddCols.flip(idx[1])\n cntRow += oddRows.get(idx[0]) ? 1 : -1\n cntCol += oddCols.get(idx[1]) ? 1 : -1\n }\n return (m - cntCol) * cntRow + (n - cntRow) * cntCol\n}\n\nclass BitSet {\n constructor(n) {\n this.arr = Array(n).fill(0)\n }\n flip(idx) {\n this.arr[idx] = this.arr[idx] === 0 ? 1 : 0\n }\n get(idx) {\n return this.arr[idx]\n }\n}"
] |
|
1,253 | reconstruct-a-2-row-binary-matrix | [
"You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row.",
"Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row."
] | /**
* @param {number} upper
* @param {number} lower
* @param {number[]} colsum
* @return {number[][]}
*/
var reconstructMatrix = function(upper, lower, colsum) {
}; | Given the following details of a matrix with n columns and 2 rows :
The matrix is a binary matrix, which means each element in the matrix can be 0 or 1.
The sum of elements of the 0-th(upper) row is given as upper.
The sum of elements of the 1-st(lower) row is given as lower.
The sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an integer array with length n.
Your task is to reconstruct the matrix with upper, lower and colsum.
Return it as a 2-D integer array.
If there are more than one valid solution, any of them will be accepted.
If no valid solution exists, return an empty 2-D array.
Example 1:
Input: upper = 2, lower = 1, colsum = [1,1,1]
Output: [[1,1,0],[0,0,1]]
Explanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.
Example 2:
Input: upper = 2, lower = 3, colsum = [2,2,1,1]
Output: []
Example 3:
Input: upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]
Output: [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]
Constraints:
1 <= colsum.length <= 10^5
0 <= upper, lower <= colsum.length
0 <= colsum[i] <= 2
| Medium | [
"array",
"greedy",
"matrix"
] | null | [] |
1,254 | number-of-closed-islands | [
"Exclude connected group of 0s on the corners because they are not closed island.",
"Return number of connected component of 0s on the grid."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var closedIsland = function(grid) {
}; | Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.
Return the number of closed islands.
Example 1:
Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
Output: 2
Explanation:
Islands in gray are closed because they are completely surrounded by water (group of 1s).
Example 2:
Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
Output: 1
Example 3:
Input: grid = [[1,1,1,1,1,1,1],
[1,0,0,0,0,0,1],
[1,0,1,1,1,0,1],
[1,0,1,0,1,0,1],
[1,0,1,1,1,0,1],
[1,0,0,0,0,0,1],
[1,1,1,1,1,1,1]]
Output: 2
Constraints:
1 <= grid.length, grid[0].length <= 100
0 <= grid[i][j] <=1
| Medium | [
"array",
"depth-first-search",
"breadth-first-search",
"union-find",
"matrix"
] | [
"const closedIsland = function(grid) {\n const m = grid.length, n = grid[0].length\n const dirs = [[0,1], [0,-1], [1,0], [-1,0]]\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if((i=== 0 || i === m - 1 || j === 0 || j === n - 1) && grid[i][j] === 0){\n fill(i, j)\n }\n }\n }\n\n \n let res = 0\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j] === 0) {\n res++\n fill(i, j)\n } \n }\n }\n \n return res\n\n \n function fill(i, j) {\n if(i < 0 || i >= m || j < 0 || j >= n || grid[i][j] !== 0) return\n grid[i][j] = 1\n for(const [dx, dy] of dirs) {\n const nx = i + dx, ny = j + dy\n fill(nx, ny)\n }\n }\n};",
"const closedIsland = function(grid) {\n const m = grid.length, n = grid[0].length\n const arr = []\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j] === 0) arr.push([i, j])\n }\n }\n const dirs = [[0,1], [0,-1], [1,0], [-1,0]]\n let num = 2\n for(const [i, j] of arr) {\n if(grid[i][j] !== 0) continue\n else {\n bfs(i, j, num)\n num++\n }\n }\n \n let res = 0\n const set = new Set()\n for(let i = 2; i < num; i++) {\n set.add(i)\n }\n \n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j] > 1 && invalid(i, j)) {\n set.delete(grid[i][j])\n } \n }\n }\n return set.size\n \n function invalid(i,j) {\n if(i === 0 || i === m - 1 || j === 0 || j === n - 1) return true\n return false\n }\n function bfs(i, j, v) {\n let q = [[i,j]]\n grid[i][j] = v\n while(q.length) {\n const tmp = []\n const size = q.length\n \n for(const [x, y] of q) {\n for(const [dx, dy] of dirs) {\n const nx = x + dx, ny = y + dy\n if(nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] === 0) {\n grid[nx][ny] = v\n tmp.push([nx, ny])\n }\n }\n }\n \n q = tmp\n }\n }\n};"
] |
|
1,255 | maximum-score-words-formed-by-letters | [
"Note that words.length is small. This means you can iterate over every subset of words (2^N)."
] | /**
* @param {string[]} words
* @param {character[]} letters
* @param {number[]} score
* @return {number}
*/
var maxScoreWords = function(words, letters, score) {
}; | Given a list of words, list of single letters (might be repeating) and score of every character.
Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).
It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively.
Example 1:
Input: words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]
Output: 23
Explanation:
Score a=1, c=9, d=5, g=3, o=2
Given letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23.
Words "dad" and "dog" only get a score of 21.
Example 2:
Input: words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]
Output: 27
Explanation:
Score a=4, b=4, c=4, x=5, z=10
Given letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27.
Word "xxxz" only get a score of 25.
Example 3:
Input: words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]
Output: 0
Explanation:
Letter "e" can only be used once.
Constraints:
1 <= words.length <= 14
1 <= words[i].length <= 15
1 <= letters.length <= 100
letters[i].length == 1
score.length == 26
0 <= score[i] <= 10
words[i], letters[i] contains only lower case English letters.
| Hard | [
"array",
"string",
"dynamic-programming",
"backtracking",
"bit-manipulation",
"bitmask"
] | [
"const maxScoreWords = function (words, letters, score) {\n const points = new Map()\n const count = Array(26).fill(0)\n for (let w of letters) {\n count[w.charCodeAt(0) - 97] = ~~count[w.charCodeAt(0) - 97] + 1\n }\n return dfs(count, 0)\n function dfs(count, index) {\n if (index >= words.length) {\n return 0\n }\n const x = dfs(count, index + 1)\n const copy = [...count]\n let point = 0\n let isValid = true\n for (let w of words[index]) {\n let k = w.charCodeAt(0) - 97\n copy[k]--\n point += score[k]\n if (copy[k] < 0) isValid = false\n }\n return Math.max(x, isValid ? point + dfs(copy, index + 1) : 0)\n }\n}"
] |
|
1,260 | shift-2d-grid | [
"Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid.",
"Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way."
] | /**
* @param {number[][]} grid
* @param {number} k
* @return {number[][]}
*/
var shiftGrid = function(grid, k) {
}; | Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.
In one shift operation:
Element at grid[i][j] moves to grid[i][j + 1].
Element at grid[i][n - 1] moves to grid[i + 1][0].
Element at grid[m - 1][n - 1] moves to grid[0][0].
Return the 2D grid after applying shift operation k times.
Example 1:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
Example 2:
Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
Example 3:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]
Constraints:
m == grid.length
n == grid[i].length
1 <= m <= 50
1 <= n <= 50
-1000 <= grid[i][j] <= 1000
0 <= k <= 100
| Easy | [
"array",
"matrix",
"simulation"
] | [
"const shiftGrid = function(grid, k) {\n for(let i = 0; i < k; i++) once(grid)\n return grid\n};\n\nfunction once(grid) {\n const m = grid.length, n = grid[0].length\n let last = grid[m - 1][n - 1]\n for(let i = 0; i < m; i++) {\n let pre = grid[i][0]\n for(let j = 1; j < n; j++) {\n let cur = grid[i][j]\n grid[i][j] = pre\n pre = cur\n }\n grid[i][0] = last\n last = pre\n }\n}"
] |
|
1,261 | find-elements-in-a-contaminated-binary-tree | [
"Use DFS to traverse the binary tree and recover it.",
"Use a hashset to store TreeNode.val for finding."
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
*/
var FindElements = function(root) {
};
/**
* @param {number} target
* @return {boolean}
*/
FindElements.prototype.find = function(target) {
};
/**
* Your FindElements object will be instantiated and called as such:
* var obj = new FindElements(root)
* var param_1 = obj.find(target)
*/ | Given a binary tree with the following rules:
root.val == 0
If treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1
If treeNode.val == x and treeNode.right != null, then treeNode.right.val == 2 * x + 2
Now the binary tree is contaminated, which means all treeNode.val have been changed to -1.
Implement the FindElements class:
FindElements(TreeNode* root) Initializes the object with a contaminated binary tree and recovers it.
bool find(int target) Returns true if the target value exists in the recovered binary tree.
Example 1:
Input
["FindElements","find","find"]
[[[-1,null,-1]],[1],[2]]
Output
[null,false,true]
Explanation
FindElements findElements = new FindElements([-1,null,-1]);
findElements.find(1); // return False
findElements.find(2); // return True
Example 2:
Input
["FindElements","find","find","find"]
[[[-1,-1,-1,-1,-1]],[1],[3],[5]]
Output
[null,true,true,false]
Explanation
FindElements findElements = new FindElements([-1,-1,-1,-1,-1]);
findElements.find(1); // return True
findElements.find(3); // return True
findElements.find(5); // return False
Example 3:
Input
["FindElements","find","find","find","find"]
[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]
Output
[null,true,false,false,true]
Explanation
FindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);
findElements.find(2); // return True
findElements.find(3); // return False
findElements.find(4); // return False
findElements.find(5); // return True
Constraints:
TreeNode.val == -1
The height of the binary tree is less than or equal to 20
The total number of nodes is between [1, 104]
Total calls of find() is between [1, 104]
0 <= target <= 106
| Medium | [
"hash-table",
"tree",
"depth-first-search",
"breadth-first-search",
"design",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const FindElements = function(root) {\n this.root = root\n this.set = new Set()\n if(root) this.set.add(0)\n \n dfs(root, 0, this.set)\n\n // console.log(this.set)\n function dfs(node, cur, set) {\n if(node == null) return\n \n if(node.left) {\n const child = cur * 2 + 1\n set.add(child)\n dfs(node.left, child, set)\n }\n if(node.right) { \n const child = cur * 2 + 2\n set.add(child)\n dfs(node.right, child, set)\n }\n }\n};\n\n\nFindElements.prototype.find = function(target) {\n return this.set.has(target)\n};"
] |
1,262 | greatest-sum-divisible-by-three | [
"Represent the state as DP[pos][mod]: maximum possible sum starting in the position \"pos\" in the array where the current sum modulo 3 is equal to mod."
] | /**
* @param {number[]} nums
* @return {number}
*/
var maxSumDivThree = function(nums) {
}; | Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.
Example 1:
Input: nums = [3,6,5,1,8]
Output: 18
Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
Example 2:
Input: nums = [4]
Output: 0
Explanation: Since 4 is not divisible by 3, do not pick any number.
Example 3:
Input: nums = [1,2,3,4,4]
Output: 12
Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).
Constraints:
1 <= nums.length <= 4 * 104
1 <= nums[i] <= 104
| Medium | [
"array",
"dynamic-programming",
"greedy",
"sorting"
] | [
"const maxSumDivThree = function (nums) {\n const n = nums.length\n let dp = [0, -Infinity, -Infinity]\n for (let i = n - 1; i >= 0; i--) {\n const nextDp = []\n for (let j = 0; j < 3; j++) {\n const nextRemain = nums[i] % 3\n nextDp[j] = Math.max(nums[i] + dp[(nextRemain + j) % 3], dp[j])\n }\n dp = nextDp\n }\n return dp[0]\n}",
"const maxSumDivThree = function(nums) {\n const sum = nums.reduce((ac, el) => ac + el, 0)\n if(sum % 3 === 0) return sum\n const remainder = sum % 3\n const comp = 3 - remainder\n nums.sort((a, b) => a - b)\n const re = [], rc = []\n for(let i = 0, len = nums.length; i < len; i++) {\n if(nums[i] % 3 === remainder) {\n if(re.length < 1) re.push(i)\n }\n if(nums[i] % 3 === comp) {\n if(rc.length < 2) rc.push(i)\n }\n if(re.length === 1 && rc.length === 2) break\n }\n if(re.length === 1 && rc.length === 2) {\n return Math.max(sum - nums[re[0]], sum - nums[rc[0]] - nums[rc[1]])\n } else if(re.length === 1) {\n return sum - nums[re[0]]\n } else if(rc.length === 2) {\n return sum - nums[rc[0]] - nums[rc[1]]\n } else {\n return 0\n }\n};"
] |
|
1,263 | minimum-moves-to-move-a-box-to-their-target-location | [
"We represent the search state as (player_row, player_col, box_row, box_col).",
"You need to count only the number of pushes. Then inside of your BFS check if the box could be pushed (in any direction) given the current position of the player."
] | /**
* @param {character[][]} grid
* @return {number}
*/
var minPushBox = function(grid) {
}; | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box.
Your task is to move the box 'B' to the target position 'T' under the following rules:
The character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell).
The character '.' represents the floor which means a free cell to walk.
The character '#' represents the wall which means an obstacle (impossible to walk there).
There is only one box 'B' and one target cell 'T' in the grid.
The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push.
The player cannot walk through the box.
Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.
Example 1:
Input: grid = [["#","#","#","#","#","#"],
["#","T","#","#","#","#"],
["#",".",".","B",".","#"],
["#",".","#","#",".","#"],
["#",".",".",".","S","#"],
["#","#","#","#","#","#"]]
Output: 3
Explanation: We return only the number of times the box is pushed.
Example 2:
Input: grid = [["#","#","#","#","#","#"],
["#","T","#","#","#","#"],
["#",".",".","B",".","#"],
["#","#","#","#",".","#"],
["#",".",".",".","S","#"],
["#","#","#","#","#","#"]]
Output: -1
Example 3:
Input: grid = [["#","#","#","#","#","#"],
["#","T",".",".","#","#"],
["#",".","#","B",".","#"],
["#",".",".",".",".","#"],
["#",".",".",".","S","#"],
["#","#","#","#","#","#"]]
Output: 5
Explanation: push the box down, left, left, up and up.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 20
grid contains only characters '.', '#', 'S', 'T', or 'B'.
There is only one character 'S', 'B', and 'T' in the grid.
| Hard | [
"array",
"breadth-first-search",
"heap-priority-queue",
"matrix"
] | [
"const minPushBox = function (grid) {\n let box, person, target\n const m = grid.length,\n n = grid[0].length\n const dirs = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ]\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n const e = grid[i][j]\n if (e === 'B') box = [i, j]\n else if (e === 'T') target = [i, j]\n else if (e === 'S') person = [i, j]\n }\n }\n\n const valid = ([i, j]) => {\n return i >= 0 && i < m && j >= 0 && j < n && grid[i][j] !== '#'\n }\n const key = ([i, j]) => `${i},${j}`\n\n const chk = (person, newPerson, box) => {\n const set = new Set()\n set.add(key(box))\n let q = [person]\n while (q.length) {\n const tmp = []\n const size = q.length\n for (let i = 0; i < size; i++) {\n const [x, y] = q[i]\n if (key([x, y]) === key(newPerson)) return true\n for (const [dx, dy] of dirs) {\n const [nx, ny] = [x + dx, y + dy]\n if (valid([nx, ny]) && !set.has(key([nx, ny]))) {\n set.add(key([nx, ny]))\n tmp.push([nx, ny])\n }\n }\n }\n q = tmp\n }\n return false\n }\n\n\n let q = [[0, box, person]]\n const dkey = (a, b) => `${a[0]},${a[1]}_${b[0]},${b[1]}`\n const set = new Set()\n set.add(dkey(box, person))\n while (q.length) {\n const size = q.length\n const tmp = []\n for (let i = 0; i < size; i++) {\n const [v, b, p] = q[i]\n if (key(b) === key(target)) return v\n const bArr = [\n [b[0], b[1] + 1],\n [b[0], b[1] - 1],\n [b[0] + 1, b[1]],\n [b[0] - 1, b[1]],\n ]\n const pArr = [\n [b[0], b[1] - 1],\n [b[0], b[1] + 1],\n [b[0] - 1, b[1]],\n [b[0] + 1, b[1]],\n ]\n\n for (let j = 0; j < 4; j++) {\n const nb = bArr[j],\n np = pArr[j]\n const nk = dkey(nb, b)\n\n if (set.has(nk)) continue\n if (valid(nb) && valid(np) && chk(p, np, b)) {\n tmp.push([v + 1, nb, b])\n set.add(nk)\n }\n }\n }\n q = tmp\n }\n\n return -1\n}",
"const minPushBox = function (grid) {\n if (\n typeof grid === 'undefined' ||\n grid === null ||\n grid.length === 0 ||\n grid[0].length === 0\n ) {\n return -1\n }\n\n let TARGET = null\n let startBlk = null\n let startPer = null\n const DIR = [\n [0, 1],\n [1, 0],\n [0, -1],\n [-1, 0],\n ]\n\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[0].length; j++) {\n if (grid[i][j] === 'S') {\n startPer = [i, j]\n grid[i][j] = '.'\n }\n if (grid[i][j] === 'T') {\n TARGET = [i, j]\n }\n if (grid[i][j] === 'B') {\n startBlk = [i, j]\n grid[i][j] = '.'\n }\n }\n }\n\n let queue = new PriorityQueue((a, b) => a.weight < b.weight)\n let states = new Map()\n queue.push({\n weight: manDist(startBlk),\n block: startBlk,\n character: startPer,\n move: 0,\n })\n while (!queue.isEmpty()) {\n let { weight, block, character, move } = queue.pop()\n if (TARGET[0] === block[0] && TARGET[1] === block[1]) {\n return move\n }\n let key = block[0] * grid[0].length + block[1]\n let val = character[0] * grid[0].length + character[1]\n if (!states.has(key)) {\n states.set(key, new Set())\n }\n states.get(key).add(val)\n DIR.forEach((d) => {\n let i = d[0] + character[0]\n let j = d[1] + character[1]\n let curV = i * grid[0].length + j\n if (validMove(i, j, block[0], block[1]) && !states.get(key).has(curV)) {\n queue.push({\n weight: manDist(block) + move,\n block: block,\n character: [i, j],\n move: move,\n })\n }\n })\n let pushDir = tryPush(character, block)\n if (pushDir !== null) {\n let newBlk = [block[0] + pushDir[0], block[1] + pushDir[1]]\n let newCha = [character[0] + pushDir[0], character[1] + pushDir[1]]\n let nBK = newBlk[0] * grid[0].length + newBlk[1]\n let nVal = newCha[0] * grid[0].length + newCha[1]\n if (!states.has(nBK) || !states.get(nBK).has(nVal)) {\n queue.push({\n weight: manDist(newBlk) + (move + 1),\n block: newBlk,\n character: newCha,\n move: move + 1,\n })\n }\n }\n }\n\n return -1\n\n function manDist(block) {\n let [x, y] = TARGET\n let [i, j] = block\n return Math.abs(x - i) + Math.abs(y - j)\n }\n function validMove(i, j, x = null, y = null) {\n if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) {\n return false\n }\n if (\n (x !== null && i === x && y !== null && j === y) ||\n grid[i][j] === '#'\n ) {\n return false\n }\n return true\n }\n function tryPush(c, b) {\n let [i, j] = c\n let [x, y] = b\n for (let u = 0; u < DIR.length; u++) {\n let [v, w] = DIR[u]\n if (\n ((Math.abs(x - i) === 1 && y === j) ||\n (Math.abs(y - j) === 1 && x === i)) &&\n validMove(i + v, j + w) &&\n validMove(x + v, y + w) &&\n i + v === x &&\n j + w === y\n ) {\n return [v, w]\n }\n }\n return null\n }\n}\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}",
"const minPushBox = function (grid) {\n const dirs = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ]\n const dis = new Map()\n const rows = grid.length\n const cols = grid[0].length\n let sk, box, target\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n if (grid[i][j] === 'B') box = [i, j]\n else if (grid[i][j] === 'S') sk = [i, j]\n else if (grid[i][j] === 'T') target = [i, j]\n }\n }\n const q = []\n const start = encode(box[0], box[1], sk[0], sk[1])\n dis.set(start, 0)\n q.push(start)\n let res = Number.MAX_VALUE\n while (q.length) {\n const u = q.pop()\n const du = decode(u)\n if (dis.get(u) >= res) continue\n if (du[0] === target[0] && du[1] === target[1]) {\n res = Math.min(res, dis.get(u))\n continue\n }\n const b = [du[0], du[1]]\n const s = [du[2], du[3]]\n for (let dir of dirs) {\n const nsx = s[0] + dir[0]\n const nsy = s[1] + dir[1]\n if (\n nsx < 0 ||\n nsx >= rows ||\n nsy < 0 ||\n nsy >= cols ||\n grid[nsx][nsy] === '#'\n )\n continue\n if (nsx === b[0] && nsy === b[1]) {\n const nbx = b[0] + dir[0]\n const nby = b[1] + dir[1]\n if (\n nbx < 0 ||\n nbx >= rows ||\n nby < 0 ||\n nby >= cols ||\n grid[nbx][nby] === '#'\n )\n continue\n const v = encode(nbx, nby, nsx, nsy)\n if (dis.has(v) && dis.get(v) <= dis.get(u) + 1) continue\n dis.set(v, dis.get(u) + 1)\n q.push(v)\n } else {\n const v = encode(b[0], b[1], nsx, nsy)\n if (dis.has(v) && dis.get(v) <= dis.get(u)) continue\n dis.set(v, dis.get(u))\n q.push(v)\n }\n }\n }\n return res === Number.MAX_VALUE ? -1 : res\n\n function encode(bx, by, sx, sy) {\n return (bx << 24) | (by << 16) | (sx << 8) | sy\n }\n function decode(num) {\n const res = []\n res[0] = (num >>> 24) & 0xff\n res[1] = (num >>> 16) & 0xff\n res[2] = (num >>> 8) & 0xff\n res[3] = num & 0xff\n return res\n }\n}",
" const minPushBox = function (grid) {\n const m = grid.length,\n n = grid[0].length\n let target, person, box\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 'T') target = [i, j]\n else if (grid[i][j] === 'B') box = [i, j]\n else if (grid[i][j] === 'S') person = [i, j]\n }\n }\n\n const valid = ([x, y]) => {\n return x >= 0 && x < m && y >= 0 && y < n && grid[x][y] !== '#'\n }\n\n const check = (cur, dest, box) => {\n const q = [cur]\n const visited = new Set([`${box[0]},${box[1]}`])\n const dirs = [\n [-1, 0],\n [1, 0],\n [0, 1],\n [0, -1],\n ]\n\n while (q.length) {\n const pos = q.shift()\n if (pos.join(',') === dest.join(',')) return true\n const newPos = []\n for (const [dx, dy] of dirs) newPos.push([pos[0] + dx, pos[1] + dy])\n for (const [nx, ny] of newPos) {\n const k = `${nx},${ny}`\n if (valid([nx, ny]) && !visited.has(k)) {\n visited.add(k)\n q.push([nx, ny])\n }\n }\n }\n\n return false\n }\n\n const q = [[0, box, person]]\n const vis = new Set([`${box.join(',')},${person.join(',')}`])\n while (q.length) {\n const [dist, box, person] = q.shift()\n if (box.join(',') === target.join(',')) return dist\n\n const bCoord = [\n [box[0] + 1, box[1]],\n [box[0] - 1, box[1]],\n [box[0], box[1] + 1],\n [box[0], box[1] - 1],\n ]\n const pCoord = [\n [box[0] - 1, box[1]],\n [box[0] + 1, box[1]],\n [box[0], box[1] - 1],\n [box[0], box[1] + 1],\n ]\n\n for (let i = 0; i < 4; i++) {\n const [newBox, newPerson] = [bCoord[i], pCoord[i]]\n const key = `${newBox.join(',')},${box.join(',')}`\n if (valid(newBox) && !vis.has(key)) {\n if (valid(newPerson) && check(person, newPerson, box)) {\n vis.add(key)\n q.push([dist + 1, newBox, box])\n }\n }\n }\n }\n\n return -1\n}"
] |
|
1,266 | minimum-time-visiting-all-points | [
"To walk from point A to point B there will be an optimal strategy to walk ?",
"Advance in diagonal as possible then after that go in straight line.",
"Repeat the process until visiting all the points."
] | /**
* @param {number[][]} points
* @return {number}
*/
var minTimeToVisitAllPoints = function(points) {
}; | On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.
You can move according to these rules:
In 1 second, you can either:
move vertically by one unit,
move horizontally by one unit, or
move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).
You have to visit the points in the same order as they appear in the array.
You are allowed to pass through points that appear later in the order, but these do not count as visits.
Example 1:
Input: points = [[1,1],[3,4],[-1,0]]
Output: 7
Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]
Time from [1,1] to [3,4] = 3 seconds
Time from [3,4] to [-1,0] = 4 seconds
Total time = 7 seconds
Example 2:
Input: points = [[3,2],[-2,2]]
Output: 5
Constraints:
points.length == n
1 <= n <= 100
points[i].length == 2
-1000 <= points[i][0], points[i][1] <= 1000
| Easy | [
"array",
"math",
"geometry"
] | [
"const minTimeToVisitAllPoints = function(points) {\n let res = 0\n for(let i = 1; i < points.length; i++) {\n res += calc(points[i], points[i - 1])\n }\n return res\n \n function calc(p1, p2) {\n const [x1, y1] = p1, [x2, y2] = p2\n const { abs, min } = Math\n const deltaX = abs(x1 - x2), deltaY = abs(y1 - y2)\n \n return min(deltaX, deltaY) + abs(deltaX - deltaY)\n }\n};"
] |
|
1,267 | count-servers-that-communicate | [
"Store number of computer in each row and column.",
"Count all servers that are not isolated."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var countServers = function(grid) {
}; | You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
Return the number of servers that communicate with any other server.
Example 1:
Input: grid = [[1,0],[0,1]]
Output: 0
Explanation: No servers can communicate with others.
Example 2:
Input: grid = [[1,0],[1,1]]
Output: 3
Explanation: All three servers can communicate with at least one other server.
Example 3:
Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
Output: 4
Explanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.
Constraints:
m == grid.length
n == grid[i].length
1 <= m <= 250
1 <= n <= 250
grid[i][j] == 0 or 1
| Medium | [
"array",
"depth-first-search",
"breadth-first-search",
"union-find",
"matrix",
"counting"
] | null | [] |
1,268 | search-suggestions-system | [
"Brute force is a good choice because length of the string is ≤ 1000.",
"Binary search the answer.",
"Use Trie data structure to store the best three matching. Traverse the Trie."
] | /**
* @param {string[]} products
* @param {string} searchWord
* @return {string[][]}
*/
var suggestedProducts = function(products, searchWord) {
}; | You are given an array of strings products and a string searchWord.
Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return a list of lists of the suggested products after each character of searchWord is typed.
Example 1:
Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"].
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"].
After typing mou, mous and mouse the system suggests ["mouse","mousepad"].
Example 2:
Input: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
Explanation: The only word "havana" will be always suggested while typing the search word.
Constraints:
1 <= products.length <= 1000
1 <= products[i].length <= 3000
1 <= sum(products[i].length) <= 2 * 104
All the strings of products are unique.
products[i] consists of lowercase English letters.
1 <= searchWord.length <= 1000
searchWord consists of lowercase English letters.
| Medium | [
"array",
"string",
"binary-search",
"trie",
"sorting",
"heap-priority-queue"
] | [
"const suggestedProducts = function(products, searchWord) {\n products.sort()\n let res = [], left = 0, right = products.length - 1\n for (let i = 0; i < searchWord.length; i++) {\n let c = searchWord.charAt(i), tmp = []\n while (products[left]?.charAt(i) < c) left++\n while (products[right]?.charAt(i) > c) right--\n for (let j = 0; j < 3 && left + j <= right; j++) tmp.push(products[left+j])\n res.push(tmp)\n }\n return res\n};",
"const suggestedProducts = function(products, searchWord) {\n const res = []\n for(let i = 0, n = searchWord.length; i < n; i++) {\n const tmp = [], pre = searchWord.slice(0, i + 1)\n for(const e of products) {\n if(e.startsWith(pre)) {\n tmp.push(e)\n tmp.sort((a, b) => a.localeCompare(b))\n if(tmp.length > 3) tmp.pop()\n }\n }\n res.push(tmp)\n }\n return res\n};",
" const suggestedProducts = function (products, searchWord) {\n products.sort()\n const root = new Node()\n for (const str of products) {\n addProduct(str)\n }\n\n const res = []\n\n let cur = root\n for (const ch of searchWord) {\n const tmp = []\n if (cur == null) {\n res.push(tmp)\n continue\n }\n const map = cur.children.get(ch)\n if (map != null) {\n addThree(map.words.values(), tmp)\n }\n\n res.push(tmp)\n cur = map\n }\n\n return res\n\n function addThree(it, arr) {\n\n for(let i = 0; i < 3; i++) {\n const res = it.next()\n if(res.value) arr.push(res.value)\n }\n }\n\n function addProduct(str) {\n let cur = root\n for (const ch of str) {\n let next = cur.children.get(ch)\n if (next == null) {\n next = new Node()\n cur.children.set(ch, next)\n }\n next.words.add(str)\n cur = next\n }\n cur.isWord = true\n }\n}\n\nclass Node {\n constructor() {\n this.children = new Map()\n this.words = new Set()\n this.isWord = false\n }\n}"
] |
|
1,269 | number-of-ways-to-stay-in-the-same-place-after-some-steps | [
"Try with Dynamic programming, dp(pos,steps): number of ways to back pos = 0 using exactly \"steps\" moves.",
"Notice that the computational complexity does not depend of \"arrlen\"."
] | /**
* @param {number} steps
* @param {number} arrLen
* @return {number}
*/
var numWays = function(steps, arrLen) {
}; | You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).
Given two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: steps = 3, arrLen = 2
Output: 4
Explanation: There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay
Example 2:
Input: steps = 2, arrLen = 4
Output: 2
Explanation: There are 2 differents ways to stay at index 0 after 2 steps
Right, Left
Stay, Stay
Example 3:
Input: steps = 4, arrLen = 2
Output: 8
Constraints:
1 <= steps <= 500
1 <= arrLen <= 106
| Hard | [
"dynamic-programming"
] | [
"const numWays = function (steps, arrLen) {\n const MOD = 10 ** 9 + 7\n const memo = Array.from({ length: (steps >> 1) + 1 }, () =>\n Array(steps + 1).fill(-1)\n )\n return dp(0, steps)\n function dp(i, steps) {\n if (steps === 0 && i === 0) return 1\n if (i < 0 || i >= arrLen || steps === 0 || i > steps) return 0\n if (memo[i][steps] !== -1) return memo[i][steps]\n return (memo[i][steps] =\n ((dp(i + 1, steps - 1) % MOD) +\n (dp(i - 1, steps - 1) % MOD) +\n (dp(i, steps - 1) % MOD)) %\n MOD)\n }\n}"
] |
|
1,275 | find-winner-on-a-tic-tac-toe-game | [
"It's straightforward to check if A or B won or not, check for each row/column/diag if all the three are the same.",
"Then if no one wins, the game is a draw iff the board is full, i.e. moves.length = 9 otherwise is pending."
] | /**
* @param {number[][]} moves
* @return {string}
*/
var tictactoe = function(moves) {
}; | Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:
Players take turns placing characters into empty squares ' '.
The first player A always places 'X' characters, while the second player B always places 'O' characters.
'X' and 'O' characters are always placed into empty squares, never on filled ones.
The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Given a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return "Draw". If there are still movements to play return "Pending".
You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.
Example 1:
Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output: "A"
Explanation: A wins, they always play first.
Example 2:
Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
Output: "B"
Explanation: B wins.
Example 3:
Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
Output: "Draw"
Explanation: The game ends in a draw since there are no moves to make.
Constraints:
1 <= moves.length <= 9
moves[i].length == 2
0 <= rowi, coli <= 2
There are no repeated elements on moves.
moves follow the rules of tic tac toe.
| Easy | [
"array",
"hash-table",
"matrix",
"simulation"
] | [
"const tictactoe = function(moves) {\n const grid = Array.from({ length: 3 }, () => Array(3).fill(''))\n for(let i = 0, n = moves.length; i < n; i++) {\n const ch = i % 2 === 0 ? 'X' : 'O'\n const [r, c] = moves[i]\n grid[r][c] = ch\n const res = chk(ch, grid)\n if(res) return ch === 'X' ? 'A' : 'B'\n }\n \n return moves.length < 9 ? 'Pending' : 'Draw'\n};\n\nfunction chk(ch, grid) {\n for(let i = 0; i < 3; i++) {\n if(\n grid[i][0] === ch &&\n grid[i][1] === ch &&\n grid[i][2] === ch\n ) return true\n }\n \n for(let i = 0; i < 3; i++) {\n if(\n grid[0][i] === ch &&\n grid[1][i] === ch &&\n grid[2][i] === ch\n ) return true\n }\n \n\n if(\n grid[0][0] === ch &&\n grid[1][1] === ch &&\n grid[2][2] === ch\n ) return true \n \n if(\n grid[0][2] === ch &&\n grid[1][1] === ch &&\n grid[2][0] === ch\n ) return true \n \n return false\n}",
"const tictactoe = function(moves) {\n const aRow = Array(3).fill(0), aCol = Array(3).fill(0), bRow= Array(3).fill(0), bCol =Array(3).fill(0)\n let ad = 0, ads = 0, bd = 0, bds = 0\n for(let i = 0; i < moves.length; i++) {\n const [r, c] = moves[i]\n if(i % 2===0) {\n if(++aRow[r] === 3 || ++aCol[c] === 3 || r === c && ++ad === 3 || r + c === 2&& ++ads === 3 ) return 'A'\n }else {\n if(++bRow[r] === 3 || ++bCol[c] === 3 || r === c && ++bd === 3 || r + c === 2&& ++bds === 3 ) return 'B'\n }\n }\n \n return moves.length >= 9 ? 'Draw' : 'Pending'\n};"
] |
|
1,276 | number-of-burgers-with-no-waste-of-ingredients | [
"Can we have an answer if the number of tomatoes is odd ?",
"If we have answer will be there multiple answers or just one answer ?",
"Let us define number of jumbo burgers as X and number of small burgers as Y\r\nWe have to find an x and y in this equation",
"1. 4X + 2Y = tomato",
"2. X + Y = cheese"
] | /**
* @param {number} tomatoSlices
* @param {number} cheeseSlices
* @return {number[]}
*/
var numOfBurgers = function(tomatoSlices, cheeseSlices) {
}; | Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:
Jumbo Burger: 4 tomato slices and 1 cheese slice.
Small Burger: 2 Tomato slices and 1 cheese slice.
Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [].
Example 1:
Input: tomatoSlices = 16, cheeseSlices = 7
Output: [1,6]
Explantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.
There will be no remaining ingredients.
Example 2:
Input: tomatoSlices = 17, cheeseSlices = 4
Output: []
Explantion: There will be no way to use all ingredients to make small and jumbo burgers.
Example 3:
Input: tomatoSlices = 4, cheeseSlices = 17
Output: []
Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.
Constraints:
0 <= tomatoSlices, cheeseSlices <= 107
| Medium | [
"math"
] | null | [] |
1,277 | count-square-submatrices-with-all-ones | [
"Create an additive table that counts the sum of elements of submatrix with the superior corner at (0,0).",
"Loop over all subsquares in O(n^3) and check if the sum make the whole array to be ones, if it checks then add 1 to the answer."
] | /**
* @param {number[][]} matrix
* @return {number}
*/
var countSquares = function(matrix) {
}; | Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Example 1:
Input: matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is 1 square of side 3.
Total number of squares = 10 + 4 + 1 = 15.
Example 2:
Input: matrix =
[
[1,0,1],
[1,1,0],
[1,1,0]
]
Output: 7
Explanation:
There are 6 squares of side 1.
There is 1 square of side 2.
Total number of squares = 6 + 1 = 7.
Constraints:
1 <= arr.length <= 300
1 <= arr[0].length <= 300
0 <= arr[i][j] <= 1
| Medium | [
"array",
"dynamic-programming",
"matrix"
] | [
"const countSquares = function (matrix) {\n const [m, n] = [matrix.length, matrix[0].length]\n let res = 0\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(matrix[i][j] && i > 0 && j > 0) {\n matrix[i][j] = 1 + Math.min(\n matrix[i - 1][j],\n matrix[i][j - 1],\n matrix[i - 1][j - 1],\n )\n }\n res += matrix[i][j]\n }\n }\n return res\n}",
"const countSquares = function (A) {\n const [M, N] = [A.length, A[0].length]\n let ans = 0\n for (let i = 0; i < M; ++i) {\n for (let j = 0; j < N; ++j) {\n if (A[i][j] && i > 0 && j > 0) {\n A[i][j] = 1 + Math.min(A[i - 1][j], A[i][j - 1], A[i - 1][j - 1])\n }\n ans += A[i][j]\n }\n }\n return ans\n}"
] |
|
1,278 | palindrome-partitioning-iii | [
"For each substring calculate the minimum number of steps to make it palindrome and store it in a table.",
"Create a dp(pos, cnt) which means the minimum number of characters changed for the suffix of s starting on pos splitting the suffix on cnt chunks."
] | /**
* @param {string} s
* @param {number} k
* @return {number}
*/
var palindromePartition = function(s, k) {
}; | You are given a string s containing lowercase letters and an integer k. You need to :
First, change some characters of s to other lowercase English letters.
Then divide s into k non-empty disjoint substrings such that each substring is a palindrome.
Return the minimal number of characters that you need to change to divide the string.
Example 1:
Input: s = "abc", k = 2
Output: 1
Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome.
Example 2:
Input: s = "aabbc", k = 3
Output: 0
Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.
Example 3:
Input: s = "leetcode", k = 8
Output: 0
Constraints:
1 <= k <= s.length <= 100.
s only contains lowercase English letters.
| Hard | [
"string",
"dynamic-programming"
] | [
"const palindromePartition = function(s, k) {\n const n = s.length\n const memo = new Map()\n return dfs(0, k)\n function cost(s, i, j) {\n let r = 0\n while(i < j) {\n if(s[i] !== s[j]) r++\n i++\n j--\n }\n return r\n }\n function dfs(i, k) {\n if(memo.has(`${i}-${k}`)) return memo.get(`${i}-${k}`)\n if(n - i === k) return 0\n if(k === 1) return cost(s, i, n - 1)\n let res = Infinity\n for(let j = i + 1; j < n - k + 2; j++) {\n res = Math.min(res, dfs(j, k - 1) + cost(s, i, j - 1))\n }\n memo.set(`${i}-${k}`, res)\n return res\n }\n};"
] |
|
1,281 | subtract-the-product-and-sum-of-digits-of-an-integer | [
"How to compute all digits of the number ?",
"Use modulus operator (%) to compute the last digit.",
"Generalise modulus operator idea to compute all digits."
] | /**
* @param {number} n
* @return {number}
*/
var subtractProductAndSum = function(n) {
}; | Given an integer number n, return the difference between the product of its digits and the sum of its digits.
Example 1:
Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
Example 2:
Input: n = 4421
Output: 21
Explanation:
Product of digits = 4 * 4 * 2 * 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
Constraints:
1 <= n <= 10^5
| Easy | [
"math"
] | [
"const subtractProductAndSum = function(n) {\n if(n === 0) return 0\n let sum = 0, product = 1\n n = '' + n\n for(let ch of n) {\n sum += +(ch)\n product *= +(ch)\n }\n return product - sum\n};"
] |
|
1,282 | group-the-people-given-the-group-size-they-belong-to | [
"Put people's IDs with same groupSize into buckets, then split each bucket into groups.",
"Greedy fill until you need a new group."
] | /**
* @param {number[]} groupSizes
* @return {number[][]}
*/
var groupThePeople = function(groupSizes) {
}; | There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.
You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.
Return a list of groups such that each person i is in a group of size groupSizes[i].
Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.
Example 1:
Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation:
The first group is [5]. The size is 1, and groupSizes[5] = 1.
The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.
The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.
Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].
Example 2:
Input: groupSizes = [2,1,3,3,3,2]
Output: [[1],[0,5],[2,3,4]]
Constraints:
groupSizes.length == n
1 <= n <= 500
1 <= groupSizes[i] <= n
| Medium | [
"array",
"hash-table"
] | [
"const groupThePeople = function(groupSizes) {\n const hash = {}\n const n = groupSizes.length\n \n for(let i = 0; i < n; i++) {\n const size = groupSizes[i]\n if(hash[size] == null) hash[size] = []\n hash[size].push(i)\n }\n \n const keys = Object.keys(hash)\n // console.log(hash)\n const res = []\n for(let size of keys) {\n size = +size\n const arr = hash[size]\n for(let i = 0; i < arr.length; i += size) {\n res.push(arr.slice(i, i + size))\n }\n }\n \n return res\n};"
] |
|
1,283 | find-the-smallest-divisor-given-a-threshold | [
"Examine every possible number for solution. Choose the largest of them.",
"Use binary search to reduce the time complexity."
] | /**
* @param {number[]} nums
* @param {number} threshold
* @return {number}
*/
var smallestDivisor = function(nums, threshold) {
}; | Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
The test cases are generated so that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [44,22,33,11,1], threshold = 5
Output: 44
Constraints:
1 <= nums.length <= 5 * 104
1 <= nums[i] <= 106
nums.length <= threshold <= 106
| Medium | [
"array",
"binary-search"
] | [
"const smallestDivisor = function(nums, threshold) {\n let l = 1, r = 1e6\n while(l < r) {\n const mid = l + Math.floor((r - l) / 2)\n if(valid(mid)) r = mid\n else l = mid + 1\n }\n return l\n \n function valid(mid) {\n let res = 0\n for(let e of nums) res += Math.ceil(e / mid)\n return res <= threshold\n }\n};"
] |
|
1,284 | minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix | [
"Flipping same index two times is like not flipping it at all. Each index can be flipped one time. Try all possible combinations. O(2^(n*m))."
] | /**
* @param {number[][]} mat
* @return {number}
*/
var minFlips = function(mat) {
}; | Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge.
Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.
A binary matrix is a matrix with all cells equal to 0 or 1 only.
A zero matrix is a matrix with all cells equal to 0.
Example 1:
Input: mat = [[0,0],[0,1]]
Output: 3
Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.
Example 2:
Input: mat = [[0]]
Output: 0
Explanation: Given matrix is a zero matrix. We do not need to change it.
Example 3:
Input: mat = [[1,0,0],[1,0,0]]
Output: -1
Explanation: Given matrix cannot be a zero matrix.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 3
mat[i][j] is either 0 or 1.
| Hard | [
"array",
"bit-manipulation",
"breadth-first-search",
"matrix"
] | [
"const minFlips = function (mat) {\n let start = 0\n const m = mat.length, n = mat[0].length\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n start |= mat[i][j] << (i * n + j)\n }\n }\n let q = [start]\n const seen = new Set(), dirs = [[-1, 0], [1, 0], [0, -1], [0, 1], [0, 0]]\n\n for(let i = 0; q.length; i++) {\n const tmp = []\n for (let size = q.length; size > 0; size--) {\n const cur = q.pop()\n if(cur === 0) return i\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n let next = cur\n for(const [dx, dy] of dirs) {\n const r = i + dx, c = j + dy\n if(r >= 0 && r < m && c >= 0 && c < n) {\n next ^= (1 << (r * n + c))\n }\n }\n if (!seen.has(next)) {\n seen.add(next)\n tmp.push(next)\n }\n }\n }\n }\n q = tmp\n }\n\n return -1\n}",
"const minFlips = function (mat) {\n const X = mat.length\n const Y = mat[0].length\n const binary = {\n 0: 1,\n 1: 2,\n 2: 4,\n 3: 8,\n 4: 16,\n 5: 32,\n 6: 64,\n 7: 128,\n 8: 256,\n }\n const mask = []\n let state = 0\n for (let i = 0; i < X; ++i) {\n for (let j = 0; j < Y; ++j) {\n let bit = 0\n state += mat[i][j] * binary[Y * i + j]\n bit += binary[Y * i + j]\n if (i > 0) {\n bit += binary[Y * (i - 1) + j]\n }\n if (i < X - 1) {\n bit += binary[Y * (i + 1) + j]\n }\n if (j > 0) {\n bit += binary[Y * i + (j - 1)]\n }\n if (j < Y - 1) {\n bit += binary[Y * i + (j + 1)]\n }\n mask.push(bit)\n }\n }\n if (state === 0) return 0\n const set = new Set()\n const q = [{ state: state, moves: 0 }]\n while (q.length !== 0) {\n const cur = q.shift()\n if (cur.state === 0) {\n return cur.moves\n }\n for (let i = 0; i < X * Y; ++i) {\n let newState = cur.state\n newState ^= mask[i]\n if (!set.has(newState)) {\n set.add(newState)\n q.push({ state: newState, moves: cur.moves + 1 })\n }\n }\n }\n return -1\n}"
] |
|
1,286 | iterator-for-combination | [
"Generate all combinations as a preprocessing.",
"Use bit masking to generate all the combinations."
] | /**
* @param {string} characters
* @param {number} combinationLength
*/
var CombinationIterator = function(characters, combinationLength) {
};
/**
* @return {string}
*/
CombinationIterator.prototype.next = function() {
};
/**
* @return {boolean}
*/
CombinationIterator.prototype.hasNext = function() {
};
/**
* Your CombinationIterator object will be instantiated and called as such:
* var obj = new CombinationIterator(characters, combinationLength)
* var param_1 = obj.next()
* var param_2 = obj.hasNext()
*/ | Design the CombinationIterator class:
CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
next() Returns the next combination of length combinationLength in lexicographical order.
hasNext() Returns true if and only if there exists a next combination.
Example 1:
Input
["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[["abc", 2], [], [], [], [], [], []]
Output
[null, "ab", true, "ac", true, "bc", false]
Explanation
CombinationIterator itr = new CombinationIterator("abc", 2);
itr.next(); // return "ab"
itr.hasNext(); // return True
itr.next(); // return "ac"
itr.hasNext(); // return True
itr.next(); // return "bc"
itr.hasNext(); // return False
Constraints:
1 <= combinationLength <= characters.length <= 15
All the characters of characters are unique.
At most 104 calls will be made to next and hasNext.
It is guaranteed that all calls of the function next are valid.
| Medium | [
"string",
"backtracking",
"design",
"iterator"
] | [
"const CombinationIterator = function (characters, combinationLength) {\n this.arr = build(combinationLength, characters.split('').sort().join(''))\n this.pos = 0\n}\n\n\nCombinationIterator.prototype.next = function () {\n if (this.pos < this.arr.length) {\n return this.arr[this.pos++]\n }\n}\n\n\nCombinationIterator.prototype.hasNext = function () {\n return this.pos < this.arr.length\n}\n\n\nfunction build(max, str, out = [], curr = '') {\n if (curr.length === max) {\n out.push(curr)\n return\n } else {\n for (let i = 0; i < str.length; i++) {\n build(max, str.slice(i + 1), out, curr + str[i])\n }\n }\n\n return out\n}",
"const CombinationIterator = function(characters, combinationLength) {\n const res = [], len = combinationLength, str = characters, n = str.length\n helper([], 0)\n this.arr = res\n this.idx = 0\n \n function helper(cur, idx) {\n if(cur.length === len) {\n res.push(cur.slice().join(''))\n return\n }\n if(idx >= n) return\n\n cur.push(str[idx])\n helper(cur, idx + 1)\n cur.pop()\n\n helper(cur, idx + 1)\n }\n};\n\n\nCombinationIterator.prototype.next = function() {\n if(this.hasNext()) {\n return this.arr[this.idx++]\n }\n};\n\n\nCombinationIterator.prototype.hasNext = function() {\n return this.arr[this.idx] != null\n};",
"const CombinationIterator = function(characters, combinationLength) {\n const res = [], len = combinationLength, str = characters, n = str.length\n helper()\n\n // console.log(res)\n this.arr = res\n this.idx = 0\n \n function helper() {\n const limit = 1 << n\n for(let i = limit - 1; i > 0; i--) {\n let tmp = i, ts = '', idx = n - 1\n while(tmp) {\n if(tmp & 1) {\n ts = str[idx] + ts\n }\n idx--\n tmp = (tmp >> 1)\n }\n if(ts.length === len) res.push(ts)\n }\n }\n};\n\n\nCombinationIterator.prototype.next = function() {\n if(this.hasNext()) {\n return this.arr[this.idx++]\n }\n};\n\n\nCombinationIterator.prototype.hasNext = function() {\n return this.arr[this.idx] != null\n};"
] |
|
1,287 | element-appearing-more-than-25-in-sorted-array | [
"Divide the array in four parts [1 - 25%] [25 - 50 %] [50 - 75 %] [75% - 100%]",
"The answer should be in one of the ends of the intervals.",
"In order to check which is element is the answer we can count the frequency with binarySearch."
] | /**
* @param {number[]} arr
* @return {number}
*/
var findSpecialInteger = function(arr) {
}; | Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
Example 1:
Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Example 2:
Input: arr = [1,1]
Output: 1
Constraints:
1 <= arr.length <= 104
0 <= arr[i] <= 105
| Easy | [
"array"
] | [
"const findSpecialInteger = function (arr) {\n const n = arr.length,\n { floor } = Math,\n { getWordIndexRange } = Search()\n const ticks = [n / 4, n / 2, (n * 3) / 4].map((e) => floor(e))\n for (const i of ticks) {\n const [s, e] = getWordIndexRange(arr, arr[i])\n if (e - s > n / 4) return arr[i]\n }\n return 0\n}\n\nfunction Search() {\n return { getWordIndexRange }\n\n \n function binarySearch(lo, hi, predicate) {\n while (lo != hi) {\n let mid = ((lo + hi) / 2) | 0\n if (predicate(mid)) {\n hi = mid\n } else {\n lo = mid + 1\n }\n }\n return lo\n }\n\n function getWordIndexRange(keys, word) {\n let lo = 0,\n hi = keys.length\n function greaterOrEqual(index) {\n return keys[index] >= word\n }\n function less(index) {\n return keys[index] > word\n }\n let lower_bound = binarySearch(0, keys.length, greaterOrEqual)\n let upper_bound = binarySearch(lower_bound, keys.length, less)\n return [lower_bound, upper_bound]\n }\n}"
] |
|
1,288 | remove-covered-intervals | [
"How to check if an interval is covered by another?",
"Compare each interval to all others and check if it is covered by any interval."
] | /**
* @param {number[][]} intervals
* @return {number}
*/
var removeCoveredIntervals = function(intervals) {
}; | Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.
The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.
Return the number of remaining intervals.
Example 1:
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:
Input: intervals = [[1,4],[2,3]]
Output: 1
Constraints:
1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= li < ri <= 105
All the given intervals are unique.
| Medium | [
"array",
"sorting"
] | [
"const removeCoveredIntervals = function(intervals) {\n intervals.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])\n const n = intervals.length\n let res = n, max = intervals[0][1]\n for(let i = 1; i < n; i++) {\n if(intervals[i][1] <= max) res--\n else max = intervals[i][1]\n }\n return res\n};"
] |
|
1,289 | minimum-falling-path-sum-ii | [
"Use dynamic programming.",
"Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i.",
"Use the concept of cumulative array to optimize the complexity of the solution."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var minFallingPathSum = function(grid) {
}; | Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts.
A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.
Example 1:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: 13
Explanation:
The possible falling paths are:
[1,5,9], [1,5,7], [1,6,7], [1,6,8],
[2,4,8], [2,4,9], [2,6,7], [2,6,8],
[3,4,8], [3,4,9], [3,5,7], [3,5,9]
The falling path with the smallest sum is [1,5,7], so the answer is 13.
Example 2:
Input: grid = [[7]]
Output: 7
Constraints:
n == grid.length == grid[i].length
1 <= n <= 200
-99 <= grid[i][j] <= 99
| Hard | [
"array",
"dynamic-programming",
"matrix"
] | [
"const minFallingPathSum = function (arr) {\n const n = arr.length\n for (let i = 1; i < n; i++) {\n const [m1, m2] = min2(arr[i - 1])\n for (j = 0; j < n; j++) {\n arr[i][j] += arr[i - 1][j] !== m1 ? m1 : m2\n }\n }\n return Math.min(...arr[n - 1])\n}\n\nfunction min2(arr) {\n let m1 = Infinity, m2 = Infinity\n arr.forEach(e => {\n if(e < m1) m2 = m1, m1 = e\n else if(e < m2) m2 = e\n })\n return [m1, m2]\n}"
] |
|
1,290 | convert-binary-number-in-a-linked-list-to-integer | [
"Traverse the linked list and store all values in a string or array. convert the values obtained to decimal value.",
"You can solve the problem in O(1) memory using bits operation. use shift left operation ( << ) and or operation ( | ) to get the decimal value in one operation."
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {number}
*/
var getDecimalValue = function(head) {
}; | Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
The most significant bit is at the head of the linked list.
Example 1:
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10
Example 2:
Input: head = [0]
Output: 0
Constraints:
The Linked List is not empty.
Number of nodes will not exceed 30.
Each node's value is either 0 or 1.
| Easy | [
"linked-list",
"math"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const getDecimalValue = function(head) {\n let res = 0\n\n while(head) {\n res = res * 2 + head.val\n head = head.next\n }\n return res\n};"
] |
1,291 | sequential-digits | [
"Generate all numbers with sequential digits and check if they are in the given range.",
"Fix the starting digit then do a recursion that tries to append all valid digits."
] | /**
* @param {number} low
* @param {number} high
* @return {number[]}
*/
var sequentialDigits = function(low, high) {
}; | An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
Example 1:
Input: low = 100, high = 300
Output: [123,234]
Example 2:
Input: low = 1000, high = 13000
Output: [1234,2345,3456,4567,5678,6789,12345]
Constraints:
10 <= low <= high <= 10^9
| Medium | [
"enumeration"
] | [
"const sequentialDigits = function(low, high) {\n const res = []\n \n let q = []\n for(let i = 1; i <= 9; i++) q.push(i)\n \n while(q.length) {\n const tmp = []\n const size = q.length\n for(let i = 0; i < size; i++) {\n const cur = q[i]\n if(cur >= low && cur <= high) {\n res.push(cur)\n }\n if(cur > high) break\n const last = cur % 10\n if(last === 9) continue\n tmp.push(cur * 10 + last + 1)\n }\n \n q = tmp\n }\n \n return res\n};",
"const sequentialDigits = function(low, high) {\n const set = new Set()\n let start = 0, end = 0\n for(let i = 10; i >= 0; i--) {\n if (low / (10 ** i) >= 1) {\n start = ~~(low / (10 ** i))\n break\n }\n }\n for(let i = 10; i >= 0; i--) {\n if (high / (10 ** i) >= 1) {\n end = ~~(high / (10 ** i))\n break\n }\n }\n for(let i = 1; i <= 9; i++) {\n helper(`${i}`) \n }\n\n const res = Array.from(set)\n res.sort((a, b) => a- b)\n return res\n \n function helper(s) {\n // console.log(s)\n if(+s > high) return\n if(+s >= low && +s <= high) {\n set.add(+s)\n }\n if(s[s.length - 1] === '9') return\n helper(`${s}${+s[s.length - 1] + 1}`)\n }\n};"
] |
|
1,292 | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | [
"Store prefix sum of all grids in another 2D array.",
"Try all possible solutions and if you cannot find one return -1.",
"If x is a valid answer then any y < x is also valid answer. Use binary search to find answer."
] | /**
* @param {number[][]} mat
* @param {number} threshold
* @return {number}
*/
var maxSideLength = function(mat, threshold) {
}; | Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.
Example 1:
Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
Output: 2
Explanation: The maximum side length of square with sum less than 4 is 2 as shown.
Example 2:
Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
Output: 0
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 300
0 <= mat[i][j] <= 104
0 <= threshold <= 105
| Medium | [
"array",
"binary-search",
"matrix",
"prefix-sum"
] | [
"const maxSideLength = function (mat, threshold) {\n let m = mat.length\n let n = mat[0].length\n const sum = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n\n let res = 0\n let len = 1 // square side length\n\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n sum[i][j] =\n sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + mat[i - 1][j - 1]\n\n if (\n i >= len &&\n j >= len &&\n sum[i][j] - sum[i - len][j] - sum[i][j - len] + sum[i - len][j - len] <=\n threshold\n )\n res = len++\n }\n }\n\n return res\n}"
] |
|
1,293 | shortest-path-in-a-grid-with-obstacles-elimination | [
"Use BFS.",
"BFS on (x,y,r) x,y is coordinate, r is remain number of obstacles you can remove."
] | /**
* @param {number[][]} grid
* @param {number} k
* @return {number}
*/
var shortestPath = function(grid, k) {
}; | You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.
Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.
Example 1:
Input: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1
Output: 6
Explanation:
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).
Example 2:
Input: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1
Output: -1
Explanation: We need to eliminate at least two obstacles to find such a walk.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 40
1 <= k <= m * n
grid[i][j] is either 0 or 1.
grid[0][0] == grid[m - 1][n - 1] == 0
| Hard | [
"array",
"breadth-first-search",
"matrix"
] | [
"const shortestPath = function (grid, k) {\n const m = grid.length\n const n = m && grid[0].length\n if (m === 1 && n === 1) return 0\n const queue = [[0, 0, k]]\n const dirs = [\n [1, 0],\n [-1, 0],\n [0, 1],\n [0, -1],\n ]\n const visited = new Set()\n let steps = 0\n while (queue.length > 0) {\n let size = queue.length\n while (size--) {\n const [row, col, em] = queue.shift()\n if (visited.has(row + \"#\" + col + \"#\" + em)) continue\n visited.add(row + \"#\" + col + \"#\" + em)\n for (let dir of dirs) {\n const nx = row + dir[0]\n const ny = col + dir[1]\n if (\n nx < 0 ||\n nx >= m ||\n ny < 0 ||\n ny >= n ||\n visited.has(nx + \"#\" + ny + \"#\" + em)\n )\n continue\n if (nx === m - 1 && ny === n - 1) return steps + 1\n if (grid[nx][ny] === 1) {\n if (em > 0) queue.push([nx, ny, em - 1])\n } else {\n queue.push([nx, ny, em])\n }\n }\n }\n steps++\n }\n return -1\n}"
] |
|
1,295 | find-numbers-with-even-number-of-digits | [
"How to compute the number of digits of a number ?",
"Divide the number by 10 again and again to get the number of digits."
] | /**
* @param {number[]} nums
* @return {number}
*/
var findNumbers = function(nums) {
}; | Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
Example 2:
Input: nums = [555,901,482,1771]
Output: 1
Explanation:
Only 1771 contains an even number of digits.
Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 105
| Easy | [
"array"
] | [
"const findNumbers = function(nums) {\n let res = 0\n for(const e of nums) {\n const str = '' + e\n if(str.length % 2 === 0) res++\n }\n return res\n};"
] |
|
1,296 | divide-array-in-sets-of-k-consecutive-numbers | [
"If the smallest number in the possible-to-split array is V, then numbers V+1, V+2, ... V+k-1 must contain there as well.",
"You can iteratively find k sets and remove them from array until it becomes empty.",
"Failure to do so would mean that array is unsplittable."
] | /**
* @param {number[]} nums
* @param {number} k
* @return {boolean}
*/
var isPossibleDivide = function(nums, k) {
}; | Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers.
Return true if it is possible. Otherwise, return false.
Example 1:
Input: nums = [1,2,3,3,4,4,5,6], k = 4
Output: true
Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].
Example 2:
Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
Output: true
Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].
Example 3:
Input: nums = [1,2,3,4], k = 3
Output: false
Explanation: Each array should be divided in subarrays of size 3.
Constraints:
1 <= k <= nums.length <= 105
1 <= nums[i] <= 109
Note: This question is the same as 846: https://leetcode.com/problems/hand-of-straights/ | Medium | [
"array",
"hash-table",
"greedy",
"sorting"
] | null | [] |
1,297 | maximum-number-of-occurrences-of-a-substring | [
"Check out the constraints, (maxSize <=26).",
"This means you can explore all substrings in O(n * 26).",
"Find the Maximum Number of Occurrences of a Substring with bruteforce."
] | /**
* @param {string} s
* @param {number} maxLetters
* @param {number} minSize
* @param {number} maxSize
* @return {number}
*/
var maxFreq = function(s, maxLetters, minSize, maxSize) {
}; | Given a string s, return the maximum number of occurrences of any substring under the following rules:
The number of unique characters in the substring must be less than or equal to maxLetters.
The substring size must be between minSize and maxSize inclusive.
Example 1:
Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
Output: 2
Explanation: Substring "aab" has 2 occurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
Example 2:
Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
Output: 2
Explanation: Substring "aaa" occur 2 times in the string. It can overlap.
Constraints:
1 <= s.length <= 105
1 <= maxLetters <= 26
1 <= minSize <= maxSize <= min(26, s.length)
s consists of only lowercase English letters.
| Medium | [
"hash-table",
"string",
"sliding-window"
] | null | [] |
1,298 | maximum-candies-you-can-get-from-boxes | [
"Use Breadth First Search (BFS) to traverse all possible boxes you can open. Only push to the queue the boxes the you have with their keys."
] | /**
* @param {number[]} status
* @param {number[]} candies
* @param {number[][]} keys
* @param {number[][]} containedBoxes
* @param {number[]} initialBoxes
* @return {number}
*/
var maxCandies = function(status, candies, keys, containedBoxes, initialBoxes) {
}; | You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and containedBoxes where:
status[i] is 1 if the ith box is open and 0 if the ith box is closed,
candies[i] is the number of candies in the ith box,
keys[i] is a list of the labels of the boxes you can open after opening the ith box.
containedBoxes[i] is a list of the boxes you found inside the ith box.
You are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.
Return the maximum number of candies you can get following the rules above.
Example 1:
Input: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]
Output: 16
Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.
Box 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.
In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.
Total number of candies collected = 7 + 4 + 5 = 16 candy.
Example 2:
Input: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]
Output: 6
Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.
The total number of candies will be 6.
Constraints:
n == status.length == candies.length == keys.length == containedBoxes.length
1 <= n <= 1000
status[i] is either 0 or 1.
1 <= candies[i] <= 1000
0 <= keys[i].length <= n
0 <= keys[i][j] < n
All values of keys[i] are unique.
0 <= containedBoxes[i].length <= n
0 <= containedBoxes[i][j] < n
All values of containedBoxes[i] are unique.
Each box is contained in one box at most.
0 <= initialBoxes.length <= n
0 <= initialBoxes[i] < n
| Hard | [
"array",
"breadth-first-search",
"graph"
] | null | [] |
1,299 | replace-elements-with-greatest-element-on-right-side | [
"Loop through the array starting from the end.",
"Keep the maximum value seen so far."
] | /**
* @param {number[]} arr
* @return {number[]}
*/
var replaceElements = function(arr) {
}; | Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.
After doing so, return the array.
Example 1:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Explanation:
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.
Example 2:
Input: arr = [400]
Output: [-1]
Explanation: There are no elements to the right of index 0.
Constraints:
1 <= arr.length <= 104
1 <= arr[i] <= 105
| Easy | [
"array"
] | [
"const replaceElements = function(arr) {\n const suffix = [-1], n = arr.length\n for(let i = n - 2; i >= 0; i--) {\n suffix.unshift(Math.max(suffix[0], arr[i + 1]))\n }\n \n return suffix\n};"
] |
|
1,300 | sum-of-mutated-array-closest-to-target | [
"If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get?",
"That graph is uni-modal.",
"Use ternary search on that graph to find the best value."
] | /**
* @param {number[]} arr
* @param {number} target
* @return {number}
*/
var findBestValue = function(arr, target) {
}; | Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target.
In case of a tie, return the minimum such integer.
Notice that the answer is not neccesarilly a number from arr.
Example 1:
Input: arr = [4,9,3], target = 10
Output: 3
Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.
Example 2:
Input: arr = [2,3,5], target = 10
Output: 5
Example 3:
Input: arr = [60864,25176,27249,21296,20204], target = 56803
Output: 11361
Constraints:
1 <= arr.length <= 104
1 <= arr[i], target <= 105
| Medium | [
"array",
"binary-search",
"sorting"
] | [
"const findBestValue = function(arr, target) {\n let l, r, mi, s = 0, m = -1;\n for(let v of arr) { s += v; m = Math.max(m, v); }\n if(s <= target) return m; \n\n for(l = 1, r = m; l < r;) {\n mi = ~~((l+r)/2);\n s = 0;\n for(let v of arr) s += (v > mi) ? mi : v;\n if(s >= target) r = mi;\n else l = mi + 1;\n }\n // check if we are 1 step off the target \n let s1=0,s2=0;\n for(let v of arr) {\n s1 += (v>l)?(l):v;\n s2 += (v>l-1)?(l-1):v;\n }\n\n return (Math.abs(s2-target) <= Math.abs(s1-target)) ? l-1 : l;\n};"
] |
|
1,301 | number-of-paths-with-max-score | [
"Use dynamic programming to find the path with the max score.",
"Use another dynamic programming array to count the number of paths with max score."
] | /**
* @param {string[]} board
* @return {number[]}
*/
var pathsWithMaxScore = function(board) {
}; | You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'.
You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.
Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.
In case there is no path, return [0, 0].
Example 1:
Input: board = ["E23","2X2","12S"]
Output: [7,1]
Example 2:
Input: board = ["E12","1X1","21S"]
Output: [4,2]
Example 3:
Input: board = ["E11","XXX","11S"]
Output: [0,0]
Constraints:
2 <= board.length == board[i].length <= 100
| Hard | [
"array",
"dynamic-programming",
"matrix"
] | [
"const pathsWithMaxScore = (\n A,\n dirs = [\n [-1, -1],\n [-1, 0],\n [0, -1],\n ],\n mod = 1e9 + 7\n) => {\n const N = A.length\n const S = [...Array(N + 1)].map((row) => Array(N + 1).fill(0)),\n P = [...Array(N + 1)].map((row) => Array(N + 1).fill(0))\n P[0][0] = 1\n for (let i = 1; i <= N; ++i) {\n for (let j = 1; j <= N; ++j) {\n if (A[i - 1][j - 1] == 'X') continue\n for (let d of dirs) {\n const u = i + d[0],\n v = j + d[1]\n const sum = !P[u][v]\n ? 0\n : S[u][v] +\n (i == 1 && j == 1\n ? 0\n : i == N && j == N\n ? 0\n : A[i - 1].charCodeAt(j - 1) - '0'.charCodeAt(0))\n if (S[i][j] == sum) P[i][j] = (P[i][j] + P[u][v]) % mod\n if (S[i][j] < sum) (S[i][j] = sum), (P[i][j] = P[u][v])\n }\n }\n }\n return [S[N][N], P[N][N]]\n}",
"const pathsWithMaxScore = (\n board,\n DIRS = [\n [-1, -1],\n [-1, 0],\n [0, -1],\n ],\n mod = 1e9 + 7\n) => {\n const m = board.length,\n n = board[0].length\n const dpSum = Array.from({ length: m }, () => Array(n).fill(0))\n const dpCnt = Array.from({ length: m }, () => Array(n).fill(0))\n dpCnt[m - 1][n - 1] = 1 // start at the bottom right square\n for (let r = m - 1; r >= 0; r--) {\n for (let c = n - 1; c >= 0; c--) {\n if (dpCnt[r][c] === 0) continue // can't reach to this square\n for (let dir of DIRS) {\n let nr = r + dir[0],\n nc = c + dir[1]\n if (nr >= 0 && nc >= 0 && board[nr].charAt(nc) !== 'X') {\n let nsum = dpSum[r][c]\n if (board[nr].charAt(nc) !== 'E') nsum += board[nr].charAt(nc) - '0'\n if (nsum > dpSum[nr][nc]) {\n dpCnt[nr][nc] = dpCnt[r][c]\n dpSum[nr][nc] = nsum\n } else if (nsum === dpSum[nr][nc]) {\n dpCnt[nr][nc] = (dpCnt[nr][nc] + dpCnt[r][c]) % mod\n }\n }\n }\n }\n }\n return [dpSum[0][0], dpCnt[0][0]]\n}"
] |
|
1,302 | deepest-leaves-sum | [
"Traverse the tree to find the max depth.",
"Traverse the tree again to compute the sum required."
] | /**
* 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 deepestLeavesSum = function(root) {
}; | Given the root of a binary tree, return the sum of values of its deepest leaves.
Example 1:
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15
Example 2:
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 19
Constraints:
The number of nodes in the tree is in the range [1, 104].
1 <= Node.val <= 100
| Medium | [
"tree",
"depth-first-search",
"breadth-first-search",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const deepestLeavesSum = function(root) {\n let res= 0\n let q = [root]\n while(q.length) {\n const size = q.length\n const tmp = []\n res = 0\n for(let i = 0; i < size; i++) {\n res += q[i].val\n if(q[i].left) tmp.push(q[i].left)\n if(q[i].right) tmp.push(q[i].right)\n }\n \n q = tmp\n }\n return res\n};"
] |
1,304 | find-n-unique-integers-sum-up-to-zero | [
"Return an array where the values are symmetric. (+x , -x).",
"If n is odd, append value 0 in your returned array."
] | /**
* @param {number} n
* @return {number[]}
*/
var sumZero = function(n) {
}; | Given an integer n, return any array containing n unique integers such that they add up to 0.
Example 1:
Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].
Example 2:
Input: n = 3
Output: [-1,0,1]
Example 3:
Input: n = 1
Output: [0]
Constraints:
1 <= n <= 1000
| Easy | [
"array",
"math"
] | [
"const sumZero = function(n) {\n const num = ~~(n / 2)\n const odd = n % 2 === 1\n const res = pair(num)\n if(odd) res.push(0)\n return res\n};\n\nfunction pair(num) {\n const set = new Set()\n const res = []\n for(let i = 1; i <= num; i++) res.push(i, -i)\n return res\n}"
] |
|
1,305 | all-elements-in-two-binary-search-trees | [
"Traverse the first tree in list1 and the second tree in list2.",
"Merge the two trees in one list and sort it."
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root1
* @param {TreeNode} root2
* @return {number[]}
*/
var getAllElements = function(root1, root2) {
}; | Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.
Example 1:
Input: root1 = [2,1,4], root2 = [1,0,3]
Output: [0,1,1,2,3,4]
Example 2:
Input: root1 = [1,null,8], root2 = [8,1]
Output: [1,1,8,8]
Constraints:
The number of nodes in each tree is in the range [0, 5000].
-105 <= Node.val <= 105
| Medium | [
"tree",
"depth-first-search",
"binary-search-tree",
"sorting",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"var getAllElements = function(root1, root2) {\n const set1 = new Set(), set2 = new Set()\n traverse(root1, set1)\n traverse(root2, set2)\n const res = []\n const it1 = set1[Symbol.iterator]()\n const it2 = set2[Symbol.iterator]()\n let { value: value1, done: done1 } = it1.next()\n let { value: value2, done: done2 } = it2.next()\n while(done1 === false || done2 === false) {\n if(done2 || value1 < value2) {\n res.push(value1)\n const obj = it1.next()\n value1 = obj.value\n done1 = obj.done\n }else {\n res.push(value2)\n const obj = it2.next()\n value2 = obj.value\n done2 = obj.done\n }\n }\n \n \n return res\n \n \n function traverse(node, set) {\n if(node == null) return\n traverse(node.left, set)\n set.add(node.val)\n traverse(node.right, set)\n }\n};"
] |
1,306 | jump-game-iii | [
"Think of BFS to solve the problem.",
"When you reach a position with a value = 0 then return true."
] | /**
* @param {number[]} arr
* @param {number} start
* @return {boolean}
*/
var canReach = function(arr, start) {
}; | Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach any index with value 0.
Notice that you can not jump outside of the array at any time.
Example 1:
Input: arr = [4,2,3,0,3,1,2], start = 5
Output: true
Explanation:
All possible ways to reach at index 3 with value 0 are:
index 5 -> index 4 -> index 1 -> index 3
index 5 -> index 6 -> index 4 -> index 1 -> index 3
Example 2:
Input: arr = [4,2,3,0,3,1,2], start = 0
Output: true
Explanation:
One possible way to reach at index 3 with value 0 is:
index 0 -> index 4 -> index 1 -> index 3
Example 3:
Input: arr = [3,0,2,1,2], start = 2
Output: false
Explanation: There is no way to reach at index 1 with value 0.
Constraints:
1 <= arr.length <= 5 * 104
0 <= arr[i] < arr.length
0 <= start < arr.length
| Medium | [
"array",
"depth-first-search",
"breadth-first-search"
] | [
"const canReach = function(arr, start) {\n const s = new Set()\n return helper(arr, start, s)\n};\n\nfunction helper(arr, start, s) {\n if(start < 0 || start >= arr.length || s.has(start)) return false\n s.add(start)\n if(arr[start] === 0) return true\n \n return helper(arr, start + arr[start], s) || helper(arr, start - arr[start], s)\n}",
"const canReach = function (A, i) {\n return (\n 0 <= i &&\n i < A.length &&\n A[i] >= 0 &&\n (!(A[i] = -A[i]) || canReach(A, i + A[i]) || canReach(A, i - A[i]))\n )\n}",
"const canReach = function(arr, start) {\n const q = [start]\n const s = new Set()\n while(q.length) {\n const len = q.length\n for(let i = 0; i < len; i++) {\n const cur = q.shift()\n s.add(cur)\n if(arr[cur] === 0) return true\n if(!s.has(cur + arr[cur])) q.push(cur + arr[cur])\n if(!s.has(cur - arr[cur])) q.push(cur - arr[cur])\n }\n }\n return false\n};"
] |
|
1,307 | verbal-arithmetic-puzzle | [
"Use Backtracking and pruning to solve this problem.",
"If you set the values of some digits (from right to left), the other digits will be constrained."
] | /**
* @param {string[]} words
* @param {string} result
* @return {boolean}
*/
var isSolvable = function(words, result) {
}; | Given an equation, represented by words on the left side and the result on the right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
No two characters can map to the same digit.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on the left side (words) will equal to the number on the right side (result).
Return true if the equation is solvable, otherwise return false.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Explanation: There is no possible mapping to satisfy the equation, so we return false.
Note that two different characters cannot map to the same digit.
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contain only uppercase English letters.
The number of different characters used in the expression is at most 10.
| Hard | [
"array",
"math",
"string",
"backtracking"
] | [
"const isSolvable = function (words, result) {\n const _isSolvable = (wordIndex, charIndex, wordsSum, resultSum, num) => {\n if (wordIndex >= words.length) {\n return wordsSum === resultSum\n }\n const wordLen = words[wordIndex].length\n if (charIndex >= wordLen) {\n if (wordIndex === words.length - 1) {\n return _isSolvable(wordIndex + 1, 0, wordsSum, num, 0)\n }\n return _isSolvable(wordIndex + 1, 0, wordsSum + num, resultSum, 0)\n }\n const char = words[wordIndex][charIndex]\n if (map.get(char) !== undefined) {\n if (map.get(char) === 0 && num === 0 && charIndex >= 1) {\n return false\n }\n return _isSolvable(\n wordIndex,\n charIndex + 1,\n wordsSum,\n resultSum,\n num * 10 + map.get(char)\n )\n }\n for (let digit = 0; digit <= 9; digit++) {\n if (digit === 0 && num === 0 && wordLen > 1) continue\n if (map.get(digit) !== undefined) continue\n map.set(digit, char)\n map.set(char, digit)\n if (\n _isSolvable(\n wordIndex,\n charIndex + 1,\n wordsSum,\n resultSum,\n num * 10 + digit\n )\n ) {\n return true\n }\n map.set(digit, undefined)\n map.set(char, undefined)\n }\n return false\n }\n const map = new Map()\n words = [...words, result]\n return _isSolvable(0, 0, 0, 0, 0)\n}"
] |
|
1,309 | decrypt-string-from-alphabet-to-integer-mapping | [
"Scan from right to left, in each step of the scanning check whether there is a trailing \"#\" 2 indexes away."
] | /**
* @param {string} s
* @return {string}
*/
var freqAlphabets = function(s) {
}; | You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows:
Characters ('a' to 'i') are represented by ('1' to '9') respectively.
Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.
Return the string formed after mapping.
The test cases are generated so that a unique mapping will always exist.
Example 1:
Input: s = "10#11#12"
Output: "jkab"
Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".
Example 2:
Input: s = "1326#"
Output: "acz"
Constraints:
1 <= s.length <= 1000
s consists of digits and the '#' letter.
s will be a valid string such that mapping is always possible.
| Easy | [
"string"
] | [
"const freqAlphabets = function(s) {\n const n = s.length, a = 'a'.charCodeAt(0) - 1\n let res = '', cur = '', num = 0\n\n for(let i = n - 1; i >= 0; i--) {\n const ch = s[i]\n if(cur === '') {\n if(ch === '#') {\n cur = ch\n num = 0\n } else{\n res = (String.fromCharCode(a + (+ch))) + res\n }\n } else {\n if (num < 1) {\n cur = ch + cur\n num++\n } else {\n cur = ch + cur\n const tmp = cur.slice(0,cur.length - 1)\n res = (String.fromCharCode(a + (+tmp))) + res\n cur = ''\n num = 0\n }\n }\n }\n return res\n};"
] |
|
1,310 | xor-queries-of-a-subarray | [
"What is the result of x ^ y ^ x ?",
"Compute the prefix sum for XOR.",
"Process the queries with the prefix sum values."
] | /**
* @param {number[]} arr
* @param {number[][]} queries
* @return {number[]}
*/
var xorQueries = function(arr, queries) {
}; | You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti].
For each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ).
Return an array answer where answer[i] is the answer to the ith query.
Example 1:
Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
Output: [2,7,14,8]
Explanation:
The binary representation of the elements in the array are:
1 = 0001
3 = 0011
4 = 0100
8 = 1000
The XOR values for queries are:
[0,1] = 1 xor 3 = 2
[1,2] = 3 xor 4 = 7
[0,3] = 1 xor 3 xor 4 xor 8 = 14
[3,3] = 8
Example 2:
Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
Output: [8,0,4,4]
Constraints:
1 <= arr.length, queries.length <= 3 * 104
1 <= arr[i] <= 109
queries[i].length == 2
0 <= lefti <= righti < arr.length
| Medium | [
"array",
"bit-manipulation",
"prefix-sum"
] | [
" \nconst xorQueries = function(arr, queries) {\n const pre = [], n = arr.length\n let xor = arr[0]\n pre.push(xor)\n for(let i = 1; i < n; i++) {\n pre[i] = pre[i - 1] ^ arr[i]\n }\n\n const res = queries.map((e, i) => {\n const [l, r] = e\n return pre[r] ^ (l > 0 ? pre[l - 1] : 0)\n })\n return res\n};",
"const xorQueries = function(arr, queries) {\n const xorArr = []\n xorArr[0] = 0\n const n = arr.length\n for(let i = 0; i < n; i++) {\n const cur = arr[i]\n xorArr.push(cur ^ xorArr[xorArr.length - 1])\n }\n const res = []\n for(const [l, r] of queries) {\n res.push(xorArr[r + 1] ^ xorArr[l])\n }\n \n return res\n};"
] |
|
1,311 | get-watched-videos-by-your-friends | [
"Do BFS to find the kth level friends.",
"Then collect movies saw by kth level friends and sort them accordingly."
] | /**
* @param {string[][]} watchedVideos
* @param {number[][]} friends
* @param {number} id
* @param {number} level
* @return {string[]}
*/
var watchedVideosByFriends = function(watchedVideos, friends, id, level) {
}; | There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i.
Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.
Example 1:
Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1
Output: ["B","C"]
Explanation:
You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):
Person with id = 1 -> watchedVideos = ["C"]
Person with id = 2 -> watchedVideos = ["B","C"]
The frequencies of watchedVideos by your friends are:
B -> 1
C -> 2
Example 2:
Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2
Output: ["D"]
Explanation:
You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).
Constraints:
n == watchedVideos.length == friends.length
2 <= n <= 100
1 <= watchedVideos[i].length <= 100
1 <= watchedVideos[i][j].length <= 8
0 <= friends[i].length < n
0 <= friends[i][j] < n
0 <= id < n
1 <= level < n
if friends[i] contains j, then friends[j] contains i
| Medium | [
"array",
"hash-table",
"breadth-first-search",
"graph",
"sorting"
] | null | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.