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,829 | maximum-xor-for-each-query | [
"Note that the maximum possible XOR result is always 2^(maximumBit) - 1",
"So the answer for a prefix is the XOR of that prefix XORed with 2^(maximumBit)-1"
] | /**
* @param {number[]} nums
* @param {number} maximumBit
* @return {number[]}
*/
var getMaximumXor = function(nums, maximumBit) {
}; | You are given a sorted array nums of n non-negative integers and an integer maximumBit. You want to perform the following query n times:
Find a non-negative integer k < 2maximumBit such that nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k is maximized. k is the answer to the ith query.
Remove the last element from the current array nums.
Return an array answer, where answer[i] is the answer to the ith query.
Example 1:
Input: nums = [0,1,1,3], maximumBit = 2
Output: [0,3,2,3]
Explanation: The queries are answered as follows:
1st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3.
2nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3.
3rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3.
4th query: nums = [0], k = 3 since 0 XOR 3 = 3.
Example 2:
Input: nums = [2,3,4,7], maximumBit = 3
Output: [5,2,6,5]
Explanation: The queries are answered as follows:
1st query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7.
2nd query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7.
3rd query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7.
4th query: nums = [2], k = 5 since 2 XOR 5 = 7.
Example 3:
Input: nums = [0,1,2,2,5,7], maximumBit = 3
Output: [4,3,6,4,6,7]
Constraints:
nums.length == n
1 <= n <= 105
1 <= maximumBit <= 20
0 <= nums[i] < 2maximumBit
nums is sorted in ascending order.
| Medium | [
"array",
"bit-manipulation",
"prefix-sum"
] | [
"const getMaximumXor = function(nums, maximumBit) {\n const n = nums.length\n let xor = nums.reduce((ac, e) => ac ^ e, 0)\n let limit = 2 ** maximumBit - 1\n const res = []\n for(let i = n - 1; i >= 0; i--) {\n const tmp = limit ^ xor\n res.push(tmp)\n xor ^= nums[i]\n }\n \n return res\n};"
] |
|
1,830 | minimum-number-of-operations-to-make-string-sorted | [
"Note that the operations given describe getting the previous permutation of s",
"To solve this problem you need to solve every suffix separately"
] | /**
* @param {string} s
* @return {number}
*/
var makeStringSorted = function(s) {
}; | You are given a string s (0-indexed). You are asked to perform the following operation on s until you get a sorted string:
Find the largest index i such that 1 <= i < s.length and s[i] < s[i - 1].
Find the largest index j such that i <= j < s.length and s[k] < s[i - 1] for all the possible values of k in the range [i, j] inclusive.
Swap the two characters at indices i - 1 and j.
Reverse the suffix starting at index i.
Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 109 + 7.
Example 1:
Input: s = "cba"
Output: 5
Explanation: The simulation goes as follows:
Operation 1: i=2, j=2. Swap s[1] and s[2] to get s="cab", then reverse the suffix starting at 2. Now, s="cab".
Operation 2: i=1, j=2. Swap s[0] and s[2] to get s="bac", then reverse the suffix starting at 1. Now, s="bca".
Operation 3: i=2, j=2. Swap s[1] and s[2] to get s="bac", then reverse the suffix starting at 2. Now, s="bac".
Operation 4: i=1, j=1. Swap s[0] and s[1] to get s="abc", then reverse the suffix starting at 1. Now, s="acb".
Operation 5: i=2, j=2. Swap s[1] and s[2] to get s="abc", then reverse the suffix starting at 2. Now, s="abc".
Example 2:
Input: s = "aabaa"
Output: 2
Explanation: The simulation goes as follows:
Operation 1: i=3, j=4. Swap s[2] and s[4] to get s="aaaab", then reverse the substring starting at 3. Now, s="aaaba".
Operation 2: i=4, j=4. Swap s[3] and s[4] to get s="aaaab", then reverse the substring starting at 4. Now, s="aaaab".
Constraints:
1 <= s.length <= 3000
s consists only of lowercase English letters.
| Hard | [
"math",
"string",
"combinatorics"
] | [
"const makeStringSorted = function (s) {\n const mod = BigInt(10 ** 9 + 7),\n n = s.length\n const a = 'a'.charCodeAt(0)\n let ans = 0n\n const freq = Array(26).fill(0n)\n for (let c of s) {\n freq[c.charCodeAt(0) - a]++\n }\n const fact = Array(n + 1).fill(1n)\n for (let i = 1n; i <= n; i++) {\n fact[i] = (fact[i - 1n] * i) % mod\n }\n let l = n\n for (let c of s) {\n l--\n let t = 0n,\n rev = 1n\n for (let i = 0; i < 26; i++) {\n if (i < c.charCodeAt(0) - a) t += freq[i]\n rev = (rev * fact[freq[i]]) % mod\n }\n ans += ((t * fact[l]) % mod) * modpow(rev, mod - 2n)\n ans %= mod\n freq[c.charCodeAt(0) - a]--\n }\n return Number(ans)\n function modpow(b, p) {\n let ans = 1n\n for (; p; p >>= 1n) {\n if (p & 1n) ans = (ans * b) % mod\n b = (b * b) % mod\n }\n return ans\n }\n}"
] |
|
1,832 | check-if-the-sentence-is-pangram | [
"Iterate over the string and mark each character as found (using a boolean array, bitmask, or any other similar way).",
"Check if the number of found characters equals the alphabet length."
] | /**
* @param {string} sentence
* @return {boolean}
*/
var checkIfPangram = function(sentence) {
}; | A pangram is a sentence where every letter of the English alphabet appears at least once.
Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.
Example 1:
Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: sentence contains at least one of every letter of the English alphabet.
Example 2:
Input: sentence = "leetcode"
Output: false
Constraints:
1 <= sentence.length <= 1000
sentence consists of lowercase English letters.
| Easy | [
"hash-table",
"string"
] | [
"const checkIfPangram = function(sentence) {\n const hash = new Map()\n for(let ch of sentence) {\n if(!hash.has(ch)) hash.set(ch, 0)\n hash.set(ch, hash.get(ch) + 1)\n }\n return hash.size >= 26\n};"
] |
|
1,833 | maximum-ice-cream-bars | [
"It is always optimal to buy the least expensive ice cream bar first.",
"Sort the prices so that the cheapest ice cream bar comes first."
] | /**
* @param {number[]} costs
* @param {number} coins
* @return {number}
*/
var maxIceCream = function(costs, coins) {
}; | It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.
Note: The boy can buy the ice cream bars in any order.
Return the maximum number of ice cream bars the boy can buy with coins coins.
You must solve the problem by counting sort.
Example 1:
Input: costs = [1,3,2,4,1], coins = 7
Output: 4
Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
Example 2:
Input: costs = [10,6,8,7,7,8], coins = 5
Output: 0
Explanation: The boy cannot afford any of the ice cream bars.
Example 3:
Input: costs = [1,6,3,1,2,5], coins = 20
Output: 6
Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
Constraints:
costs.length == n
1 <= n <= 105
1 <= costs[i] <= 105
1 <= coins <= 108
| Medium | [
"array",
"greedy",
"sorting"
] | [
"const maxIceCream = function(costs, coins) {\n costs.sort((a, b) => a - b)\n let res = 0, idx = 0\n while(coins >= costs[idx]) {\n res++\n coins -= costs[idx++]\n }\n \n return res\n};"
] |
|
1,834 | single-threaded-cpu | [
"To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element",
"We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks"
] | /**
* @param {number[][]} tasks
* @return {number[]}
*/
var getOrder = function(tasks) {
}; | You are given n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available to process at enqueueTimei and will take processingTimei to finish processing.
You have a single-threaded CPU that can process at most one task at a time and will act in the following way:
If the CPU is idle and there are no available tasks to process, the CPU remains idle.
If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
Once a task is started, the CPU will process the entire task without stopping.
The CPU can finish a task then start a new one instantly.
Return the order in which the CPU will process the tasks.
Example 1:
Input: tasks = [[1,2],[2,4],[3,2],[4,1]]
Output: [0,2,3,1]
Explanation: The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
Example 2:
Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
Output: [4,3,2,0,1]
Explanation: The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
Constraints:
tasks.length == n
1 <= n <= 105
1 <= enqueueTimei, processingTimei <= 109
| Medium | [
"array",
"sorting",
"heap-priority-queue"
] | [
"const getOrder = function(tasks) {\n const pq = new PriorityQueue(compare), n = tasks.length\n const res = []\n let time = 0, i = 0\n for(let i = 0; i < n; i++) tasks[i].push(i)\n tasks.sort((a, b) => a[0] - b[0])\n \n time = tasks[0][0]\n while(i < n || !pq.isEmpty()) {\n while ((i < n) && (tasks[i][0] <= time)) {\n pq.push([tasks[i][1], tasks[i][2]])\n i++\n }\n if(!pq.isEmpty()) {\n const [dur, idx] = pq.pop()\n time += dur\n res.push(idx)\n } else if(i < n) {\n time = tasks[i][0]\n }\n\n }\n\n return res\n};\n\nfunction compare(a, b) {\n if(a[0] < b[0]) return true\n else if (a[0] > b[0]) return false\n else {\n return a[1] < b[1]\n }\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}",
"const getOrder = function(tasks) {\n const pq = new PriorityQueue(compare), n = tasks.length\n const res = []\n let time = 0, i = 0\n for(let i = 0; i < n; i++) tasks[i].push(i)\n tasks.sort((a, b) => a[0] - b[0])\n \n while(i < n || !pq.isEmpty()) {\n if(pq.isEmpty()) {\n time = Math.max(time, tasks[i][0])\n }\n while(i < n && time >= tasks[i][0]) {\n pq.push([tasks[i][1], tasks[i][2]])\n i++\n }\n const [dur, idx] = pq.pop()\n time += dur\n res.push(idx)\n }\n\n return res\n};\n\nfunction compare(a, b) {\n if(a[0] < b[0]) return true\n else if (a[0] > b[0]) return false\n else {\n return a[1] < b[1]\n }\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}",
"const getOrder = function(tasks) {\n const n = tasks.length\n const pq = new PriorityQueue((a, b) => a[0] === b[0] ? a[1] < b[1] : a[0] < b[0])\n tasks.forEach((e, i) => e.push(i))\n tasks.sort((a, b) => a[0] - b[0])\n let idx = 0, time = 0\n const res = []\n\n while(idx < n || !pq.isEmpty()) {\n while(idx < n && tasks[idx][0] <= time) {\n pq.push([tasks[idx][1], task[idx][2]])\n idx++\n }\n if(!pq.isEmpty()) {\n const tmp = pq.pop()\n time += tmp[0]\n res.push(tmp[1])\n } else if(idx < n) {\n time = tasks[idx][0]\n }\n }\n return res\n\n};",
"const getOrder = function (tasks) {\n tasks = tasks.map((e, idx) => [e[0], e[1], idx])\n tasks.sort((a, b) => a[0] - b[0])\n const pq = new PriorityQueue(compare)\n const res = []\n let i = 0,\n t = 0\n while (i < tasks.length) {\n while (i < tasks.length && tasks[i][0] <= t) {\n let [ent, pt, ind] = tasks[i]\n i += 1\n pq.push([pt, ind])\n }\n if (pq.size() == 0) {\n if (i < tasks.length) t = tasks[i][0]\n continue\n }\n let [pt, ind] = pq.pop()\n res.push(ind)\n t += pt\n }\n while (pq.size()) {\n let [pt, index] = pq.pop()\n res.push(index)\n }\n return res\n}\n\nfunction compare(a, b) {\n if (a[0] < b[0]) return true\n else if (a[0] > b[0]) return false\n else {\n return a[1] < b[1]\n }\n}"
] |
|
1,835 | find-xor-sum-of-all-pairs-bitwise-and | [
"Think about (a&b) ^ (a&c). Can you simplify this expression?",
"It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...).",
"Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[1]) ^ (arr2XorSum&arr1[2]) ^ ... = arr2XorSum & arr1XorSum."
] | /**
* @param {number[]} arr1
* @param {number[]} arr2
* @return {number}
*/
var getXORSum = function(arr1, arr2) {
}; | The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.
For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.
You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.
Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length.
Return the XOR sum of the aforementioned list.
Example 1:
Input: arr1 = [1,2,3], arr2 = [6,5]
Output: 0
Explanation: The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].
The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.
Example 2:
Input: arr1 = [12], arr2 = [4]
Output: 4
Explanation: The list = [12 AND 4] = [4]. The XOR sum = 4.
Constraints:
1 <= arr1.length, arr2.length <= 105
0 <= arr1[i], arr2[j] <= 109
| Hard | [
"array",
"math",
"bit-manipulation"
] | [
"const getXORSum = function(arr1, arr2) {\n let a = 0, b = 0\n for(const e of arr1) a ^= e\n for(const e of arr2) b ^= e\n \n return a & b\n};",
"// On every bit XOR acts as modulo 2 addition and AND acts as modulo 2 multiplication.\n// The set {0,1} with modulo 2 addition and multiplication is the field GF(2) and the distributive property holds in every field.\n\n\nconst getXORSum = function(arr1, arr2) {\n const bits = Array(32).fill(0)\n for (let v of arr2) {\n let pos = 0;\n while (v > 0) {\n if (v & 1) {\n bits[pos]++;\n }\n v = v >> 1;\n pos++;\n }\n }\n\n let res = 0;\n\n for (let v of arr1) {\n let pos = 0;\n let tmp = 0;\n while (v > 0) {\n if (v & 1) {\n if (bits[pos] % 2 == 1) {\n tmp |= (1 << pos);\n }\n }\n v = v >> 1;\n pos++;\n }\n\n res ^= tmp;\n }\n\n return res;\n};",
"const getXORSum = function(arr1, arr2) {\n let x1 = arr1[0], x2 = arr2[0]\n for(let i = 1; i < arr1.length; i++) x1 ^= arr1[i]\n for(let i = 1; i < arr2.length; i++) x2 ^= arr2[i]\n return x1 & x2\n};"
] |
|
1,837 | sum-of-digits-in-base-k | [
"Convert the given number into base k.",
"Use mod-10 to find what each digit is after the conversion and sum the digits."
] | /**
* @param {number} n
* @param {number} k
* @return {number}
*/
var sumBase = function(n, k) {
}; | Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k.
After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.
Example 1:
Input: n = 34, k = 6
Output: 9
Explanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
Example 2:
Input: n = 10, k = 10
Output: 1
Explanation: n is already in base 10. 1 + 0 = 1.
Constraints:
1 <= n <= 100
2 <= k <= 10
| Easy | [
"math"
] | [
"const sumBase = function(n, k) {\n let str = n.toString(k)\n let res = 0\n for(let ch of str) res += +ch\n \n return res\n};"
] |
|
1,838 | frequency-of-the-most-frequent-element | [
"Note that you can try all values in a brute force manner and find the maximum frequency of that value.",
"To find the maximum frequency of a value consider the biggest elements smaller than or equal to this value"
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var maxFrequency = function(nums, k) {
}; | The frequency of an element is the number of times it occurs in an array.
You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maximum possible frequency of an element after performing at most k operations.
Example 1:
Input: nums = [1,2,4], k = 5
Output: 3
Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4].
4 has a frequency of 3.
Example 2:
Input: nums = [1,4,8,13], k = 5
Output: 2
Explanation: There are multiple optimal solutions:
- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.
- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.
- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.
Example 3:
Input: nums = [3,9,6], k = 2
Output: 1
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= k <= 105
| Medium | [
"array",
"binary-search",
"greedy",
"sliding-window",
"sorting",
"prefix-sum"
] | [
"const maxFrequency = function(nums, k) {\n let res = 1, i = 0, j = 0, sum = 0\n const n = nums.length\n nums.sort((a, b) => a - b)\n for(j = 0; j < n; j++) {\n sum += nums[j]\n while(sum + k < (j - i + 1) * nums[j]) {\n sum -= nums[i]\n i++\n }\n res = Math.max(res, j - i + 1)\n } \n return res\n};",
"const maxFrequency = function(nums, k) {\n nums.sort((a, b) => a - b)\n let i = 0, sum = 0, res = 1\n for(let j = 0; j < nums.length; j++) {\n sum += nums[j]\n while(sum + k < (j - i + 1) * nums[j]) {\n sum -= nums[i]\n i++\n }\n res = Math.max(res, j - i + 1)\n }\n return res\n};"
] |
|
1,839 | longest-substring-of-all-vowels-in-order | [
"Start from each 'a' and find the longest beautiful substring starting at that index.",
"Based on the current character decide if you should include the next character in the beautiful substring."
] | /**
* @param {string} word
* @return {number}
*/
var longestBeautifulSubstring = function(word) {
}; | A string is considered beautiful if it satisfies the following conditions:
Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.
The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.).
For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful.
Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu"
Output: 13
Explanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13.
Example 2:
Input: word = "aeeeiiiioooauuuaeiou"
Output: 5
Explanation: The longest beautiful substring in word is "aeiou" of length 5.
Example 3:
Input: word = "a"
Output: 0
Explanation: There is no beautiful substring, so return 0.
Constraints:
1 <= word.length <= 5 * 105
word consists of characters 'a', 'e', 'i', 'o', and 'u'.
| Medium | [
"string",
"sliding-window"
] | [
"function longestBeautifulSubstring(word) {\n let res = 0, cur = 'a', cnt = 0\n const set = new Set()\n for(let ch of word) {\n if(ch < cur) {\n set.clear()\n cnt = 0\n cur = 'a'\n if(ch === cur) {\n cnt++\n set.add(cur)\n }\n } else {\n cnt++\n set.add(ch)\n cur = ch\n if(set.size === 5) res = Math.max(res, cnt)\n }\n }\n return res\n}",
"function longestBeautifulSubstring(word) {\n let res = 0, cur = 'a', cnt = 0\n const set = new Set()\n for (let ch of word) {\n if (ch >= cur) {\n cnt++\n cur = ch\n set.add(ch)\n } else {\n set.clear()\n cnt = 0\n cur = 'a'\n if(ch === cur) {\n set.add(ch)\n cnt++\n }\n }\n if (set.size === 5) {\n res = Math.max(res, cnt)\n }\n }\n\n return res\n}",
"function longestBeautifulSubstring(word) {\n let result = 0,\n current = 0\n let currentVowel = \"a\"\n const set = new Set()\n for (let i = 0; i < word.length; i++)\n if (word.charAt(i) < currentVowel) {\n set.clear()\n if (word.charAt(i) == \"a\") {\n set.add(\"a\")\n current = 1\n } else current = 0\n currentVowel = \"a\"\n } else {\n current++\n currentVowel = word.charAt(i)\n set.add(currentVowel)\n if (set.size == 5) result = Math.max(result, current)\n }\n return result\n}"
] |
|
1,840 | maximum-building-height | [
"Is it possible to find the max height if given the height range of a particular building?",
"You can find the height range of a restricted building by doing 2 passes from the left and right."
] | /**
* @param {number} n
* @param {number[][]} restrictions
* @return {number}
*/
var maxBuilding = function(n, restrictions) {
}; | You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n.
However, there are city restrictions on the heights of the new buildings:
The height of each building must be a non-negative integer.
The height of the first building must be 0.
The height difference between any two adjacent buildings cannot exceed 1.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height less than or equal to maxHeighti.
It is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions.
Return the maximum possible height of the tallest building.
Example 1:
Input: n = 5, restrictions = [[2,1],[4,1]]
Output: 2
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.
Example 2:
Input: n = 6, restrictions = []
Output: 5
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.
Example 3:
Input: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]
Output: 5
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.
Constraints:
2 <= n <= 109
0 <= restrictions.length <= min(n - 1, 105)
2 <= idi <= n
idi is unique.
0 <= maxHeighti <= 109
| Hard | [
"array",
"math"
] | [
"var maxBuilding = function (n, restrictions) {\n restrictions.sort((a, b) => a[0] - b[0]);\n let prevInd = 1,\n prevH = 0;\n for (let i = 0; i < restrictions.length; i++) {\n restrictions[i][1] = Math.min(\n restrictions[i][1],\n prevH + (restrictions[i][0] - prevInd)\n );\n prevInd = restrictions[i][0];\n prevH = restrictions[i][1];\n }\n\n for (let i = restrictions.length - 2; i >= 0; i--) {\n restrictions[i][1] = Math.min(\n restrictions[i][1],\n restrictions[i + 1][1] + (restrictions[i + 1][0] - restrictions[i][0])\n );\n }\n\n let ph = 0,\n pInd = 1,\n highest = 0;\n for (let i = 0; i < restrictions.length; i++) {\n let ind = restrictions[i][0];\n let h = restrictions[i][1];\n if (ph < h) {\n h = Math.min(h, ph + (ind - pInd));\n\n let remains = Math.max(0, ind - pInd - (h - ph));\n highest = Math.max(highest, h + ~~(remains / 2));\n } else {\n let remains = ind - pInd - (ph - h);\n highest = Math.max(highest, ph + ~~(remains / 2));\n }\n ph = h;\n pInd = ind;\n }\n highest = Math.max(highest, ph + (n - pInd));\n return highest;\n};"
] |
|
1,844 | replace-all-digits-with-characters | [
"We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it",
"Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position"
] | /**
* @param {string} s
* @return {string}
*/
var replaceDigits = function(s) {
}; | You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices.
There is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c.
For example, shift('a', 5) = 'f' and shift('x', 0) = 'x'.
For every odd index i, you want to replace the digit s[i] with shift(s[i-1], s[i]).
Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.
Example 1:
Input: s = "a1c1e1"
Output: "abcdef"
Explanation: The digits are replaced as follows:
- s[1] -> shift('a',1) = 'b'
- s[3] -> shift('c',1) = 'd'
- s[5] -> shift('e',1) = 'f'
Example 2:
Input: s = "a1b2c3d4e"
Output: "abbdcfdhe"
Explanation: The digits are replaced as follows:
- s[1] -> shift('a',1) = 'b'
- s[3] -> shift('b',2) = 'd'
- s[5] -> shift('c',3) = 'f'
- s[7] -> shift('d',4) = 'h'
Constraints:
1 <= s.length <= 100
s consists only of lowercase English letters and digits.
shift(s[i-1], s[i]) <= 'z' for all odd indices i.
| Easy | [
"string"
] | [
"const replaceDigits = function(s) {\n let arr = s.split('')\n for(let i = 1; i < s.length; i += 2) {\n arr[i] = shift(s[i - 1], +s[i])\n }\n\n return arr.join('')\n\n function shift(ch, x) {\n return String.fromCharCode(ch.charCodeAt(0) + x)\n }\n};"
] |
|
1,845 | seat-reservation-manager | [
"You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time.",
"You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an element, in a reasonable time.",
"Ordered sets support these operations."
] | /**
* @param {number} n
*/
var SeatManager = function(n) {
};
/**
* @return {number}
*/
SeatManager.prototype.reserve = function() {
};
/**
* @param {number} seatNumber
* @return {void}
*/
SeatManager.prototype.unreserve = function(seatNumber) {
};
/**
* Your SeatManager object will be instantiated and called as such:
* var obj = new SeatManager(n)
* var param_1 = obj.reserve()
* obj.unreserve(seatNumber)
*/ | Design a system that manages the reservation state of n seats that are numbered from 1 to n.
Implement the SeatManager class:
SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available.
int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.
void unreserve(int seatNumber) Unreserves the seat with the given seatNumber.
Example 1:
Input
["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"]
[[5], [], [], [2], [], [], [], [], [5]]
Output
[null, 1, 2, null, 2, 3, 4, 5, null]
Explanation
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].
seatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are [3,4,5], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are [4,5], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].
Constraints:
1 <= n <= 105
1 <= seatNumber <= n
For each call to reserve, it is guaranteed that there will be at least one unreserved seat.
For each call to unreserve, it is guaranteed that seatNumber will be reserved.
At most 105 calls in total will be made to reserve and unreserve.
| Medium | [
"design",
"heap-priority-queue"
] | null | [] |
1,846 | maximum-element-after-decreasing-and-rearranging | [
"Sort the Array.",
"Decrement each element to the largest integer that satisfies the conditions."
] | /**
* @param {number[]} arr
* @return {number}
*/
var maximumElementAfterDecrementingAndRearranging = function(arr) {
}; | You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
The value of the first element in arr must be 1.
The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x.
There are 2 types of operations that you can perform any number of times:
Decrease the value of any element of arr to a smaller positive integer.
Rearrange the elements of arr to be in any order.
Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.
Example 1:
Input: arr = [2,2,1,2,1]
Output: 2
Explanation:
We can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1].
The largest element in arr is 2.
Example 2:
Input: arr = [100,1,1000]
Output: 3
Explanation:
One possible way to satisfy the conditions is by doing the following:
1. Rearrange arr so it becomes [1,100,1000].
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now arr = [1,2,3], which satisfies the conditions.
The largest element in arr is 3.
Example 3:
Input: arr = [1,2,3,4,5]
Output: 5
Explanation: The array already satisfies the conditions, and the largest element is 5.
Constraints:
1 <= arr.length <= 105
1 <= arr[i] <= 109
| Medium | [
"array",
"greedy",
"sorting"
] | [
"const maximumElementAfterDecrementingAndRearranging = function(arr) {\n arr.sort((a, b) => a - b);\n arr[0] = 1;\n for(let i = 1; i < arr.length; i++) {\n if(arr[i] <= arr[i - 1] + 1) continue;\n arr[i] = arr[i - 1] + 1;\n }\n return arr[arr.length - 1];\n};"
] |
|
1,847 | closest-room | [
"Is there a way to sort the queries so it's easier to search the closest room larger than the size?",
"Use binary search to speed up the search time."
] | /**
* @param {number[][]} rooms
* @param {number[][]} queries
* @return {number[]}
*/
var closestRoom = function(rooms, queries) {
}; | There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] = [roomIdi, sizei] denotes that there is a room with room number roomIdi and size equal to sizei. Each roomIdi is guaranteed to be unique.
You are also given k queries in a 2D array queries where queries[j] = [preferredj, minSizej]. The answer to the jth query is the room number id of a room such that:
The room has a size of at least minSizej, and
abs(id - preferredj) is minimized, where abs(x) is the absolute value of x.
If there is a tie in the absolute difference, then use the room with the smallest such id. If there is no such room, the answer is -1.
Return an array answer of length k where answer[j] contains the answer to the jth query.
Example 1:
Input: rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]
Output: [3,-1,3]
Explanation: The answers to the queries are as follows:
Query = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.
Query = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.
Query = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.
Example 2:
Input: rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]
Output: [2,1,3]
Explanation: The answers to the queries are as follows:
Query = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.
Query = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.
Query = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.
Constraints:
n == rooms.length
1 <= n <= 105
k == queries.length
1 <= k <= 104
1 <= roomIdi, preferredj <= 107
1 <= sizei, minSizej <= 107
| Hard | [
"array",
"binary-search",
"sorting"
] | [
" const closestRoom = function (rooms, queries) {\n rooms.sort((a, b) => b[1] - a[1])\n const n = queries.length\n const minSize = Array(n).fill(0).map((_, i) => i)\n .sort((a, b) => queries[b][1] - queries[a][1])\n\n const res = new Array(queries.length).fill(-1)\n const bst = new BinarySearchTree()\n let currentRoom = 0\n\n minSize.forEach((query) => {\n const [preferredRoom, minimumSize] = queries[query]\n if (rooms[0][1] < minimumSize) return\n\n while (currentRoom < rooms.length && rooms[currentRoom][1] >= minimumSize) {\n bst.add(rooms[currentRoom][0])\n currentRoom++\n }\n\n res[query] = bst.search(preferredRoom)\n })\n\n return res\n}\n\nclass BinarySearchTree {\n constructor() {\n this.root = null\n }\n\n add(val) {\n this.root = this.insert(this.root, val)\n }\n\n insert(node, val) {\n if (!node) return new TreeNode(val)\n if (node.val < val) {\n node.right = this.insert(node.right, val)\n } else {\n node.left = this.insert(node.left, val)\n }\n return node\n }\n\n search(val, node = this.root) {\n if (node.val === val) return val\n const currentDistance = Math.abs(node.val - val)\n const nextChild = node.val < val ? node.right : node.left\n if (!nextChild) return node.val\n const closestChild = this.search(val, nextChild)\n const childDistance = Math.abs(closestChild - val)\n if (childDistance < currentDistance) return closestChild\n if (childDistance === currentDistance)\n return Math.min(closestChild, node.val)\n return node.val\n }\n}\n\nclass TreeNode {\n constructor(val) {\n this.val = val\n this.left = null\n this.right = null\n }\n}"
] |
|
1,848 | minimum-distance-to-the-target-element | [
"Loop in both directions until you find the target element.",
"For each index i such that nums[i] == target calculate abs(i - start)."
] | /**
* @param {number[]} nums
* @param {number} target
* @param {number} start
* @return {number}
*/
var getMinDistance = function(nums, target, start) {
}; | Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x.
Return abs(i - start).
It is guaranteed that target exists in nums.
Example 1:
Input: nums = [1,2,3,4,5], target = 5, start = 3
Output: 1
Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.
Example 2:
Input: nums = [1], target = 1, start = 0
Output: 0
Explanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.
Example 3:
Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0
Output: 0
Explanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 104
0 <= start < nums.length
target is in nums.
| Easy | [
"array"
] | [
"const getMinDistance = function(nums, target, start) {\n let min = Infinity, res = -1\n for(let i = 0; i < nums.length; i++) {\n if(nums[i] === target) {\n if(min > Math.abs(i - start)) {\n res = i\n min = Math.abs(i - start)\n }\n }\n }\n \n return min\n \n};"
] |
|
1,849 | splitting-a-string-into-descending-consecutive-values | [
"One solution is to try all possible splits using backtrack",
"Look out for trailing zeros in string"
] | /**
* @param {string} s
* @return {boolean}
*/
var splitString = function(s) {
}; | You are given a string s that consists of only digits.
Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1.
For example, the string s = "0090089" can be split into ["0090", "089"] with numerical values [90,89]. The values are in descending order and adjacent values differ by 1, so this way is valid.
Another example, the string s = "001" can be split into ["0", "01"], ["00", "1"], or ["0", "0", "1"]. However all the ways are invalid because they have numerical values [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order.
Return true if it is possible to split s as described above, or false otherwise.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "1234"
Output: false
Explanation: There is no valid way to split s.
Example 2:
Input: s = "050043"
Output: true
Explanation: s can be split into ["05", "004", "3"] with numerical values [5,4,3].
The values are in descending order with adjacent values differing by 1.
Example 3:
Input: s = "9080701"
Output: false
Explanation: There is no valid way to split s.
Constraints:
1 <= s.length <= 20
s only consists of digits.
| Medium | [
"string",
"backtracking"
] | [
"const splitString = function(s) {\n return helper(s, null)\n};\n\nfunction helper(str, previous) {\n for(let i = 0, n = str.length; i < n; i++) {\n const tmp = +(str.slice(0, i + 1))\n if(previous == null) {\n if(helper(str.slice(i + 1), tmp)) return true\n } else if(previous - tmp === 1 && (i === n - 1 || helper(str.slice(i + 1), tmp))) return true\n }\n \n return false\n}",
"const splitString = function(s) {\n return dfs(s, 0, [Infinity])\n};\n\nfunction dfs(str, idx, arr) {\n if(idx >= str.length && arr.length > 2) return true\n for(let i = idx; i < str.length; i++) {\n const tmp = str.slice(idx, i + 1)\n const num = parseInt(tmp, 10)\n const pre = arr[arr.length - 1]\n if(num < pre && (pre === Infinity || pre - num === 1)) {\n arr.push(num)\n if(dfs(str, i + 1, arr)) return true \n arr.pop()\n }\n }\n return false\n}"
] |
|
1,850 | minimum-adjacent-swaps-to-reach-the-kth-smallest-number | [
"Find the next permutation of the given string k times.",
"Try to move each element to its correct position and calculate the number of steps."
] | /**
* @param {string} num
* @param {number} k
* @return {number}
*/
var getMinSwaps = function(num, k) {
}; | You are given a string num, representing a large integer, and an integer k.
We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones.
For example, when num = "5489355142":
The 1st smallest wonderful integer is "5489355214".
The 2nd smallest wonderful integer is "5489355241".
The 3rd smallest wonderful integer is "5489355412".
The 4th smallest wonderful integer is "5489355421".
Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer.
The tests are generated in such a way that kth smallest wonderful integer exists.
Example 1:
Input: num = "5489355142", k = 4
Output: 2
Explanation: The 4th smallest wonderful number is "5489355421". To get this number:
- Swap index 7 with index 8: "5489355142" -> "5489355412"
- Swap index 8 with index 9: "5489355412" -> "5489355421"
Example 2:
Input: num = "11112", k = 4
Output: 4
Explanation: The 4th smallest wonderful number is "21111". To get this number:
- Swap index 3 with index 4: "11112" -> "11121"
- Swap index 2 with index 3: "11121" -> "11211"
- Swap index 1 with index 2: "11211" -> "12111"
- Swap index 0 with index 1: "12111" -> "21111"
Example 3:
Input: num = "00123", k = 1
Output: 1
Explanation: The 1st smallest wonderful number is "00132". To get this number:
- Swap index 3 with index 4: "00123" -> "00132"
Constraints:
2 <= num.length <= 1000
1 <= k <= 1000
num only consists of digits.
| Medium | [
"two-pointers",
"string",
"greedy"
] | [
" const getMinSwaps = function (num, k) {\n const temp = num.split('')\n for (let i = 0; i < k; i++) nextPermutation(temp)\n return count(num.split(''), temp, temp.length)\n}\n\nfunction nextPermutation(a) {\n let i = a.length - 2\n //Find the first element which isn't in increasing order fom behind\n while (i >= 0 && a[i] >= a[i + 1]) i--\n //If we found an element\n if (i >= 0) {\n // Find the rightmost element such that a[j] > a[i]\n const j = bSearch(a, i + 1, a.length - 1, a[i])\n // swap a[i] and a[j]\n a[i] = a[i] ^ a[j] ^ (a[j] = a[i])\n }\n //reverse array from i + 1 till end\n reverse(a, i + 1, a.length - 1)\n}\n\nfunction bSearch(a, i, j, key) {\n while (i <= j) {\n const mid = (i + j) >>> 1\n if (key < a[mid]) i = mid + 1\n else j = mid - 1\n }\n return i - 1\n}\n\nfunction reverse(a, i, j) {\n while (i < j) a[i] = a[i] ^ a[j] ^ (a[j--] = a[i++])\n}\n\nfunction count(s1, s2, n) {\n let i = 0,\n j = 0,\n res = 0\n\n while (i < n) {\n j = i\n while (s1[j] != s2[i]) j++\n while (i < j) {\n const temp = s1[j]\n s1[j] = s1[j - 1]\n s1[j-- - 1] = temp\n ++res\n }\n ++i\n }\n return res\n}"
] |
|
1,851 | minimum-interval-to-include-each-query | [
"Is there a way to order the intervals and queries such that it takes less time to query?",
"Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size?"
] | /**
* @param {number[][]} intervals
* @param {number[]} queries
* @return {number[]}
*/
var minInterval = function(intervals, queries) {
}; | You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1.
You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1.
Return an array containing the answers to the queries.
Example 1:
Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
Output: [3,3,1,4]
Explanation: The queries are processed as follows:
- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.
- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.
- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.
- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.
Example 2:
Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]
Output: [2,-1,4,6]
Explanation: The queries are processed as follows:
- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.
- Query = 19: None of the intervals contain 19. The answer is -1.
- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.
- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.
Constraints:
1 <= intervals.length <= 105
1 <= queries.length <= 105
intervals[i].length == 2
1 <= lefti <= righti <= 107
1 <= queries[j] <= 107
| Hard | [
"array",
"binary-search",
"line-sweep",
"sorting",
"heap-priority-queue"
] | [
"const minInterval = function (intervals, queries) {\n const n = intervals.length\n const m = queries.length\n const sortedQueryIdx = [...Array(m).keys()].sort(\n (a, b) => queries[a] - queries[b]\n )\n intervals.sort((a, b) => a[0] - b[0]) // sort by start & ascending\n const minHeap = new BinaryHeap((c, p) => c.size >= p.size)\n const res = Array(m).fill(0)\n let i = 0\n for (const idx of sortedQueryIdx) {\n const query = queries[idx]\n while (i < n && intervals[i][0] <= query) {\n minHeap.push({\n size: intervals[i][1] - intervals[i][0] + 1,\n start: intervals[i][0],\n end: intervals[i][1],\n })\n i++\n }\n while (!minHeap.isEmpty() && minHeap.peek().end < query) {\n minHeap.pop()\n }\n res[idx] = minHeap.isEmpty() ? -1 : minHeap.peek().size\n }\n return res\n}\n\nclass BinaryHeap {\n \n constructor(compareFn) {\n this.content = []\n this.compareFn = compareFn // Min-Heap: (c, p) => c > p\n }\n\n \n size() {\n return this.content.length\n }\n\n \n isEmpty() {\n return this.size() === 0\n }\n\n \n peek() {\n return this.size() > 0 ? this.content[0] : null\n }\n\n \n push(node) {\n this.content.push(node)\n this._bubbleUp(this.content.length - 1)\n }\n\n \n pop() {\n if (this.content.length === 0) return null\n const root = this.content[0]\n const last = this.content.pop()\n if (this.content.length > 0) {\n this.content[0] = last\n this._sinkDown(0)\n }\n return root\n }\n\n \n remove(node) {\n const length = this.content.length\n for (let i = 0; i < length; i++) {\n if (this.content[i] !== node) continue\n const last = this.content.pop()\n if (i === length - 1) break\n this.content[i] = last\n this._bubbleUp(i)\n this._sinkDown(i)\n break\n }\n }\n\n \n _bubbleUp(idx) {\n const node = this.content[idx]\n while (idx > 0) {\n const parentIdx = Math.floor((idx + 1) / 2) - 1\n const parent = this.content[parentIdx]\n if (this.compareFn(node, parent)) break\n this.content[parentIdx] = node\n this.content[idx] = parent\n idx = parentIdx\n }\n }\n\n \n _sinkDown(idx) {\n const node = this.content[idx]\n while (true) {\n const child2Idx = (idx + 1) * 2\n const child1Idx = child2Idx - 1\n let swapIdx = -1\n if (child1Idx < this.content.length) {\n const child1 = this.content[child1Idx]\n if (!this.compareFn(child1, node)) swapIdx = child1Idx\n }\n if (child2Idx < this.content.length) {\n const child2 = this.content[child2Idx]\n const compareNode = swapIdx === -1 ? node : this.content[child1Idx]\n if (!this.compareFn(child2, compareNode)) swapIdx = child2Idx\n }\n if (swapIdx === -1) break\n this.content[idx] = this.content[swapIdx]\n this.content[swapIdx] = node\n idx = swapIdx\n }\n }\n}",
"const minInterval = function (A, Q) {\n const QQ = []\n for (let idx = 0; idx < Q.length; idx++) QQ.push([Q[idx], idx])\n QQ.sort((a, b) => a[0] - b[0])\n A.sort((a, b) => a[0] - b[0])\n let i = 0,\n N = A.length\n const ans = Array(Q.length).fill(-1)\n const m = new TreeMap()\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n for (let [q, index] of QQ) {\n for (; i < N && A[i][0] <= q; i++) {\n let len = A[i][1] - A[i][0] + 1\n if (m.get(len) == null) m.set(len, 0)\n m.set(len, m.get(len) + 1)\n pq.push([A[i][1], len])\n }\n while (pq.size() > 0 && pq.peek()[0] < q) {\n let [right, len] = pq.peek()\n m.set(len, m.get(len) - 1)\n if (m.get(len) === 0) m.remove(len)\n pq.pop()\n }\n const first = m.getMinKey()\n if (m.getLength()) ans[index] = first\n }\n return ans\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}\n\nfunction TreeMap() {\n var root = null\n var keyType = void 0\n var length = 0\n\n return {\n each: each,\n set: set,\n get: get,\n getTree: getTree,\n getLength: getLength,\n getMaxKey: getMaxKey,\n getMinKey: getMinKey,\n remove: remove,\n }\n\n function checkKey(key, checkKeyType) {\n var localKeyType = typeof key\n\n if (\n localKeyType !== 'number' &&\n localKeyType !== 'string' &&\n localKeyType !== 'boolean'\n ) {\n throw new Error(\"'key' must be a number, a string or a boolean\")\n }\n\n if (checkKeyType === true && localKeyType !== keyType) {\n throw new Error('All keys must be of the same type')\n }\n\n return localKeyType\n }\n\n function call(callback) {\n var args = Array.prototype.slice.call(arguments, 1)\n\n if (typeof callback === 'function') {\n callback.apply(void 0, args)\n }\n }\n\n function getTree() {\n return root\n }\n\n function getLength() {\n return length\n }\n\n function each(callback) {\n internalEach(root, callback)\n }\n\n function internalEach(node, callback, internalCallback) {\n if (node === null) {\n return call(internalCallback)\n }\n\n internalEach(node.left, callback, function () {\n call(callback, node.value, node.key)\n\n internalEach(node.right, callback, function () {\n call(internalCallback)\n })\n })\n }\n\n function get(key) {\n checkKey(key)\n\n return internalGet(key, root)\n }\n\n function internalGet(key, node) {\n if (node === null) {\n return void 0\n }\n\n if (key < node.key) {\n return internalGet(key, node.left)\n } else if (key > node.key) {\n return internalGet(key, node.right)\n } else {\n return node.value\n }\n }\n\n function set(key, value) {\n if (root === null) {\n keyType = checkKey(key)\n } else {\n checkKey(key, true)\n }\n\n root = internalSet(key, value, root)\n }\n\n function internalSet(key, value, node) {\n if (node === null) {\n length++\n\n return {\n key: key,\n value: value,\n left: null,\n right: null,\n }\n }\n\n if (key < node.key) {\n node.left = internalSet(key, value, node.left)\n } else if (key > node.key) {\n node.right = internalSet(key, value, node.right)\n } else {\n node.value = value\n }\n\n return node\n }\n\n function getMaxKey() {\n var maxNode = getMaxNode(root)\n\n if (maxNode !== null) {\n return maxNode.key\n }\n\n return maxNode\n }\n\n function getMinKey() {\n var minNode = getMinNode(root)\n\n if (minNode !== null) {\n return minNode.key\n }\n\n return minNode\n }\n\n function getMaxNode(node) {\n while (node !== null && node.right !== null) {\n node = node.right\n }\n\n return node\n }\n\n function getMinNode(node) {\n while (node !== null && node.left !== null) {\n node = node.left\n }\n\n return node\n }\n\n function remove(key) {\n checkKey(key)\n\n root = internalRemove(key, root)\n }\n\n function internalRemove(key, node) {\n if (node === null) {\n return null\n }\n\n if (key < node.key) {\n node.left = internalRemove(key, node.left)\n } else if (key > node.key) {\n node.right = internalRemove(key, node.right)\n } else {\n if (node.left !== null && node.right !== null) {\n var maxNode = getMaxNode(node.left)\n\n var maxNodeKey = maxNode.key\n var maxNodeValue = maxNode.value\n\n maxNode.key = node.key\n maxNode.value = node.value\n node.key = maxNodeKey\n node.value = maxNodeValue\n\n node.left = internalRemove(key, node.left)\n } else if (node.left !== null) {\n length--\n return node.left\n } else if (node.right !== null) {\n length--\n return node.right\n } else {\n length--\n return null\n }\n }\n\n return node\n }\n}"
] |
|
1,854 | maximum-population-year | [
"For each year find the number of people whose birth_i ≤ year and death_i > year.",
"Find the maximum value between all years."
] | /**
* @param {number[][]} logs
* @return {number}
*/
var maximumPopulation = function(logs) {
}; | You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person.
The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die.
Return the earliest year with the maximum population.
Example 1:
Input: logs = [[1993,1999],[2000,2010]]
Output: 1993
Explanation: The maximum population is 1, and 1993 is the earliest year with this population.
Example 2:
Input: logs = [[1950,1961],[1960,1971],[1970,1981]]
Output: 1960
Explanation:
The maximum population is 2, and it had happened in years 1960 and 1970.
The earlier year between them is 1960.
Constraints:
1 <= logs.length <= 100
1950 <= birthi < deathi <= 2050
| Easy | [
"array",
"counting"
] | [
"const maximumPopulation = function(logs) {\n const n = logs.length\n const arr = Array(101).fill(0)\n const base = 1950\n for(let log of logs) {\n const [start, end] = log\n arr[start - base]++\n arr[end - base]--\n }\n \n let res = 0, tmp = -Infinity\n for(let i = 1; i < 101; i++) {\n arr[i] += arr[i - 1]\n }\n for(let i = 0; i < 101; i++) {\n if(arr[i] > tmp) {\n res = i\n tmp = arr[i]\n }\n }\n return res + base\n};",
"const maximumPopulation = function(logs) {\n logs.sort((a, b) => {\n if(a[0] === b[0]) return a[1] - b[1]\n return a[0] - b[0]\n })\n const arr = Array(101).fill(0)\n const bit = new FenwickTree(101)\n for(let i = 0, len = logs.length; i < len; i++) {\n const [start, end] = logs[i]\n const idx = start - 1950\n bit.update(idx + 1, 1)\n }\n for(let i = 0, len = logs.length; i < len; i++) {\n const [start, end] = logs[i]\n const idx = end - 1950\n bit.update(idx + 1, -1)\n }\n let max = 0\n for(let i = 1; i <= 101; i++) {\n max = Math.max(max, bit.query(i))\n }\n let tmp\n for(let i = 1; i <= 101; i++) {\n if(bit.query(i) === max) {\n tmp = i\n break\n }\n }\n \n return 1950 + tmp - 1\n};\n\nconst lowBit = (x) => x & -x\nclass FenwickTree {\n constructor(n) {\n if (n < 1) return\n this.sum = Array(n + 1).fill(0)\n }\n update(i, delta) {\n if (i < 1) return\n while (i < this.sum.length) {\n this.sum[i] += delta\n i += lowBit(i)\n }\n }\n query(i) {\n if (i < 1) return\n let sum = 0\n while (i > 0) {\n sum += this.sum[i]\n i -= lowBit(i)\n }\n return sum\n }\n}"
] |
|
1,855 | maximum-distance-between-a-pair-of-values | [
"Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search.",
"There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1]"
] | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var maxDistance = function(nums1, nums2) {
}; | You are given two non-increasing 0-indexed integer arrays nums1 and nums2.
A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i.
Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0.
An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.
Example 1:
Input: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]
Output: 2
Explanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).
The maximum distance is 2 with pair (2,4).
Example 2:
Input: nums1 = [2,2,2], nums2 = [10,10,1]
Output: 1
Explanation: The valid pairs are (0,0), (0,1), and (1,1).
The maximum distance is 1 with pair (0,1).
Example 3:
Input: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]
Output: 2
Explanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).
The maximum distance is 2 with pair (2,4).
Constraints:
1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[j] <= 105
Both nums1 and nums2 are non-increasing.
| Medium | [
"array",
"two-pointers",
"binary-search",
"greedy"
] | [
"const maxDistance = function(nums1, nums2) {\n let res = 0\n const m = nums1.length, n = nums2.length\n for(let i = 0; i < m; i++) {\n const idx = bSearch(nums2, i, n - 1, nums1[i])\n res = Math.max(res, idx - i)\n }\n return res\n};\n\nfunction bSearch(a, i, j, key) {\n while (i <= j) {\n let mid = (i + j) >>> 1\n if (key <= a[mid]) i = mid + 1\n else if(key > a[mid]) j = mid - 1\n }\n return i - 1\n}"
] |
|
1,856 | maximum-subarray-min-product | [
"Is there a way we can sort the elements to simplify the problem?",
"Can we find the maximum min-product for every value in the array?"
] | /**
* @param {number[]} nums
* @return {number}
*/
var maxSumMinProduct = function(nums) {
}; | The min-product of an array is equal to the minimum value in the array multiplied by the array's sum.
For example, the array [3,2,5] (minimum value is 2) has a min-product of 2 * (3+2+5) = 2 * 10 = 20.
Given an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 109 + 7.
Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,2,3,2]
Output: 14
Explanation: The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2).
2 * (2+3+2) = 2 * 7 = 14.
Example 2:
Input: nums = [2,3,3,1,2]
Output: 18
Explanation: The maximum min-product is achieved with the subarray [3,3] (minimum value is 3).
3 * (3+3) = 3 * 6 = 18.
Example 3:
Input: nums = [3,1,5,6,4,2]
Output: 60
Explanation: The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4).
4 * (5+6+4) = 4 * 15 = 60.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 107
| Medium | [
"array",
"stack",
"monotonic-stack",
"prefix-sum"
] | [
"const maxSumMinProduct = function(nums) {\n const n = nums.length, left = Array(n).fill(0), right = Array(n).fill(n - 1)\n const mod = BigInt(1e9 + 7)\n let res = 0n\n let stk = []\n for(let i = 0; i < n; i++) {\n while(stk.length && nums[stk[stk.length - 1]] >= nums[i]) {\n stk.pop()\n }\n left[i] = stk.length ? stk[stk.length - 1] + 1 : 0\n stk.push(i)\n }\n \n stk = []\n for(let i = n - 1; i >= 0; i--) {\n while(stk.length && nums[stk[stk.length - 1]] >= nums[i]) {\n stk.pop()\n }\n right[i] = stk.length ? stk[stk.length - 1] - 1 : n - 1\n stk.push(i)\n }\n \n const preSum = []\n for(let i = 0; i < n; i++) {\n preSum[i] = (i === 0 ? 0n : preSum[i - 1]) + BigInt(nums[i])\n }\n for(let i = 0; i < n; i++) {\n res = max(res, fn(nums[i], left[i], right[i]))\n }\n \n return res % mod\n \n function max(a, b) {\n return a > b ? a : b\n }\n function fn(v, l, r) {\n return BigInt(v) * (l === 0 ? preSum[r] : preSum[r] - preSum[l - 1])\n }\n};",
"const maxSumMinProduct = function (nums) {\n const n = nums.length\n const mod = BigInt(10 ** 9 + 7)\n const preSum = Array(n + 1).fill(0n)\n for (let i = 0; i < n; i++) {\n preSum[i + 1] = preSum[i] + BigInt(nums[i])\n }\n const l = Array(n).fill(0) // l[i] stores index of farthest element greater or equal to nums[i]\n const r = Array(n).fill(0) // r[i] stores index of farthest element greater or equal to nums[i]\n let st = []\n\n for (let i = 0; i < n; i++) {\n while (st.length && nums[st[st.length - 1]] >= nums[i]) st.pop()\n if (st.length) l[i] = st[st.length - 1] + 1\n else l[i] = 0\n st.push(i)\n }\n \n st = []\n for (let i = n - 1; i >= 0; i--) {\n while (st.length && nums[st[st.length - 1]] >= nums[i]) st.pop()\n if (st.length) r[i] = st[st.length - 1] - 1\n else r[i] = n - 1\n st.push(i)\n }\n function getSum(left, right) {\n // inclusive\n return preSum[right + 1] - preSum[left]\n }\n\n let maxProduct = 0n\n for (let i = 0; i < n; i++) {\n maxProduct = bigint_max(maxProduct, BigInt(nums[i]) * getSum(l[i], r[i]))\n }\n return maxProduct % mod\n}\nfunction bigint_max(...args){\n if (args.length < 1){ throw 'Max of empty list'; }\n m = args[0];\n args.forEach(a=>{if (a > m) {m = a}});\n return m;\n}",
"const maxSumMinProduct = function(nums) {\n const n = nums.length, s1 = [], s2 = [],\n left = Array(n), right = Array(n), mod = BigInt(1e9 + 7)\n for(let i = 0; i < n; i++) {\n while(s1.length && nums[s1[s1.length - 1]] >= nums[i]) s1.pop()\n if(s1.length) left[i] = s1[s1.length - 1] + 1\n else left[i] = 0\n s1.push(i)\n }\n \n for(let i = n - 1; i >= 0; i--) {\n while(s2.length && nums[s2[s2.length - 1]] >= nums[i]) s2.pop()\n if(s2.length) right[i] = s2[s2.length - 1] - 1\n else right[i] = n - 1\n s2.push(i)\n }\n \n const preSum = Array(n)\n for(let i = 0; i < n; i++) {\n preSum[i] = (i === 0 ? 0n : preSum[i - 1]) + BigInt(nums[i])\n }\n let res = 0n\n for(let i = 0; i < n; i++) {\n res = max(res, getSum(preSum, left[i], right[i]) * BigInt(nums[i]))\n }\n return res % mod\n \n};\n\nfunction getSum(arr, l, r) {\n return arr[r] - (l === 0 ? 0n : arr[l - 1])\n}\n\nfunction max(...args) {\n let res = -Infinity\n for(let e of args) {\n if(e > res) res = e\n }\n return res\n}"
] |
|
1,857 | largest-color-value-in-a-directed-graph | [
"Use topological sort.",
"let dp[u][c] := the maximum count of vertices with color c of any path starting from vertex u. (by JerryJin2905)"
] | /**
* @param {string} colors
* @param {number[][]} edges
* @return {number}
*/
var largestPathValue = function(colors, edges) {
}; | There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1.
You are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj.
A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.
Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.
Example 1:
Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
Output: 3
Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image).
Example 2:
Input: colors = "a", edges = [[0,0]]
Output: -1
Explanation: There is a cycle from 0 to 0.
Constraints:
n == colors.length
m == edges.length
1 <= n <= 105
0 <= m <= 105
colors consists of lowercase English letters.
0 <= aj, bj < n
| Hard | [
"hash-table",
"dynamic-programming",
"graph",
"topological-sort",
"memoization",
"counting"
] | [
"const largestPathValue = function (colors, edges) {\n const graph = {}\n const n = colors.length,\n a = 'a'.charCodeAt(0)\n const indegree = Array(colors.length).fill(0)\n for (let e of edges) {\n if (graph[e[0]] == null) graph[e[0]] = []\n graph[e[0]].push(e[1])\n indegree[e[1]]++\n }\n // cnt[i][j] is the maximum count of j-th color from the ancester nodes to node i.\n const cnt = Array.from({ length: n }, () => Array(26).fill(0))\n const q = []\n for (let i = 0; i < n; i++) { \n if (indegree[i] === 0) {\n q.push(i)\n cnt[i][colors.charCodeAt(i) - a] = 1\n }\n }\n let res = 0,\n seen = 0\n while (q.length) {\n const u = q[0]\n q.shift()\n const val = Math.max(...cnt[u])\n res = Math.max(res, val)\n seen++\n for (let v of (graph[u] || [])) {\n for (let i = 0; i < 26; i++) {\n cnt[v][i] = Math.max(\n cnt[v][i],\n cnt[u][i] + (i === colors.charCodeAt(v) - a)\n )\n }\n if (--indegree[v] === 0) q.push(v)\n }\n }\n return seen < colors.length ? -1 : res\n}",
" const largestPathValue = function(colors, edges) {\n const graph = {}, n = colors.length, a = 'a'.charCodeAt(0)\n const indegree = Array(n).fill(0)\n for (const [from, to] of edges) {\n if (graph[from] == null) graph[from] = []\n graph[from].push(to)\n indegree[to]++\n }\n const cnt = Array.from({ length: n }, () => Array(26).fill(0))\n const code = idx => colors.charCodeAt(idx) - a\n const q = []\n for (let i = 0; i < n; i++) {\n if(indegree[i] === 0) {\n q.push(i)\n cnt[i][code(i)] = 1\n }\n }\n let res = 0, seen = 0\n\n while(q.length) {\n const u = q.pop()\n const val = cnt[u][code(u)]\n res = Math.max(res, val)\n seen++\n for(const next of (graph[u] || [])) {\n for(let i = 0; i < 26; i++) {\n cnt[next][i] = Math.max(cnt[next][i], cnt[u][i] + (i === code(next) ? 1 : 0))\n }\n if(--indegree[next] === 0) {\n q.push(next)\n }\n }\n }\n return seen < n ? -1 : res\n};",
"const largestPathValue = function (colors, edges) {\n const graph = {}\n const n = colors.length,\n a = 'a'.charCodeAt(0)\n const indegree = Array(colors.length).fill(0)\n for (let e of edges) {\n if (graph[e[0]] == null) graph[e[0]] = []\n graph[e[0]].push(e[1])\n indegree[e[1]]++\n }\n const cnt = Array.from({ length: n }, () => Array(26).fill(0))\n const q = []\n for (let i = 0; i < n; i++) {\n if (indegree[i] === 0) {\n q.push(i)\n cnt[i][colors.charCodeAt(i) - a] = 1\n }\n }\n let res = 0,\n seen = 0\n while (q.length) {\n const u = q[0]\n q.shift()\n const val = Math.max(...cnt[u])\n res = Math.max(res, val)\n seen++\n if (graph[u] == null) continue\n for (let v of graph[u]) {\n for (let i = 0; i < 26; i++) {\n cnt[v][i] = Math.max(\n cnt[v][i],\n cnt[u][i] + (i === colors.charCodeAt(v) - a)\n )\n }\n if (--indegree[v] === 0) q.push(v)\n }\n }\n return seen < colors.length ? -1 : res\n}"
] |
|
1,859 | sorting-the-sentence | [
"Divide the string into the words as an array of strings",
"Sort the words by removing the last character from each word and sorting according to it"
] | /**
* @param {string} s
* @return {string}
*/
var sortSentence = function(s) {
}; | A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.
A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.
For example, the sentence "This is a sentence" can be shuffled as "sentence4 a3 is2 This1" or "is2 sentence4 This1 a3".
Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.
Example 1:
Input: s = "is2 sentence4 This1 a3"
Output: "This is a sentence"
Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.
Example 2:
Input: s = "Myself2 Me1 I4 and3"
Output: "Me Myself and I"
Explanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.
Constraints:
2 <= s.length <= 200
s consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9.
The number of words in s is between 1 and 9.
The words in s are separated by a single space.
s contains no leading or trailing spaces.
| Easy | [
"string",
"sorting"
] | [
"const sortSentence = function(s) {\n const arr = s.split(' ')\n const n = arr.length, res = Array(n)\n for(let e of arr) {\n const idx = +e[e.length - 1]\n res[idx - 1] = e.slice(0, e.length - 1)\n }\n return res.join(' ')\n};"
] |
|
1,860 | incremental-memory-leak | [
"What is the upper bound for the number of seconds?",
"Simulate the process of allocating memory."
] | /**
* @param {number} memory1
* @param {number} memory2
* @return {number[]}
*/
var memLeak = function(memory1, memory2) {
}; | You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second.
At the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes.
Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively.
Example 1:
Input: memory1 = 2, memory2 = 2
Output: [3,1,0]
Explanation: The memory is allocated as follows:
- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.
- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.
- At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively.
Example 2:
Input: memory1 = 8, memory2 = 11
Output: [6,0,4]
Explanation: The memory is allocated as follows:
- At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.
- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.
- At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.
- At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.
- At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.
- At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively.
Constraints:
0 <= memory1, memory2 <= 231 - 1
| Medium | [
"simulation"
] | [
"const memLeak = function(memory1, memory2) {\n let i = 1\n const res = Array(3).fill(0)\n res[0] = 1\n res[1] = memory1\n res[2] = memory2\n while(true) {\n if(res[1] >= i || res[2] >= i) {\n if(res[1] >= i && res[2] >= i) {\n if(res[1] === res[2]) {\n res[1] -= i\n } else if(res[1] > res[2]) {\n res[1] -= i\n } else {\n res[2] -= i\n }\n } else if(res[1] >= i) {\n res[1] -= i\n } else if(res[2] >= i){\n res[2] -= i\n }\n } else {\n res[0] = i\n return res\n }\n \n i++\n }\n};"
] |
|
1,861 | rotating-the-box | [
"Rotate the box using the relation rotatedBox[i][j] = box[m - 1 - j][i].",
"Start iterating from the bottom of the box and for each empty cell check if there is any stone above it with no obstacles between them."
] | /**
* @param {character[][]} box
* @return {character[][]}
*/
var rotateTheBox = function(box) {
}; | You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following:
A stone '#'
A stationary obstacle '*'
Empty '.'
The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.
It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box.
Return an n x m matrix representing the box after the rotation described above.
Example 1:
Input: box = [["#",".","#"]]
Output: [["."],
["#"],
["#"]]
Example 2:
Input: box = [["#",".","*","."],
["#","#","*","."]]
Output: [["#","."],
["#","#"],
["*","*"],
[".","."]]
Example 3:
Input: box = [["#","#","*",".","*","."],
["#","#","#","*",".","."],
["#","#","#",".","#","."]]
Output: [[".","#","#"],
[".","#","#"],
["#","#","*"],
["#","*","."],
["#",".","*"],
["#",".","."]]
Constraints:
m == box.length
n == box[i].length
1 <= m, n <= 500
box[i][j] is either '#', '*', or '.'.
| Medium | [
"array",
"two-pointers",
"matrix"
] | [
"const rotateTheBox = function(box) {\n const m = box.length, n = box[0].length\n const res = Array.from({ length: n }, () => Array(m).fill('.'))\n for(let i = 0; i < m; i++) {\n for(let j = n - 1, pos = n - 1; j >= 0; j--) {\n if(box[i][j] === '.') continue\n if(box[i][j] === '#') {\n res[pos][m - 1 - i] = '#'\n pos--\n } else {\n res[j][m - 1 - i] = '*'\n pos = j - 1\n }\n }\n }\n return res\n};",
"const rotateTheBox = function(box) {\n const m = box.length, n = box[0].length\n const res = Array.from({ length: n }, () => Array(m).fill('.'))\n for(let i = 0; i < m; i++) {\n let j = n - 1\n let pos = j\n while(j >= 0) {\n if(box[i][j] === '*') {\n pos = j - 1\n } else if(box[i][j] === '#') {\n box[i][j] = '.'\n box[i][pos] = '#'\n res[pos][m - 1 - i] = '#'\n pos--\n }\n res[j][m - 1 - i] = box[i][j]\n j--\n }\n \n }\n return res\n};"
] |
|
1,862 | sum-of-floored-pairs | [
"Find the frequency (number of occurrences) of all elements in the array.",
"For each element, iterate through its multiples and multiply frequencies to find the answer."
] | /**
* @param {number[]} nums
* @return {number}
*/
var sumOfFlooredPairs = function(nums) {
}; | Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 109 + 7.
The floor() function returns the integer part of the division.
Example 1:
Input: nums = [2,5,9]
Output: 10
Explanation:
floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0
floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1
floor(5 / 2) = 2
floor(9 / 2) = 4
floor(9 / 5) = 1
We calculate the floor of the division for every pair of indices in the array then sum them up.
Example 2:
Input: nums = [7,7,7,7,7,7,7]
Output: 49
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105
| Hard | [
"array",
"math",
"binary-search",
"prefix-sum"
] | [
"const sumOfFlooredPairs = function (nums) {\n const MAX = Math.max(...nums)\n const countsGreaterOrEqualTo = new Array(MAX + 1).fill(0)\n const numCounts = new Map()\n const MOD = 1e9 + 7\n nums.forEach((num) => {\n countsGreaterOrEqualTo[num]++\n numCounts.set(num, (numCounts.get(num) || 0) + 1)\n })\n\n for (let num = MAX - 1; num >= 0; num--) {\n countsGreaterOrEqualTo[num] += countsGreaterOrEqualTo[num + 1]\n }\n \n let totalCount = 0\n numCounts.forEach((count, num) => {\n let current = num\n while (current <= MAX) {\n totalCount = (totalCount + countsGreaterOrEqualTo[current] * count) % MOD\n current += num\n }\n })\n\n return totalCount\n}"
] |
|
1,863 | sum-of-all-subset-xor-totals | [
"Is there a way to iterate through all the subsets of the array?",
"Can we use recursion to efficiently iterate through all the subsets?"
] | /**
* @param {number[]} nums
* @return {number}
*/
var subsetXORSum = function(nums) {
}; | The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.
For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.
Given an array nums, return the sum of all XOR totals for every subset of nums.
Note: Subsets with the same elements should be counted multiple times.
An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.
Example 1:
Input: nums = [1,3]
Output: 6
Explanation: The 4 subsets of [1,3] are:
- The empty subset has an XOR total of 0.
- [1] has an XOR total of 1.
- [3] has an XOR total of 3.
- [1,3] has an XOR total of 1 XOR 3 = 2.
0 + 1 + 3 + 2 = 6
Example 2:
Input: nums = [5,1,6]
Output: 28
Explanation: The 8 subsets of [5,1,6] are:
- The empty subset has an XOR total of 0.
- [5] has an XOR total of 5.
- [1] has an XOR total of 1.
- [6] has an XOR total of 6.
- [5,1] has an XOR total of 5 XOR 1 = 4.
- [5,6] has an XOR total of 5 XOR 6 = 3.
- [1,6] has an XOR total of 1 XOR 6 = 7.
- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.
0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28
Example 3:
Input: nums = [3,4,5,6,7,8]
Output: 480
Explanation: The sum of all XOR totals for every subset is 480.
Constraints:
1 <= nums.length <= 12
1 <= nums[i] <= 20
| Easy | [
"array",
"math",
"backtracking",
"bit-manipulation",
"combinatorics"
] | [
"const subsetXORSum = function(nums) {\n let res = {sum: 0}\n \n helper(nums, 0, [], res)\n return res.sum\n};\n\nfunction helper(arr, idx, cur, res) {\n if(idx === arr.length) {\n res.sum += calc(cur)\n return\n }\n const clone = cur.slice()\n helper(arr, idx + 1, clone, res)\n const c2 = cur.slice()\n c2.push(arr[idx])\n helper(arr, idx + 1, c2, res)\n}\n\nfunction calc(arr) {\n let res = 0\n for(let e of arr) res ^= e\n return res\n}"
] |
|
1,864 | minimum-number-of-swaps-to-make-the-binary-string-alternating | [
"Think about all valid strings of length n.",
"Try to count the mismatched positions with each valid string of length n."
] | /**
* @param {string} s
* @return {number}
*/
var minSwaps = function(s) {
}; | Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible.
The string is called alternating if no two adjacent characters are equal. For example, the strings "010" and "1010" are alternating, while the string "0100" is not.
Any two characters may be swapped, even if they are not adjacent.
Example 1:
Input: s = "111000"
Output: 1
Explanation: Swap positions 1 and 4: "111000" -> "101010"
The string is now alternating.
Example 2:
Input: s = "010"
Output: 0
Explanation: The string is already alternating, no swaps are needed.
Example 3:
Input: s = "1110"
Output: -1
Constraints:
1 <= s.length <= 1000
s[i] is either '0' or '1'.
| Medium | [
"string",
"greedy"
] | [
"const minSwaps = function(s) {\n const valid = chk(s)\n if(valid === -1) return -1\n const [zeroNum, oneNum] = valid\n let res = Infinity\n if(zeroNum === oneNum) {\n // zero start\n let tmpZero = 0\n let cur = '0'\n for(let i = 0; i < s.length; i++) {\n if(i % 2 === 0 && s[i] !== '0') tmpZero++\n }\n \n res = Math.min(tmpZero, res)\n // one start\n let tmpOne = 0\n cur = '1'\n for(let i = 0; i < s.length; i++) {\n if(i % 2 === 0 && s[i] !== '1') tmpOne++\n }\n res = Math.min(tmpOne, res)\n } else if(zeroNum > oneNum) {\n let tmpZero = 0\n let cur = '0'\n for(let i = 0; i < s.length; i++) {\n if(i % 2 === 0 && s[i] !== '0') tmpZero++\n }\n \n res = Math.min(tmpZero, res) \n } else {\n let tmpOne = 0\n cur = '1'\n for(let i = 0; i < s.length; i++) {\n if(i % 2 === 0 && s[i] !== '1') tmpOne++\n }\n res = Math.min(tmpOne, res)\n }\n return res\n};\n\nfunction chk(str) {\n let oneNum = 0, zeroNum = 0\n for(let ch of str) {\n if(ch === '0') zeroNum++\n else oneNum++\n } \n return Math.abs(zeroNum - oneNum) <= 1 ? [zeroNum, oneNum] : -1\n}"
] |
|
1,865 | finding-pairs-with-a-certain-sum | [
"The length of nums1 is small in comparison to that of nums2",
"If we iterate over elements of nums1 we just need to find the count of tot - element for all elements in nums1"
] | /**
* @param {number[]} nums1
* @param {number[]} nums2
*/
var FindSumPairs = function(nums1, nums2) {
};
/**
* @param {number} index
* @param {number} val
* @return {void}
*/
FindSumPairs.prototype.add = function(index, val) {
};
/**
* @param {number} tot
* @return {number}
*/
FindSumPairs.prototype.count = function(tot) {
};
/**
* Your FindSumPairs object will be instantiated and called as such:
* var obj = new FindSumPairs(nums1, nums2)
* obj.add(index,val)
* var param_2 = obj.count(tot)
*/ | You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types:
Add a positive integer to an element of a given index in the array nums2.
Count the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given value (0 <= i < nums1.length and 0 <= j < nums2.length).
Implement the FindSumPairs class:
FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer arrays nums1 and nums2.
void add(int index, int val) Adds val to nums2[index], i.e., apply nums2[index] += val.
int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot.
Example 1:
Input
["FindSumPairs", "count", "add", "count", "count", "add", "add", "count"]
[[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]]
Output
[null, 8, null, 2, 1, null, null, 11]
Explanation
FindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]);
findSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4
findSumPairs.add(3, 2); // now nums2 = [1,4,5,4,5,4]
findSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5
findSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1
findSumPairs.add(0, 1); // now nums2 = [2,4,5,4,5,4]
findSumPairs.add(1, 1); // now nums2 = [2,5,5,4,5,4]
findSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4
Constraints:
1 <= nums1.length <= 1000
1 <= nums2.length <= 105
1 <= nums1[i] <= 109
1 <= nums2[i] <= 105
0 <= index < nums2.length
1 <= val <= 105
1 <= tot <= 109
At most 1000 calls are made to add and count each.
| Medium | [
"array",
"hash-table",
"design"
] | [
"const FindSumPairs = function(nums1, nums2) {\n this.nums1 = nums1\n this.nums2 = nums2\n const m = nums1.length, n = nums2.length\n this.mp = {}\n for(let x of nums2) {\n if(this.mp[x] == null) this.mp[x] = 0\n this.mp[x]++\n }\n};\n\n\nFindSumPairs.prototype.add = function(index, val) {\n if(val !== 0) {\n if(!(--this.mp[this.nums2[index]])) delete this.mp[this.nums2[index]] \n }\n this.nums2[index] += val\n if(this.mp[this.nums2[index]] == null) this.mp[this.nums2[index]] = 0\n if(val !== 0)this.mp[this.nums2[index]]++\n};\n\n\nFindSumPairs.prototype.count = function(tot) {\n let ans = 0;\n for (let x of this.nums1) {\n let res = tot - x;\n if (!this.mp[res]) continue;\n ans += this.mp[res];\n }\n return ans;\n};"
] |
|
1,866 | number-of-ways-to-rearrange-sticks-with-k-sticks-visible | [
"Is there a way to build the solution from a base case?",
"How many ways are there if we fix the position of one stick?"
] | /**
* @param {number} n
* @param {number} k
* @return {number}
*/
var rearrangeSticks = function(n, k) {
}; | There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it.
For example, if the sticks are arranged [1,3,2,5,4], then the sticks with lengths 1, 3, and 5 are visible from the left.
Given n and k, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7.
Example 1:
Input: n = 3, k = 2
Output: 3
Explanation: [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.
The visible sticks are underlined.
Example 2:
Input: n = 5, k = 5
Output: 1
Explanation: [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.
The visible sticks are underlined.
Example 3:
Input: n = 20, k = 11
Output: 647427950
Explanation: There are 647427950 (mod 109 + 7) ways to rearrange the sticks such that exactly 11 sticks are visible.
Constraints:
1 <= n <= 1000
1 <= k <= n
| Hard | [
"math",
"dynamic-programming",
"combinatorics"
] | [
"const rearrangeSticks = function(n, k) {\n const mod = BigInt(1e9 + 7)\n const g = Array.from({ length: 1001 }, () => Array(1001).fill(0n))\n g[1][1] = 1n\n for(let i = 2; i <= 1000; i++) {\n for(let j = 1; j <= i; j++ ) {\n g[i][j] = (g[i - 1][j - 1] + BigInt(i - 1) * g[i - 1][j] % mod) % mod\n }\n }\n return g[n][k]\n};",
"const rearrangeSticks = function(n, k) {\n const MOD = 1e9 + 7;\n // first # can be smallest # in which case we recurse for (n - 1, k - 1) \n // or it can not be and smallest can be in any of n - 1 otehr positions for recursed(n - 1, k)\n const dp = new Array(n + 1).fill().map( _ => new Array(k + 1).fill(0) );\n for (let i = 1; i <= n; ++i) {\n for (let j = 1; j <= k; ++j) {\n if (j === i) {\n dp[i][j] = 1;\n } else if (j < i) {\n dp[i][j] = (dp[i - 1][j - 1] + (i - 1) * dp[i - 1][j]) % MOD;\n }\n }\n }\n return dp[n][k] % MOD;\n \n};"
] |
|
1,869 | longer-contiguous-segments-of-ones-than-zeros | [
"Check every possible segment of 0s and 1s.",
"Is there a way to iterate through the string to keep track of the current character and its count?"
] | /**
* @param {string} s
* @return {boolean}
*/
var checkZeroOnes = function(s) {
}; | Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise.
For example, in s = "110100010" the longest continuous segment of 1s has length 2, and the longest continuous segment of 0s has length 3.
Note that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's.
Example 1:
Input: s = "1101"
Output: true
Explanation:
The longest contiguous segment of 1s has length 2: "1101"
The longest contiguous segment of 0s has length 1: "1101"
The segment of 1s is longer, so return true.
Example 2:
Input: s = "111000"
Output: false
Explanation:
The longest contiguous segment of 1s has length 3: "111000"
The longest contiguous segment of 0s has length 3: "111000"
The segment of 1s is not longer, so return false.
Example 3:
Input: s = "110100010"
Output: false
Explanation:
The longest contiguous segment of 1s has length 2: "110100010"
The longest contiguous segment of 0s has length 3: "110100010"
The segment of 1s is not longer, so return false.
Constraints:
1 <= s.length <= 100
s[i] is either '0' or '1'.
| Easy | [
"string"
] | [
"const checkZeroOnes = function(s) {\n const stack = []\n let zl = 0, ol = 0\n for(let e of s) {\n let tmp = 0, zo = ''\n while(stack.length && stack[stack.length - 1] !== e) {\n if(zo === '') zo = stack[stack.length - 1]\n tmp++\n stack.pop()\n }\n if(zo === '1') ol = Math.max(tmp, ol)\n if(zo === '0') zl = Math.max(tmp, zl)\n stack.push(e)\n } \n if(stack.length) {\n let zo = stack[stack.length - 1]\n if(zo === '1') ol = Math.max(stack.length, ol)\n if(zo === '0') zl = Math.max(stack.length, zl)\n }\n return ol > zl\n};"
] |
|
1,870 | minimum-speed-to-arrive-on-time | [
"Given the speed the trains are traveling at, can you find the total time it takes for you to arrive?",
"Is there a cutoff where any speeds larger will always allow you to arrive on time?"
] | /**
* @param {number[]} dist
* @param {number} hour
* @return {number}
*/
var minSpeedOnTime = function(dist, hour) {
}; | You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride.
Each train can only depart at an integer hour, so you may need to wait in between each train ride.
For example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark.
Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time.
Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.
Example 1:
Input: dist = [1,3,2], hour = 6
Output: 1
Explanation: At speed 1:
- The first train ride takes 1/1 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.
- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.
- You will arrive at exactly the 6 hour mark.
Example 2:
Input: dist = [1,3,2], hour = 2.7
Output: 3
Explanation: At speed 3:
- The first train ride takes 1/3 = 0.33333 hours.
- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.
- You will arrive at the 2.66667 hour mark.
Example 3:
Input: dist = [1,3,2], hour = 1.9
Output: -1
Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.
Constraints:
n == dist.length
1 <= n <= 105
1 <= dist[i] <= 105
1 <= hour <= 109
There will be at most two digits after the decimal point in hour.
| Medium | [
"array",
"binary-search"
] | [
"const minSpeedOnTime = function(dist, hour) {\n let n = dist.length, l = 1, r = 1e7 + 1\n while(l < r) {\n const mid = l + ((r - l) >> 1)\n let time = 0\n for(let i = 0; i < n - 1; i++) time += Math.ceil(dist[i] / mid)\n time += dist[dist.length - 1] / mid\n if(time > hour) l = mid + 1\n else r = mid\n }\n return l > 1e7 ? -1 : l\n};",
"const minSpeedOnTime = function(dist, hour) {\n let l = 1, r = 1e7\n while(l <= r) {\n let mid = (l + r) >> 1\n if(valid(mid)) r = mid -1\n else l = mid + 1\n }\n return l > 1e7 ? -1 : l\n \n function valid(speed) {\n let sum = 0\n for(let e of dist) {\n sum = Math.ceil(sum)\n sum += e / speed\n if(sum > hour) return \n }\n \n return true\n }\n};",
"const minSpeedOnTime = function(dist, hour) {\n const sum = dist.reduce((ac, e) => ac + e, 0)\n let l = 1, r = 10 ** 7\n while(l < r) {\n let mid = l + ((r - l) >> 1)\n if(chk(mid)) r = mid\n else l = mid + 1\n }\n\n return chk(l) ? l : -1\n \n function chk(speed) {\n let res = 0\n for(let i = 0, len = dist.length; i < len - 1; i++) {\n res += Math.ceil(dist[i] / speed)\n }\n if (dist.length) res += dist[dist.length - 1] / speed \n return res <= hour\n }\n \n};",
"const minSpeedOnTime = function(dist, hour) {\n let l = 1, r = 1e7\n while(l < r) {\n const mid = l + Math.floor((r - l) / 2)\n if(!valid(mid)) l = mid + 1\n else r = mid\n }\n // console.log(l)\n return valid(l) ? l : -1\n \n function valid(mid) {\n let res = 0\n for(let i = 0, n = dist.length; i < n; i++) {\n const d = dist[i] \n res += (i === n - 1 ? d / mid : Math.ceil(d / mid))\n }\n return res <= hour\n }\n};"
] |
|
1,871 | jump-game-vii | [
"Consider for each reachable index i the interval [i + a, i + b].",
"Use partial sums to mark the intervals as reachable."
] | /**
* @param {string} s
* @param {number} minJump
* @param {number} maxJump
* @return {boolean}
*/
var canReach = function(s, minJump, maxJump) {
}; | You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled:
i + minJump <= j <= min(i + maxJump, s.length - 1), and
s[j] == '0'.
Return true if you can reach index s.length - 1 in s, or false otherwise.
Example 1:
Input: s = "011010", minJump = 2, maxJump = 3
Output: true
Explanation:
In the first step, move from index 0 to index 3.
In the second step, move from index 3 to index 5.
Example 2:
Input: s = "01101110", minJump = 2, maxJump = 3
Output: false
Constraints:
2 <= s.length <= 105
s[i] is either '0' or '1'.
s[0] == '0'
1 <= minJump <= maxJump < s.length
| Medium | [
"string",
"dynamic-programming",
"sliding-window",
"prefix-sum"
] | [
"const canReach = function(s, minJump, maxJump) {\n const n = s.length\n const queue = [0]\n let mx = 0\n const { max, min } = Math\n while(queue.length) {\n const i = queue.shift()\n for(let j = max(i + minJump, mx + 1); j < min(s.length, i + maxJump + 1); j++) {\n if(s[j] === '0') {\n if(j === n - 1) return true\n queue.push(j)\n }\n }\n mx = i + maxJump\n }\n \n return false\n};",
"const canReach = function(s, minJump, maxJump) {\n let n = s.length;\n const {max, min} = Math\n if (s[n - 1] != '0') return false;\n const pre_sum = Array(n + 1).fill(0);\n const check = Array(n + 1).fill(0);\n check[1] = 1;\n pre_sum[1] = 1;\n for (let i = 1; i < n; i++) {\n pre_sum[i + 1] = pre_sum[i];\n if (s[i] == '1') continue;\n if (i < minJump) continue;\n let r = i - minJump;\n let l = max(0, i - maxJump);\n if (pre_sum[r + 1] - pre_sum[l] == 0) continue;\n check[i + 1] = true;\n pre_sum[i + 1]++;\n }\n return check[n];\n};",
"const canReach = function(s, minJump, maxJump) {\n const n = s.length, dp = Array(n).fill(0)\n dp[0] = 1\n let pre = 0\n for(let i = 1; i < n; i++) {\n if(i >= minJump) {\n pre += dp[i - minJump]\n }\n if(i > maxJump) pre -= dp[i - maxJump - 1]\n dp[i] = pre > 0 && s[i] === '0' ? 1 : 0\n }\n return dp[n - 1]\n};",
"const canReach = function(s, minJump, maxJump) {\n const n = s.length\n const dp = Array(n).fill(0)\n dp[0] = 1\n let pre = 0\n for(let i = 1; i < n; i++) {\n if(i < minJump) continue\n if(i >= minJump) pre += dp[i - minJump]\n if(i > maxJump) pre -= dp[i - maxJump - 1]\n dp[i] = pre > 0 && s[i] === '0' ? 1 : 0\n }\n \n return dp[n - 1] ? true : false\n};"
] |
|
1,872 | stone-game-viii | [
"Let's note that the only thing that matters is how many stones were removed so we can maintain dp[numberOfRemovedStones]",
"dp[x] = max(sum of all elements up to y - dp[y]) for all y > x"
] | /**
* @param {number[]} stones
* @return {number}
*/
var stoneGameVIII = function(stones) {
}; | Alice and Bob take turns playing a game, with Alice starting first.
There are n stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following:
Choose an integer x > 1, and remove the leftmost x stones from the row.
Add the sum of the removed stones' values to the player's score.
Place a new stone, whose value is equal to that sum, on the left side of the row.
The game stops when only one stone is left in the row.
The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference.
Given an integer array stones of length n where stones[i] represents the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimally.
Example 1:
Input: stones = [-1,2,-3,4,-5]
Output: 5
Explanation:
- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of
value 2 on the left. stones = [2,-5].
- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on
the left. stones = [-3].
The difference between their scores is 2 - (-3) = 5.
Example 2:
Input: stones = [7,-6,5,10,5,-2,-6]
Output: 13
Explanation:
- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a
stone of value 13 on the left. stones = [13].
The difference between their scores is 13 - 0 = 13.
Example 3:
Input: stones = [-10,-12]
Output: -22
Explanation:
- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her
score and places a stone of value -22 on the left. stones = [-22].
The difference between their scores is (-22) - 0 = -22.
Constraints:
n == stones.length
2 <= n <= 105
-104 <= stones[i] <= 104
| Hard | [
"array",
"math",
"dynamic-programming",
"prefix-sum",
"game-theory"
] | [
"const stoneGameVIII = function (A) {\n let N = A.length,\n ans = -Infinity\n for (let i = 1; i < N; ++i) A[i] += A[i - 1] // now A[i] becomes prefix[i]\n let mx = A[N - 1] // dp[N - 1] = prefix[N - 1]\n for (let i = N - 2; i >= 0; --i) {\n ans = Math.max(ans, mx) // since dp[i] = mx, we try to use dp[i] to update ans.\n mx = Math.max(mx, A[i] - mx) // try to update mx using prefix[i] - dp[i]\n }\n return ans\n}"
] |
|
1,876 | substrings-of-size-three-with-distinct-characters | [
"Try using a set to find out the number of distinct characters in a substring."
] | /**
* @param {string} s
* @return {number}
*/
var countGoodSubstrings = function(s) {
}; | A string is good if there are no repeated characters.
Given a string s, return the number of good substrings of length three in s.
Note that if there are multiple occurrences of the same substring, every occurrence should be counted.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "xyzzaz"
Output: 1
Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz".
The only good substring of length 3 is "xyz".
Example 2:
Input: s = "aababcabc"
Output: 4
Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc".
The good substrings are "abc", "bca", "cab", and "abc".
Constraints:
1 <= s.length <= 100
s consists of lowercase English letters.
| Easy | [
"hash-table",
"string",
"sliding-window",
"counting"
] | [
" const countGoodSubstrings = function(s) {\n let res = 0\n for(let i = 2; i < s.length; i++) {\n if(chk(s, i)) res++\n }\n \n return res\n};\n\nfunction chk(s, i) {\n return s[i - 2] !== s[i - 1] &&\n s[i - 2] !== s[i] &&\n s[i - 1] !== s[i]\n}"
] |
|
1,877 | minimize-maximum-pair-sum-in-array | [
"Would sorting help find the optimal order?",
"Given a specific element, how would you minimize its specific pairwise sum?"
] | /**
* @param {number[]} nums
* @return {number}
*/
var minPairSum = function(nums) {
}; | The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs.
For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8.
Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:
Each element of nums is in exactly one pair, and
The maximum pair sum is minimized.
Return the minimized maximum pair sum after optimally pairing up the elements.
Example 1:
Input: nums = [3,5,2,3]
Output: 7
Explanation: The elements can be paired up into pairs (3,3) and (5,2).
The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
Example 2:
Input: nums = [3,5,4,2,4,6]
Output: 8
Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2).
The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
Constraints:
n == nums.length
2 <= n <= 105
n is even.
1 <= nums[i] <= 105
| Medium | [
"array",
"two-pointers",
"greedy",
"sorting"
] | [
"var minPairSum = function(nums) {\n nums.sort((a, b) => a - b)\n let res = 0\n for(let i = 0, limit = nums.length / 2; i < limit; i++) {\n res = Math.max(res, nums[i] + nums[nums.length - 1 - i])\n }\n \n return res\n};"
] |
|
1,878 | get-biggest-three-rhombus-sums-in-a-grid | [
"You need to maintain only the biggest 3 distinct sums",
"The limits are small enough for you to iterate over all rhombus sizes then iterate over all possible borders to get the sums"
] | /**
* @param {number[][]} grid
* @return {number[]}
*/
var getBiggestThree = function(grid) {
}; | You are given an m x n integer matrix grid.
A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:
Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.
Return the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct values, return all of them.
Example 1:
Input: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]
Output: [228,216,211]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 20 + 3 + 200 + 5 = 228
- Red: 200 + 2 + 10 + 4 = 216
- Green: 5 + 200 + 4 + 2 = 211
Example 2:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: [20,9,8]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 4 + 2 + 6 + 8 = 20
- Red: 9 (area 0 rhombus in the bottom right corner)
- Green: 8 (area 0 rhombus in the bottom middle)
Example 3:
Input: grid = [[7,7,7]]
Output: [7]
Explanation: All three possible rhombus sums are the same, so return [7].
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 105
| Medium | [
"array",
"math",
"sorting",
"heap-priority-queue",
"matrix",
"prefix-sum"
] | [
"const getBiggestThree = function (grid) {\n const rows = grid.length\n const cols = grid[0].length\n const res = []\n for(let i = 0; i < rows; i++) {\n for(let j = 0; j < cols; j++) {\n for(let size = 0; i - size >= 0 && i + size < rows && j + size * 2 < cols; size++) {\n let tmp = 0, r = i, c = j\n do {tmp += grid[r++][c++]} while(r < rows && c < cols && r < i + size)\n if(size > 0) {\n do {tmp += grid[r--][c++]} while(c < cols && c < j + 2 * size)\n do {tmp += grid[r--][c--]} while(r > 0 && r > i - size)\n do {tmp += grid[r++][c--]} while(c > 0 && r < i)\n }\n if(res.indexOf(tmp) === -1) res.push(tmp)\n if(res.length > 3) {\n res.sort((a, b) => b - a)\n res.splice(3)\n }\n }\n }\n }\n res.sort((a, b) => b - a)\n return res\n}"
] |
|
1,879 | minimum-xor-sum-of-two-arrays | [
"Since n <= 14, we can consider every subset of nums2.",
"We can represent every subset of nums2 using bitmasks."
] | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var minimumXORSum = function(nums1, nums2) {
}; | You are given two integer arrays nums1 and nums2 of length n.
The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed).
For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4.
Rearrange the elements of nums2 such that the resulting XOR sum is minimized.
Return the XOR sum after the rearrangement.
Example 1:
Input: nums1 = [1,2], nums2 = [2,3]
Output: 2
Explanation: Rearrange nums2 so that it becomes [3,2].
The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.
Example 2:
Input: nums1 = [1,0,3], nums2 = [5,3,4]
Output: 8
Explanation: Rearrange nums2 so that it becomes [5,4,3].
The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.
Constraints:
n == nums1.length
n == nums2.length
1 <= n <= 14
0 <= nums1[i], nums2[i] <= 107
| Hard | [
"array",
"dynamic-programming",
"bit-manipulation",
"bitmask"
] | [
"const minimumXORSum = function (nums1, nums2) {\n const n = nums1.length\n const limit = 1 << n\n const dp = Array(limit).fill(Infinity)\n dp[0] = 0\n for (let mask = 1; mask < limit; ++mask) {\n for (let i = 0; i < n; ++i) {\n if ((mask >> i) & 1) {\n dp[mask] = Math.min(\n dp[mask],\n dp[mask ^ (1 << i)] + (nums1[bitCnt(mask) - 1] ^ nums2[i])\n )\n }\n }\n }\n return dp[limit - 1]\n}\n\nfunction bitCnt(num) {\n let res = 0\n while (num) {\n res++\n num = num & (num - 1)\n }\n\n return res\n}",
"const minimumXORSum = function (nums1, nums2) {\n const n = nums1.length, dp = Array(1 << n).fill(Infinity)\n return dfs(0, 0)\n function dfs(i, mask) {\n if(i === n) return 0\n if(dp[mask] !== Infinity) return dp[mask]\n for(let j = 0; j < n; j++) {\n if((mask & (1 << j)) === 0) {\n dp[mask] = Math.min(\n dp[mask], \n (nums1[i] ^ nums2[j]) + dfs(i + 1, mask | (1 << j))\n )\n }\n }\n return dp[mask]\n }\n}",
"const minimumXORSum = function(nums1, nums2) {\n const dp = Array(1 << nums2.length).fill(Infinity)\n return dfs(dp, nums1, nums2, 0, 0)\n};\n\nfunction dfs(dp, a, b, i, mask) {\n if(i >= a.length) return 0\n if(dp[mask] === Infinity) {\n for(let j = 0; j < b.length; j++) {\n if((mask & (1 << j)) === 0) {\n dp[mask] = Math.min(dp[mask], (a[i] ^ b[j]) + dfs(dp, a, b, i + 1, mask + (1 << j)))\n }\n }\n }\n return dp[mask]\n}",
"const minimumXORSum = function (nums1, nums2) {\n const dp = Array(1 << nums2.length).fill(Infinity)\n return dfs(0, 0)\n \n function dfs(i, mask) {\n if(i >= nums2.length) return 0\n if(dp[mask] != Infinity) return dp[mask]\n for(let j = 0; j < nums2.length; j++) {\n if((mask & (1 << j)) === 0) {\n dp[mask] = Math.min(dp[mask], (nums1[i] ^ nums2[j]) + dfs(i + 1, mask + (1 << j)) ) \n }\n } \n return dp[mask]\n }\n}",
"const minimumXORSum = function (nums1, nums2) {\n const n = nums1.length, dp = Array(1 << n).fill(Infinity)\n return dfs(0, 0)\n\n function dfs(i, mask) {\n if(i >= n) return 0\n if(dp[mask] !== Infinity) return dp[mask]\n for(let j = 0; j < n; j++) {\n if((mask & (1 << j)) === 0) {\n dp[mask] = Math.min(dp[mask], (nums1[i] ^ nums2[j]) + dfs(i + 1, mask | (1 << j)))\n }\n }\n return dp[mask]\n }\n}"
] |
|
1,880 | check-if-word-equals-summation-of-two-words | [
"Convert each character of each word to its numerical value.",
"Check if the numerical values satisfies the condition."
] | /**
* @param {string} firstWord
* @param {string} secondWord
* @param {string} targetWord
* @return {boolean}
*/
var isSumEqual = function(firstWord, secondWord, targetWord) {
}; | The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.).
The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.
For example, if s = "acb", we concatenate each letter's letter value, resulting in "021". After converting it, we get 21.
You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive.
Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.
Example 1:
Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb"
Output: true
Explanation:
The numerical value of firstWord is "acb" -> "021" -> 21.
The numerical value of secondWord is "cba" -> "210" -> 210.
The numerical value of targetWord is "cdb" -> "231" -> 231.
We return true because 21 + 210 == 231.
Example 2:
Input: firstWord = "aaa", secondWord = "a", targetWord = "aab"
Output: false
Explanation:
The numerical value of firstWord is "aaa" -> "000" -> 0.
The numerical value of secondWord is "a" -> "0" -> 0.
The numerical value of targetWord is "aab" -> "001" -> 1.
We return false because 0 + 0 != 1.
Example 3:
Input: firstWord = "aaa", secondWord = "a", targetWord = "aaaa"
Output: true
Explanation:
The numerical value of firstWord is "aaa" -> "000" -> 0.
The numerical value of secondWord is "a" -> "0" -> 0.
The numerical value of targetWord is "aaaa" -> "0000" -> 0.
We return true because 0 + 0 == 0.
Constraints:
1 <= firstWord.length, secondWord.length, targetWord.length <= 8
firstWord, secondWord, and targetWord consist of lowercase English letters from 'a' to 'j' inclusive.
| Easy | [
"string"
] | [
"const isSumEqual = function(firstWord, secondWord, targetWord) {\n let str = 'abcdefghij'\n const hash = {}, reverse = {}\n for(let i = 0; i < str.length; i++) {\n hash[str[i]] = i\n reverse[i] = str[i]\n }\n let len1 = firstWord.length, len2 = secondWord.length\n if (len1 < len2) return isSumEqual(secondWord, firstWord, targetWord)\n // len1 >= len2\n if (len1 > len2) {\n for(let i = len1 - len2; i > 0; i--) {\n secondWord = 'a' + secondWord\n }\n }\n let res = '', inc = 0\n for(let i = len1 - 1; i >= 0; i--) {\n const tmp = hash[firstWord[i]] + hash[secondWord[i]] + inc\n if (tmp > 9) {\n inc = 1\n } else {\n inc = 0\n }\n const cur = tmp % 10\n res = reverse[cur] + res\n }\n \n if(inc) res = 'b' + res\n // console.log(res)\n let r1 = '', r2 = ''\n for(let i = 0; i < targetWord.length; i++) {\n r1 = r1 + hash[targetWord[i]]\n }\n for(let i = 0; i < res.length; i++) {\n r2 = r2 + hash[res[i]]\n }\n return (+r1) === (+r2)\n};"
] |
|
1,881 | maximum-value-after-insertion | [
"Note that if the number is negative it's the same as positive but you look for the minimum instead.",
"In the case of maximum, if s[i] < x it's optimal that x is put before s[i].",
"In the case of minimum, if s[i] > x it's optimal that x is put before s[i]."
] | /**
* @param {string} n
* @param {number} x
* @return {string}
*/
var maxValue = function(n, x) {
}; | You are given a very large integer n, represented as a string, and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number.
You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n. You cannot insert x to the left of the negative sign.
For example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making n = 763.
If n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255.
Return a string representing the maximum value of n after the insertion.
Example 1:
Input: n = "99", x = 9
Output: "999"
Explanation: The result is the same regardless of where you insert 9.
Example 2:
Input: n = "-13", x = 2
Output: "-123"
Explanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123.
Constraints:
1 <= n.length <= 105
1 <= x <= 9
The digits in n are in the range [1, 9].
n is a valid representation of an integer.
In the case of a negative n, it will begin with '-'.
| Medium | [
"string",
"greedy"
] | [
"const maxValue = function(n, x) {\n const neg = n[0] === '-'\n if (neg) {\n for(let i = 1; i < n.length; i++) {\n if(+n[i] > x) {\n return n.slice(0, i) + x + n.slice(i)\n }\n }\n return n + x\n } else {\n for(let i = 0; i < n.length; i++) {\n if(+n[i] < x) {\n \n return n.slice(0, i) + x + n.slice(i)\n }\n }\n return n + x\n }\n};"
] |
|
1,882 | process-tasks-using-servers | [
"You can maintain a Heap of available Servers and a Heap of unavailable servers",
"Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules"
] | /**
* @param {number[]} servers
* @param {number[]} tasks
* @return {number[]}
*/
var assignTasks = function(servers, tasks) {
}; | You are given two 0-indexed integer arrays servers and tasks of lengths n and m respectively. servers[i] is the weight of the ith server, and tasks[j] is the time needed to process the jth task in seconds.
Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty.
At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index.
If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above.
A server that is assigned task j at second t will be free again at second t + tasks[j].
Build an array ans of length m, where ans[j] is the index of the server the jth task will be assigned to.
Return the array ans.
Example 1:
Input: servers = [3,3,2], tasks = [1,2,3,2,1,2]
Output: [2,2,0,2,1,2]
Explanation: Events in chronological order go as follows:
- At second 0, task 0 is added and processed using server 2 until second 1.
- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.
- At second 2, task 2 is added and processed using server 0 until second 5.
- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.
- At second 4, task 4 is added and processed using server 1 until second 5.
- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.
Example 2:
Input: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]
Output: [1,4,1,4,1,3,2]
Explanation: Events in chronological order go as follows:
- At second 0, task 0 is added and processed using server 1 until second 2.
- At second 1, task 1 is added and processed using server 4 until second 2.
- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4.
- At second 3, task 3 is added and processed using server 4 until second 7.
- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9.
- At second 5, task 5 is added and processed using server 3 until second 7.
- At second 6, task 6 is added and processed using server 2 until second 7.
Constraints:
servers.length == n
tasks.length == m
1 <= n, m <= 2 * 105
1 <= servers[i], tasks[j] <= 2 * 105
| Medium | [
"array",
"heap-priority-queue"
] | [
"const assignTasks = function(servers, tasks) {\n const avail = new PQ((a, b) => a[0] === b[0] ? a[1] < b[1] : a[0] < b[0])\n const busy = new PQ((a, b) => a[2] < b[2])\n const res = []\n const { max } = Math\n // init\n for(let i = 0, len = servers.length; i < len; i++) {\n avail.push([servers[i], i, 0])\n }\n \n for(let i = 0, len = tasks.length; i < len; i++) {\n while(!busy.isEmpty() && busy.peek()[2] <= i) {\n const s = busy.pop()\n s[2] = i\n avail.push(s)\n }\n if(!avail.isEmpty()) {\n const s = avail.pop()\n res.push(s[1])\n busy.push([s[0], s[1], max(i, s[2]) + tasks[i]])\n } else {\n const tmp = busy.peek()\n while(!busy.isEmpty() && busy.peek()[2] === tmp[2]) {\n avail.push(busy.pop())\n }\n const s = avail.pop()\n res.push(s[1])\n busy.push([s[0], s[1], max(i, s[2]) + tasks[i]])\n }\n }\n \n return res\n};\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}",
"const assignTasks = function (servers, tasks) {\n const available = new PriorityQueue((a, b) =>\n a[0] === b[0] ? a[1] < b[1] : a[0] < b[0]\n )\n const occupied = new PriorityQueue((a, b) =>\n a[0] === b[0] ? (a[1] === b[1] ? a[2] < b[2] : a[1] < b[1]) : a[0] < b[0]\n )\n\n const res = [],\n m = tasks.length,\n n = servers.length\n for (let i = 0; i < n; i++) {\n const w = servers[i]\n available.push([w, i])\n }\n let now = 0\n for (let i = 0; i < m; i++) {\n const t = tasks[i]\n\n while (!occupied.isEmpty() && occupied.peek()[0] <= now) {\n const [end, weight, index] = occupied.pop()\n available.push([weight, index])\n }\n\n let idx\n if (!available.isEmpty()) {\n const [weight, index] = available.pop()\n idx = index\n occupied.push([now + t, weight, index])\n if(i >= now) now++\n } else {\n let [endTime, weight, index] = occupied.pop()\n idx = index\n occupied.push([endTime + t, weight, index])\n now = endTime\n }\n\n res.push(idx)\n }\n\n return res\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}",
"const assignTasks = function(servers, tasks) {\n const freePQ = new PriorityQueue((a, b) => a.w === b.w ? a.i < b.i : a.w < b.w)\n const runningPQ = new PriorityQueue((a, b) => a.e === b.e ? (a.w === b.w ? a.i < b.i : a.w < b.w) : a.e < b.e)\n const m = servers.length, n = tasks.length\n for(let i = 0; i < m; i++) freePQ.push({w: servers[i], i, e: 0})\n const res = []\n for(let i = 0; i < n; i++) {\n const cur = tasks[i]\n while(!runningPQ.isEmpty() && runningPQ.peek().e <= i) {\n const tmp = runningPQ.pop()\n tmp.e = i\n freePQ.push(tmp)\n }\n if(freePQ.isEmpty()) {\n const tmp = runningPQ.pop()\n res[i] = tmp.i\n tmp.e += cur\n runningPQ.push(tmp)\n } else {\n const tmp = freePQ.pop()\n res[i] = tmp.i\n tmp.e = i + cur\n runningPQ.push(tmp)\n }\n }\n return res\n};",
"const assignTasks = function(servers, tasks) {\n let i = 0\n const freePQ = new PriorityQueue((a, b) => {\n if(a.w < b.w) return true\n else if(a.w > b.w) return false\n else {\n if(a.idx < b.idx) return true\n return false\n }\n })\n const runningPQ = new PriorityQueue((a, b) => {\n return a.end < b.end\n })\n const res = []\n for(let i = 0; i < servers.length; i++) {\n freePQ.push({\n w: servers[i],\n idx: i\n })\n }\n let taskIdx = 0\n while(taskIdx < tasks.length) {\n while(!runningPQ.isEmpty() && runningPQ.peek().end <= i) {\n let server = runningPQ.pop()\n freePQ.push({\n w: server.w,\n idx: server.idx\n })\n }\n \n while(taskIdx <= i && !freePQ.isEmpty() && taskIdx < tasks.length) {\n const server = freePQ.pop()\n res[taskIdx] = server.idx\n runningPQ.push({\n end: i + tasks[taskIdx],\n w: server.w,\n idx: server.idx\n })\n taskIdx++\n }\n if(i < tasks.length || !freePQ.isEmpty()) i++\n else i = Math.max(i + 1, runningPQ.peek().end)\n }\n return res\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}",
"const assignTasks = function(servers, tasks) {\n const freePQ = new PriorityQueue((a, b) => {\n if(a.w < b.w) return true\n else if(a.w > b.w) return false\n else {\n if(a.idx < b.idx) return true\n return false\n }\n })\n const runningPQ = new PriorityQueue((a, b) => {\n return a.end === b.end ? (a.w === b.w ? a.idx < b.idx : a.w < b.w) : a.end < b.end\n })\n const res = []\n for(let i = 0; i < servers.length; i++) {\n freePQ.push({\n w: servers[i],\n idx: i\n })\n }\n for(let i = 0, n = tasks.length; i < n; i++) {\n const cur = tasks[i]\n while(runningPQ.size() && runningPQ.peek().end <= i) {\n const el = runningPQ.pop()\n freePQ.push({\n w: el.w,\n idx: el.idx,\n })\n }\n \n if(freePQ.isEmpty()) {\n const el = runningPQ.pop()\n res[i] = el.idx\n el.end += cur\n runningPQ.push(el)\n } else {\n const el = freePQ.pop()\n res[i] = el.idx\n el.end = i + cur\n runningPQ.push(el)\n }\n }\n\n return res\n};"
] |
|
1,883 | minimum-skips-to-arrive-at-meeting-on-time | [
"Is there something you can keep track of from one road to another?",
"How would knowing the start time for each state help us solve the problem?"
] | /**
* @param {number[]} dist
* @param {number} speed
* @param {number} hoursBefore
* @return {number}
*/
var minSkips = function(dist, speed, hoursBefore) {
}; | You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at.
After you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.
For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait.
However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.
For example, suppose traveling the first road takes 1.4 hours and traveling the second road takes 0.6 hours. Skipping the rest after the first road will mean you finish traveling the second road right at the 2 hour mark, letting you start traveling the third road immediately.
Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.
Example 1:
Input: dist = [1,3,2], speed = 4, hoursBefore = 2
Output: 1
Explanation:
Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.
You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.
Note that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.
Example 2:
Input: dist = [7,3,5,5], speed = 2, hoursBefore = 10
Output: 2
Explanation:
Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.
You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours.
Example 3:
Input: dist = [7,3,5,5], speed = 1, hoursBefore = 10
Output: -1
Explanation: It is impossible to arrive at the meeting on time even if you skip all the rests.
Constraints:
n == dist.length
1 <= n <= 1000
1 <= dist[i] <= 105
1 <= speed <= 106
1 <= hoursBefore <= 107
| Hard | [
"array",
"dynamic-programming"
] | [
"const minSkips = function (dist, speed, hoursBefore) {\n let left = 0\n let right = dist.length\n\n while (left < right) {\n let mid = ~~(left + (right - left) / 2)\n if (dfs(dist, speed, mid) > 1.0 * hoursBefore) {\n left = mid + 1\n } else {\n right = mid\n }\n }\n return dfs(dist, speed, left) <= 1.0 * hoursBefore ? left : -1\n function dfs(dist, speed, skips) {\n const dp = Array.from({ length: dist.length }, () =>\n Array(skips + 1).fill(0)\n )\n let eps = 1e-9\n for (let i = 0; i <= skips; i++) {\n dp[0][i] = (dist[0] * 1.0) / speed - eps\n }\n\n for (let i = 1; i < dist.length; i++) {\n dp[i][0] = Math.ceil(dp[i - 1][0]) + (dist[i] * 1.0) / speed - eps\n for (let j = 1; j <= skips; j++) {\n let time = dp[i - 1][j - 1] + (dist[i] * 1.0) / speed - eps\n dp[i][j] = Math.min(\n time,\n Math.ceil(dp[i - 1][j]) + (dist[i] * 1.0) / speed - eps\n )\n }\n }\n return dp[dist.length - 1][skips]\n }\n}"
] |
|
1,884 | egg-drop-with-2-eggs-and-n-floors | [
"Is it really optimal to always drop the egg on the middle floor for each move?",
"Can we create states based on the number of unbroken eggs and floors to build our solution?"
] | /**
* @param {number} n
* @return {number}
*/
var twoEggDrop = function(n) {
}; | You are given two identical eggs and you have access to a building with n floors labeled from 1 to n.
You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.
In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.
Return the minimum number of moves that you need to determine with certainty what the value of f is.
Example 1:
Input: n = 2
Output: 2
Explanation: We can drop the first egg from floor 1 and the second egg from floor 2.
If the first egg breaks, we know that f = 0.
If the second egg breaks but the first egg didn't, we know that f = 1.
Otherwise, if both eggs survive, we know that f = 2.
Example 2:
Input: n = 100
Output: 14
Explanation: One optimal strategy is:
- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.
- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.
- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.
Regardless of the outcome, it takes at most 14 drops to determine f.
Constraints:
1 <= n <= 1000
| Medium | [
"math",
"dynamic-programming"
] | [
"const twoEggDrop = function (n) {\n const dp = Array(n + 1).fill(0)\n\n helper(n)\n// console.log(dp)\n return dp[n]\n\n function helper(k) {\n if(k === 0) return 0\n if (dp[k] === 0) {\n for (let i = 1; i <= k; i++) {\n dp[k] = Math.min(\n dp[k] === 0 ? k : dp[k],\n 1 + Math.max(i - 1, helper(k - i))\n )\n }\n }\n return dp[k]\n }\n}"
] |
|
1,886 | determine-whether-matrix-can-be-obtained-by-rotation | [
"What is the maximum number of rotations you have to check?",
"Is there a formula you can use to rotate a matrix 90 degrees?"
] | /**
* @param {number[][]} mat
* @param {number[][]} target
* @return {boolean}
*/
var findRotation = function(mat, target) {
}; | Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.
Example 1:
Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]
Output: true
Explanation: We can rotate mat 90 degrees clockwise to make mat equal target.
Example 2:
Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]
Output: false
Explanation: It is impossible to make mat equal to target by rotating mat.
Example 3:
Input: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]
Output: true
Explanation: We can rotate mat 90 degrees clockwise two times to make mat equal target.
Constraints:
n == mat.length == target.length
n == mat[i].length == target[i].length
1 <= n <= 10
mat[i][j] and target[i][j] are either 0 or 1.
| Easy | [
"array",
"matrix"
] | [
"const findRotation = function(mat, target) {\n if(chk(mat, target)) return true\n for(let i = 0; i < 3; i++) {\n rotate(mat)\n if(chk(mat, target)) return true\n }\n return false\n};\n\nfunction chk(m1, m2) {\n for(let i = 0; i < m1.length; i++) {\n for(let j = 0; j < m1.length; j++) {\n if(m1[i][j] !== m2[i][j]) return false\n }\n }\n return true\n}\n\nfunction rotate(matrix) {\n matrix.reverse()\n for (let i = 0; i < matrix.length; ++i) {\n for (let j = matrix[i].length - 1; j > i; j--) swap(matrix, i, j)\n }\n}\n\nfunction swap(matrix, i, j) {\n const tmp = matrix[j][i]\n matrix[j][i] = matrix[i][j]\n matrix[i][j] = tmp\n}"
] |
|
1,887 | reduction-operations-to-make-the-array-elements-equal | [
"Sort the array.",
"Try to reduce all elements with maximum value to the next maximum value in one operation."
] | /**
* @param {number[]} nums
* @return {number}
*/
var reductionOperations = function(nums) {
}; | Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:
Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i.
Find the next largest value in nums strictly smaller than largest. Let its value be nextLargest.
Reduce nums[i] to nextLargest.
Return the number of operations to make all elements in nums equal.
Example 1:
Input: nums = [5,1,3]
Output: 3
Explanation: It takes 3 operations to make all elements in nums equal:
1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].
2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].
3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].
Example 2:
Input: nums = [1,1,1]
Output: 0
Explanation: All elements in nums are already equal.
Example 3:
Input: nums = [1,1,2,2,3]
Output: 4
Explanation: It takes 4 operations to make all elements in nums equal:
1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].
2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].
3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].
4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].
Constraints:
1 <= nums.length <= 5 * 104
1 <= nums[i] <= 5 * 104
| Medium | [
"array",
"sorting"
] | [
"const reductionOperations = function(nums) {\n nums.sort((a, b) => a - b)\n const n = nums.length\n const arr = Array(n).fill(0)\n for(let i = 1; i < n; i++) {\n if(nums[i] > nums[i - 1]) arr[i] = 1\n }\n let res = 0, pre = 0\n \n for(let i = 1; i < n; i++) {\n if(arr[i] === 0) arr[i] = arr[i - 1]\n else arr[i] += arr[i - 1]\n }\n\n for(let e of arr) {\n res += e\n }\n return res\n};"
] |
|
1,888 | minimum-number-of-flips-to-make-the-binary-string-alternating | [
"Note what actually matters is how many 0s and 1s are in odd and even positions",
"For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity"
] | /**
* @param {string} s
* @return {number}
*/
var minFlips = function(s) {
}; | You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:
Type-1: Remove the character at the start of the string s and append it to the end of the string.
Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.
Return the minimum number of type-2 operations you need to perform such that s becomes alternating.
The string is called alternating if no two adjacent characters are equal.
For example, the strings "010" and "1010" are alternating, while the string "0100" is not.
Example 1:
Input: s = "111000"
Output: 2
Explanation: Use the first operation two times to make s = "100011".
Then, use the second operation on the third and sixth elements to make s = "101010".
Example 2:
Input: s = "010"
Output: 0
Explanation: The string is already alternating.
Example 3:
Input: s = "1110"
Output: 1
Explanation: Use the second operation on the second element to make s = "1010".
Constraints:
1 <= s.length <= 105
s[i] is either '0' or '1'.
| Medium | [
"string",
"dynamic-programming",
"greedy",
"sliding-window"
] | [
"const minFlips = function (s) {\n let n = s.length\n let t = s + s\n let a0 = 0\n let a1 = 0\n let b0 = 0\n let b1 = 0\n let ans = Infinity\n for (let i = 0; i < t.length; i++) {\n if (t[i] == '0') {\n if (i % 2 == 0) {\n a0++\n } else {\n b0++\n }\n } else {\n if (i % 2 == 0) {\n a1++\n } else {\n b1++\n }\n }\n\n if (i >= n) {\n if (t[i - n] == '0') {\n if ((i - n) % 2 == 0) {\n a0--\n } else {\n b0--\n }\n } else {\n if ((i - n) % 2 == 0) {\n a1--\n } else {\n b1--\n }\n }\n }\n ans = Math.min(ans, Math.min(n - a0 - b1, n - a1 - b0))\n }\n\n return ans\n}",
"const minFlips = function (s) {\n const n = s.length\n s += s\n let s1 = '', s2 = ''\n for(let i = 0;i < s.length; i++) {\n s1 += i % 2 === 0 ? '0' : '1'\n s2 += i % 2 === 0 ? '1' : '0'\n }\n let res1 = 0, res2 = 0, res = Infinity\n for(let i = 0; i < s.length; i++) {\n if(s1[i] !== s[i]) res1++\n if(s2[i] !== s[i]) res2++\n if(i >= n) {\n if(s1[i - n] !== s[i - n]) res1--\n if(s2[i - n] !== s[i - n]) res2--\n }\n if(i >= n - 1) {\n res = Math.min(res, res1, res2)\n }\n }\n \n return res\n}",
"const minFlips = function (s) {\n const n = s.length\n const ss = s + s\n let s1 = '', s2 = ''\n for(let i = 0; i < 2 * n; i++) {\n if(i % 2 === 0) {\n s1 += '0'\n s2 += '1'\n }else{\n s1 += '1'\n s2 += '0'\n }\n }\n\n let res = Infinity, res1 = 0, res2 = 0\n\n for (let i = 0; i < 2 * n; i++) {\n if(ss[i] !== s1[i]) res1++\n if(ss[i] !== s2[i]) res2++\n if(i >= n) {\n if(ss[i - n] !== s1[i - n]) res1--\n if(ss[i - n] !== s2[i - n]) res2--\n }\n if(i >= n - 1) {\n res = Math.min(res, res1, res2)\n }\n }\n\n return res\n}"
] |
|
1,889 | minimum-space-wasted-from-packaging | [
"Given a fixed size box, is there a way to quickly query which packages (i.e., count and sizes) should end up in that box size?",
"Do we have to order the boxes a certain way to allow us to answer the query quickly?"
] | /**
* @param {number[]} packages
* @param {number[][]} boxes
* @return {number}
*/
var minWastedSpace = function(packages, boxes) {
}; | You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box.
The package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces.
You want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes.
For example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8], you can fit the packages of size-2 and size-3 into two boxes of size-4 and the package with size-5 into a box of size-8. This would result in a waste of (4-2) + (4-3) + (8-5) = 6.
Return the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7.
Example 1:
Input: packages = [2,3,5], boxes = [[4,8],[2,8]]
Output: 6
Explanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.
The total waste is (4-2) + (4-3) + (8-5) = 6.
Example 2:
Input: packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]
Output: -1
Explanation: There is no box that the package of size 5 can fit in.
Example 3:
Input: packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]
Output: 9
Explanation: It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.
The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.
Constraints:
n == packages.length
m == boxes.length
1 <= n <= 105
1 <= m <= 105
1 <= packages[i] <= 105
1 <= boxes[j].length <= 105
1 <= boxes[j][k] <= 105
sum(boxes[j].length) <= 105
The elements in boxes[j] are distinct.
| Hard | [
"array",
"binary-search",
"sorting",
"prefix-sum"
] | [
"const minWastedSpace = function (packages, boxes) {\n const mod = 1e9 + 7\n const n = packages.length\n packages.sort((a, b) => a - b)\n const preSum = packages.reduce(\n (acc, cur) => {\n acc.push(acc[acc.length - 1] + cur)\n return acc\n },\n [0]\n )\n\n const upperBound = (target) => {\n let lo = 0,\n hi = n\n while (lo < hi) {\n const mi = (lo + hi) >> 1\n const val = packages[mi]\n if (val <= target) {\n lo = mi + 1\n } else {\n hi = mi\n }\n }\n return lo\n }\n\n let res = Infinity\n for (const bs of boxes) {\n bs.sort((a, b) => b - a)\n if (bs[0] < packages[n - 1]) continue\n let wastes = bs[0] * n - preSum[n]\n let last = bs[0]\n for (let i = 1; i < bs.length; i++) {\n const b = bs[i]\n const j = upperBound(b)\n if (j <= 0) {\n break\n }\n wastes -= (last - b) * j\n last = b\n }\n res = Math.min(res, wastes)\n }\n return res === Infinity ? -1 : res % mod\n}",
"var minWastedSpace = function (packages, boxes) {\n packages.sort(function (a, b) {\n return a - b\n })\n let count = 0,\n b,\n wastage,\n minWastage = Number.MAX_SAFE_INTEGER,\n flag = false\n for (let i = 0; i < boxes.length; i++) {\n boxes[i].sort(function (a, b) {\n return a - b\n })\n b = 0\n wastage = 0\n count = 0\n if (boxes[i][boxes[i].length - 1] < packages[packages.length - 1]) {\n //This supplier's largest box is smaller than our larget package, this supplier can't be used\n continue\n }\n while (count < packages.length && b < boxes[i].length) {\n if (packages[count] <= boxes[i][b]) {\n wastage += boxes[i][b] - packages[count]\n if (wastage > minWastage) {\n //Need not to porcess this supplier if wastage has already been more than minWastage\n break\n }\n count++\n } else {\n b++\n }\n }\n if (count === packages.length) {\n flag = true //We have found atleas 1 answer\n if (wastage < minWastage) {\n minWastage = wastage\n }\n }\n }\n if (flag === false) {\n return -1\n }\n return minWastage % 1000000007\n}"
] |
|
1,893 | check-if-all-the-integers-in-a-range-are-covered | [
"Iterate over every integer point in the range [left, right].",
"For each of these points check if it is included in one of the ranges."
] | /**
* @param {number[][]} ranges
* @param {number} left
* @param {number} right
* @return {boolean}
*/
var isCovered = function(ranges, left, right) {
}; | You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi.
Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise.
An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi.
Example 1:
Input: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5
Output: true
Explanation: Every integer between 2 and 5 is covered:
- 2 is covered by the first range.
- 3 and 4 are covered by the second range.
- 5 is covered by the third range.
Example 2:
Input: ranges = [[1,10],[10,20]], left = 21, right = 21
Output: false
Explanation: 21 is not covered by any range.
Constraints:
1 <= ranges.length <= 50
1 <= starti <= endi <= 50
1 <= left <= right <= 50
| Easy | [
"array",
"hash-table",
"prefix-sum"
] | [
"const isCovered = function(ranges, left, right) {\n const arr = Array(52).fill(0)\n for(let [s, e] of ranges) {\n arr[s]++\n arr[e + 1]--\n }\n for(let i = 1; i < 52; i++) {\n arr[i] += arr[i - 1]\n }\n for(let i = left; i <= right; i++) {\n if(arr[i] === 0) return false\n }\n \n return true\n};",
"const isCovered = function(ranges, left, right) {\n\tfor(let i = left; i <= right; i++) {\n\t\tlet seen = false;\n\t\tfor(let j = 0; j < ranges.length && !seen; j++) \n\t\t\tif(i >= ranges[j][0] && i <= ranges[j][1]) \n\t\t\t\tseen = true;\n\t\tif(!seen) return false;\n\t}\n\treturn true;\n};",
"const isCovered = function(ranges, left, right) {\n const arr = Array(52).fill(0)\n for(let [s, e] of ranges) {\n arr[s]++\n arr[e + 1]--\n }\n\n let overlaps = 0\n for(let i = 1; i <= right; i++) {\n overlaps += arr[i];\n if (i >= left && overlaps == 0) return false;\n }\n \n return true\n};"
] |
|
1,894 | find-the-student-that-will-replace-the-chalk | [
"Subtract the sum of chalk from k until k is less than the sum of chalk.",
"Now iterate over the array. If chalk[i] is less than k, this is the answer. Otherwise, subtract chalk[i] from k and continue."
] | /**
* @param {number[]} chalk
* @param {number} k
* @return {number}
*/
var chalkReplacer = function(chalk, k) {
}; | There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again.
You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk.
Return the index of the student that will replace the chalk pieces.
Example 1:
Input: chalk = [5,1,5], k = 22
Output: 0
Explanation: The students go in turns as follows:
- Student number 0 uses 5 chalk, so k = 17.
- Student number 1 uses 1 chalk, so k = 16.
- Student number 2 uses 5 chalk, so k = 11.
- Student number 0 uses 5 chalk, so k = 6.
- Student number 1 uses 1 chalk, so k = 5.
- Student number 2 uses 5 chalk, so k = 0.
Student number 0 does not have enough chalk, so they will have to replace it.
Example 2:
Input: chalk = [3,4,1,2], k = 25
Output: 1
Explanation: The students go in turns as follows:
- Student number 0 uses 3 chalk so k = 22.
- Student number 1 uses 4 chalk so k = 18.
- Student number 2 uses 1 chalk so k = 17.
- Student number 3 uses 2 chalk so k = 15.
- Student number 0 uses 3 chalk so k = 12.
- Student number 1 uses 4 chalk so k = 8.
- Student number 2 uses 1 chalk so k = 7.
- Student number 3 uses 2 chalk so k = 5.
- Student number 0 uses 3 chalk so k = 2.
Student number 1 does not have enough chalk, so they will have to replace it.
Constraints:
chalk.length == n
1 <= n <= 105
1 <= chalk[i] <= 105
1 <= k <= 109
| Medium | [
"array",
"binary-search",
"simulation",
"prefix-sum"
] | null | [] |
1,895 | largest-magic-square | [
"Check all squares in the matrix and find the largest one."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var largestMagicSquare = function(grid) {
}; | A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square.
Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid.
Example 1:
Input: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]
Output: 3
Explanation: The largest magic square has a size of 3.
Every row sum, column sum, and diagonal sum of this magic square is equal to 12.
- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12
- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12
- Diagonal sums: 5+4+3 = 6+4+2 = 12
Example 2:
Input: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]
Output: 2
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 106
| Medium | [
"array",
"matrix",
"prefix-sum"
] | null | [] |
1,896 | minimum-cost-to-change-the-final-value-of-expression | [
"How many possible states are there for a given expression?",
"Is there a data structure that we can use to solve the problem optimally?"
] | /**
* @param {string} expression
* @return {number}
*/
var minOperationsToFlip = function(expression) {
}; | You are given a valid boolean expression as a string expression consisting of the characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'.
For example, "()1|1" and "(1)&()" are not valid while "1", "(((1))|(0))", and "1|(0&(1))" are valid expressions.
Return the minimum cost to change the final value of the expression.
For example, if expression = "1|1|(0&0)&1", its value is 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1. We want to apply operations so that the new expression evaluates to 0.
The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows:
Turn a '1' into a '0'.
Turn a '0' into a '1'.
Turn a '&' into a '|'.
Turn a '|' into a '&'.
Note: '&' does not take precedence over '|' in the order of calculation. Evaluate parentheses first, then in left-to-right order.
Example 1:
Input: expression = "1&(0|1)"
Output: 1
Explanation: We can turn "1&(0|1)" into "1&(0&1)" by changing the '|' to a '&' using 1 operation.
The new expression evaluates to 0.
Example 2:
Input: expression = "(0&0)&(0&0&0)"
Output: 3
Explanation: We can turn "(0&0)&(0&0&0)" into "(0|1)|(0&0&0)" using 3 operations.
The new expression evaluates to 1.
Example 3:
Input: expression = "(0|(1|0&1))"
Output: 1
Explanation: We can turn "(0|(1|0&1))" into "(0|(0|0&1))" using 1 operation.
The new expression evaluates to 0.
Constraints:
1 <= expression.length <= 105
expression only contains '1','0','&','|','(', and ')'
All parentheses are properly matched.
There will be no empty parentheses (i.e: "()" is not a substring of expression).
| Hard | [
"math",
"string",
"dynamic-programming",
"stack"
] | [
"function minOperationsToFlip (s) {\n const nums = []\n const ops = []\n for (let i = 0; i < s.length; i++) {\n if (s[i] === '0') nums.push([0, 0, 1])\n else if (s[i] === '1') nums.push([1, 1, 0])\n else if (s[i] === '(') ops.push('(')\n else if (s[i] === ')') {\n while (ops.length && ops[ops.length - 1] !== '(') {\n const op = ops.pop()\n calc(op)\n }\n if (ops.length) ops.pop()\n } else {\n while (ops.length && grade(ops[ops.length - 1]) >= grade(s[i])) {\n const op = ops.pop()\n calc(op)\n }\n ops.push(s[i])\n }\n }\n\n while (ops.length && nums.length >= 2) {\n const op = ops.pop()\n calc(op)\n }\n const val = nums[0][0]\n return nums[0][2 - val]\n\n function calc (op) {\n const [x, y] = [nums.pop(), nums.pop()]\n let [z, a0, a1] = [0, 0, 0]\n switch (op) {\n case '&':\n z = x[0] & y[0]\n if (x[0] === 0 && y[0] === 0) {\n a0 = 0\n a1 = Math.min(x[2] + 1, y[2] + 1)\n }\n if (x[0] === 0 && y[0] === 1) {\n a0 = 0\n a1 = 1\n }\n if (x[0] === 1 && y[0] === 0) {\n a0 = 0\n a1 = 1\n }\n if (x[0] === 1 && y[0] === 1) {\n a0 = Math.min(x[1], y[1])\n a1 = 0\n }\n break\n case '|':\n z = x[0] | y[0]\n if (x[0] === 0 && y[0] === 0) {\n a0 = 0\n a1 = Math.min(x[2], y[2])\n }\n if (x[0] === 0 && y[0] === 1) {\n a0 = 1\n a1 = 0\n }\n if (x[0] === 1 && y[0] === 0) {\n a0 = 1\n a1 = 0\n }\n if (x[0] === 1 && y[0] === 1) {\n a0 = Math.min(x[1] + 1, y[1] + 1)\n a1 = 0\n }\n break\n }\n nums.push([z, a0, a1])\n }\n function grade (op) {\n switch (op) {\n case '(':\n return 1\n case '&':\n case '|':\n return 2\n }\n return 0\n }\n};"
] |
|
1,897 | redistribute-characters-to-make-all-strings-equal | [
"Characters are independent—only the frequency of characters matters.",
"It is possible to distribute characters if all characters can be divided equally among all strings."
] | /**
* @param {string[]} words
* @return {boolean}
*/
var makeEqual = function(words) {
}; | You are given an array of strings words (0-indexed).
In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].
Return true if you can make every string in words equal using any number of operations, and false otherwise.
Example 1:
Input: words = ["abc","aabc","bc"]
Output: true
Explanation: Move the first 'a' in words[1] to the front of words[2],
to make words[1] = "abc" and words[2] = "abc".
All the strings are now equal to "abc", so return true.
Example 2:
Input: words = ["ab","a"]
Output: false
Explanation: It is impossible to make all the strings equal using the operation.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] consists of lowercase English letters.
| Easy | [
"hash-table",
"string",
"counting"
] | [
"const makeEqual = function(words) {\n const arr = Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n for(let w of words) {\n for(let ch of w) {\n arr[ch.charCodeAt(0) - a]++\n }\n }\n const n = words.length\n for(let i = 0; i < 26; i++) {\n if(arr[i] % n !== 0) return false\n }\n return true\n};"
] |
|
1,898 | maximum-number-of-removable-characters | [
"First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence",
"We can binary search the K and check by solving the above problem."
] | /**
* @param {string} s
* @param {string} p
* @param {number[]} removable
* @return {number}
*/
var maximumRemovals = function(s, p, removable) {
}; | You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed).
You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence.
Return the maximum k you can choose such that p is still a subsequence of s after the removals.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Example 1:
Input: s = "abcacb", p = "ab", removable = [3,1,0]
Output: 2
Explanation: After removing the characters at indices 3 and 1, "abcacb" becomes "accb".
"ab" is a subsequence of "accb".
If we remove the characters at indices 3, 1, and 0, "abcacb" becomes "ccb", and "ab" is no longer a subsequence.
Hence, the maximum k is 2.
Example 2:
Input: s = "abcbddddd", p = "abcd", removable = [3,2,1,4,5,6]
Output: 1
Explanation: After removing the character at index 3, "abcbddddd" becomes "abcddddd".
"abcd" is a subsequence of "abcddddd".
Example 3:
Input: s = "abcab", p = "abc", removable = [0,1,2,3,4]
Output: 0
Explanation: If you remove the first index in the array removable, "abc" is no longer a subsequence.
Constraints:
1 <= p.length <= s.length <= 105
0 <= removable.length < s.length
0 <= removable[i] < s.length
p is a subsequence of s.
s and p both consist of lowercase English letters.
The elements in removable are distinct.
| Medium | [
"array",
"string",
"binary-search"
] | [
"const maximumRemovals = function (s, p, removable) {\n const n = removable.length\n let l = 0,\n r = n\n while (l < r) {\n let mid = (l + r + 1) >> 1\n if (is_valid(s, p, removable, mid)) l = mid\n else r = mid - 1\n }\n return l\n}\n\nfunction is_valid(s, p, removable, cnt) {\n let len1 = s.length,\n len2 = p.length\n const check = Array(len1).fill(0)\n for (let i = 0; i < cnt; i++) check[removable[i]] = 1\n let ind1 = 0,\n ind2 = 0\n while (ind1 < len1 && ind2 < len2) {\n if (s[ind1] != p[ind2] || check[ind1]) {\n ind1++\n continue\n }\n ind1++, ind2++\n }\n return ind2 == len2\n}",
"const maximumRemovals = function(s, p, removable) {\n let l = 0, r = removable.length\n while(l < r) {\n const mid = r - Math.floor((r - l) / 2)\n if(valid(mid)) l = mid\n else r = mid - 1\n }\n return l\n \n function valid(mid) {\n let arr = s.split('')\n for (let i = 0; i < mid; i++) arr[removable[i]] = null\n arr = arr.filter(e => e !== null)\n \n for(let i = 0, j = 0; i < arr.length && j < p.length;) {\n if(arr[i] === p[j]) i++, j++\n else i++\n if(j === p.length) return true\n }\n return false\n }\n};"
] |
|
1,899 | merge-triplets-to-form-target-triplet | [
"Which triplets do you actually care about?",
"What property of max can you use to solve the problem?"
] | /**
* @param {number[][]} triplets
* @param {number[]} target
* @return {boolean}
*/
var mergeTriplets = function(triplets, target) {
}; | A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain.
To obtain target, you may apply the following operation on triplets any number of times (possibly zero):
Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)].
For example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5].
Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.
Example 1:
Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]
Output: true
Explanation: Perform the following operations:
- Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]]
The target triplet [2,7,5] is now an element of triplets.
Example 2:
Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5]
Output: false
Explanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets.
Example 3:
Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]
Output: true
Explanation: Perform the following operations:
- Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]].
- Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]].
The target triplet [5,5,5] is now an element of triplets.
Constraints:
1 <= triplets.length <= 105
triplets[i].length == target.length == 3
1 <= ai, bi, ci, x, y, z <= 1000
| Medium | [
"array",
"greedy"
] | [
"const mergeTriplets = function (triplets, target) {\n let n = triplets.length\n const ans = Array(3).fill(0)\n const { max } = Math\n for (let i = 0; i < n; i++) {\n if (\n triplets[i][0] <= target[0] &&\n triplets[i][1] <= target[1] &&\n triplets[i][2] <= target[2]\n ) {\n ans[0] = max(ans[0], triplets[i][0])\n ans[1] = max(ans[1], triplets[i][1])\n ans[2] = max(ans[2], triplets[i][2])\n }\n }\n return ans[0] == target[0] && ans[1] == target[1] && ans[2] == target[2]\n}"
] |
|
1,900 | the-earliest-and-latest-rounds-where-players-compete | [
"Brute force using bitmasks and simulate the rounds.",
"Calculate each state one time and save its solution."
] | /**
* @param {number} n
* @param {number} firstPlayer
* @param {number} secondPlayer
* @return {number[]}
*/
var earliestAndLatest = function(n, firstPlayer, secondPlayer) {
}; | There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.).
The tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round.
For example, if the row consists of players 1, 2, 4, 6, 7
Player 1 competes against player 7.
Player 2 competes against player 6.
Player 4 automatically advances to the next round.
After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order).
The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round.
Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively.
Example 1:
Input: n = 11, firstPlayer = 2, secondPlayer = 4
Output: [3,4]
Explanation:
One possible scenario which leads to the earliest round number:
First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
Second round: 2, 3, 4, 5, 6, 11
Third round: 2, 3, 4
One possible scenario which leads to the latest round number:
First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
Second round: 1, 2, 3, 4, 5, 6
Third round: 1, 2, 4
Fourth round: 2, 4
Example 2:
Input: n = 5, firstPlayer = 1, secondPlayer = 5
Output: [1,1]
Explanation: The players numbered 1 and 5 compete in the first round.
There is no way to make them compete in any other round.
Constraints:
2 <= n <= 28
1 <= firstPlayer < secondPlayer <= n
| Hard | [
"dynamic-programming",
"memoization"
] | [
"const earliestAndLatest = function (n, firstPlayer, secondPlayer) {\n const { max, min } = Math\n const hash = {}\n function dp(l, r, m) {\n const key = `${l}${r}${m}`\n if (hash[key] != null) return hash[key]\n if (l > r) return dp(r, l, m)\n if (l === r) return [1, 1]\n let nxt_m = (m + 1) >> 1\n let ans = [n, 0]\n for (let i = 1; i < l + 1; i++) {\n let l_win = i - 1,\n l_lose = l - i\n for (\n let j = max(r - ~~(m / 2) - 1, 0) + l_lose + 1;\n j < min(r - 1 - l_win, nxt_m - i) + 1;\n j++\n ) {\n let tmp = dp(i, j, nxt_m)\n ans = [min(ans[0], tmp[0]), max(ans[1], tmp[1])]\n }\n }\n hash[key] = [ans[0] + 1, ans[1] + 1]\n return hash[key]\n }\n\n return dp(firstPlayer, n - secondPlayer + 1, n)\n}"
] |
|
1,901 | find-a-peak-element-ii | [
"Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction.",
"Split the array into three parts: central column left side and right side.",
"Go through the central column and two neighbor columns and look for maximum.",
"If it's in the central column - this is our peak.",
"If it's on the left side, run this algorithm on subarray left_side + central_column.",
"If it's on the right side, run this algorithm on subarray right_side + central_column"
] | /**
* @param {number[][]} mat
* @return {number[]}
*/
var findPeakGrid = function(mat) {
}; | A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom.
Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j].
You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell.
You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.
Example 1:
Input: mat = [[1,4],[3,2]]
Output: [0,1]
Explanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.
Example 2:
Input: mat = [[10,20,15],[21,30,14],[7,16,32]]
Output: [1,1]
Explanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 500
1 <= mat[i][j] <= 105
No two adjacent cells are equal.
| Medium | [
"array",
"binary-search",
"matrix"
] | [
"const findPeakGrid = function(mat) {\n let lowCol = 0;\n let highCol = mat[0].length - 1;\n\n while(lowCol <= highCol) {\n let midCol = lowCol + ~~((highCol - lowCol) / 2);\n let maxRow = 0;\n for(let i = 0; i < mat.length; i++) {\n maxRow = mat[i][midCol] > mat[maxRow][midCol] ? i : maxRow;\n }\n\n let isLeftElementBig = midCol - 1 >= lowCol && mat[maxRow][midCol - 1] > mat[maxRow][midCol];\n let isRightElementBig = midCol + 1 <= highCol && mat[maxRow][midCol + 1] > mat[maxRow][midCol];\n\n if(!isLeftElementBig && !isRightElementBig) {\n return [maxRow, midCol];\n } else if(isRightElementBig) {\n lowCol = midCol + 1;\n } else {\n highCol = midCol - 1;\n }\n }\n return null;\n};"
] |
|
1,903 | largest-odd-number-in-string | [
"In what order should you iterate through the digits?",
"If an odd number exists, where must the number start from?"
] | /**
* @param {string} num
* @return {string}
*/
var largestOddNumber = function(num) {
}; | You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: num = "52"
Output: "5"
Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number.
Example 2:
Input: num = "4206"
Output: ""
Explanation: There are no odd numbers in "4206".
Example 3:
Input: num = "35427"
Output: "35427"
Explanation: "35427" is already an odd number.
Constraints:
1 <= num.length <= 105
num only consists of digits and does not contain any leading zeros.
| Easy | [
"math",
"string",
"greedy"
] | [
"const largestOddNumber = function(num) {\n let idx= -1\n for(let i = 0, n = num.length; i < n; i++) {\n if((+num[i]) % 2 === 1) idx = i\n }\n return num.slice(0, idx+1)\n};"
] |
|
1,904 | the-number-of-full-rounds-you-have-played | [
"Consider the day as 48 hours instead of 24.",
"For each round check if you were playing."
] | /**
* @param {string} loginTime
* @param {string} logoutTime
* @return {number}
*/
var numberOfRounds = function(loginTime, logoutTime) {
}; | You are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00, and after every 15 minutes, a new round starts.
For example, the second round starts at 00:15, the fourth round starts at 00:45, and the seventh round starts at 01:30.
You are given two strings loginTime and logoutTime where:
loginTime is the time you will login to the game, and
logoutTime is the time you will logout from the game.
If logoutTime is earlier than loginTime, this means you have played from loginTime to midnight and from midnight to logoutTime.
Return the number of full chess rounds you have played in the tournament.
Note: All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00 and the last round of the day starts at 23:45.
Example 1:
Input: loginTime = "09:31", logoutTime = "10:14"
Output: 1
Explanation: You played one full round from 09:45 to 10:00.
You did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began.
You did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended.
Example 2:
Input: loginTime = "21:30", logoutTime = "03:00"
Output: 22
Explanation: You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00.
10 + 12 = 22.
Constraints:
loginTime and logoutTime are in the format hh:mm.
00 <= hh <= 23
00 <= mm <= 59
loginTime and logoutTime are not equal.
| Medium | [
"math",
"string"
] | [
"const numberOfRounds = function(startTime, finishTime) {\n let start = 60 * parseInt(startTime.slice(0, 2)) + parseInt(startTime.slice(3))\n let finish = 60 * parseInt(finishTime.slice(0, 2)) + parseInt(finishTime.slice(3));\n if (start > finish) finish += 60 * 24; // If `finishTime` is earlier than `startTime`, add 24 hours to `finishTime`.\n return Math.max(0, Math.floor(finish / 15) - Math.ceil(start / 15)); // floor(finish / 15) - ceil(start / 15)\n};",
"const numberOfRounds = function(startTime, finishTime) {\n const { ceil, floor } = Math\n const start = new Node(startTime), finish = new Node(finishTime)\n if(finish.compare(start)) finish.hour += 24\n let cnt = 0\n if(start.hour === finish.hour) {\n const r = floor(finish.minute / 15)\n const l = ceil(start.minute / 15)\n if(l >= r) return 0\n return r - l\n }\n cnt += 4 - ceil(start.minute / 15) + floor(finish.minute / 15)\n start.hour++\n cnt += (finish.hour - start.hour) * 4\n return cnt\n};\n\nclass Node {\n constructor(str) {\n this.hour = +str.slice(0, 2)\n this.minute = +str.slice(3)\n }\n compare(node) {\n return this.hour === node.hour ? this.minute < node.minute : this.hour < node.hour\n }\n}"
] |
|
1,905 | count-sub-islands | [
"Let's use floodfill to iterate over the islands of the second grid",
"Let's note that if all the cells in an island in the second grid if they are represented by land in the first grid then they are connected hence making that island a sub-island"
] | /**
* @param {number[][]} grid1
* @param {number[][]} grid2
* @return {number}
*/
var countSubIslands = function(grid1, grid2) {
}; | You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.
An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.
Return the number of islands in grid2 that are considered sub-islands.
Example 1:
Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
Output: 3
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
Example 2:
Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
Output: 2
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
Constraints:
m == grid1.length == grid2.length
n == grid1[i].length == grid2[i].length
1 <= m, n <= 500
grid1[i][j] and grid2[i][j] are either 0 or 1.
| Medium | [
"array",
"depth-first-search",
"breadth-first-search",
"union-find",
"matrix"
] | [
"const countSubIslands = function(grid1, grid2) {\n let m = grid2.length, n = grid2[0].length, res = 0;\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid2[i][j] === 1) res += dfs(grid1, grid2, i, j); \n }\n }\n return res; \n};\n\nfunction dfs(B, A, i, j) {\n let m = A.length, n = A[0].length, res = 1;\n if (i < 0 || i == m || j < 0 || j == n || A[i][j] == 0) return 1;\n A[i][j] = 0;\n res &= dfs(B, A, i - 1, j);\n res &= dfs(B, A, i + 1, j);\n res &= dfs(B, A, i, j - 1);\n res &= dfs(B, A, i, j + 1);\n return res & B[i][j];\n}"
] |
|
1,906 | minimum-absolute-difference-queries | [
"How does the maximum value being 100 help us?",
"How can we tell if a number exists in a given range?"
] | /**
* @param {number[]} nums
* @param {number[][]} queries
* @return {number[]}
*/
var minDifference = function(nums, queries) {
}; | The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1.
For example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note that it is not 0 because a[i] and a[j] must be different.
You are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive).
Return an array ans where ans[i] is the answer to the ith query.
A subarray is a contiguous sequence of elements in an array.
The value of |x| is defined as:
x if x >= 0.
-x if x < 0.
Example 1:
Input: nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]
Output: [2,1,4,1]
Explanation: The queries are processed as follows:
- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.
- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.
- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.
- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.
Example 2:
Input: nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]
Output: [-1,1,1,3]
Explanation: The queries are processed as follows:
- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the
elements are the same.
- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.
- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.
- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.
Constraints:
2 <= nums.length <= 105
1 <= nums[i] <= 100
1 <= queries.length <= 2 * 104
0 <= li < ri < nums.length
| Medium | [
"array",
"hash-table"
] | [
"const minDifference = function (nums, queries) {\n const res = [],\n cnt = Array.from({ length: nums.length + 1 }, () => Array(101).fill(0))\n\n for (let i = 0; i < nums.length; ++i) {\n for (let j = 1; j <= 100; ++j) {\n cnt[i + 1][j] = cnt[i][j] + (nums[i] == j)\n }\n }\n\n for (let i = 0; i < queries.length; ++i) {\n let prev = 0,\n delta = Infinity\n for (let j = 1; j <= 100; ++j)\n if (cnt[queries[i][1] + 1][j] - cnt[queries[i][0]][j]) {\n delta = Math.min(delta, prev == 0 ? Infinity : j - prev)\n prev = j\n }\n res.push(delta == Infinity ? -1 : delta)\n }\n return res\n}"
] |
|
1,909 | remove-one-element-to-make-the-array-strictly-increasing | [
"For each index i in nums remove this index.",
"If the array becomes sorted return true, otherwise revert to the original array and try different index."
] | /**
* @param {number[]} nums
* @return {boolean}
*/
var canBeIncreasing = function(nums) {
}; | Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true.
The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Example 1:
Input: nums = [1,2,10,5,7]
Output: true
Explanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].
[1,2,5,7] is strictly increasing, so return true.
Example 2:
Input: nums = [2,3,1,2]
Output: false
Explanation:
[3,1,2] is the result of removing the element at index 0.
[2,1,2] is the result of removing the element at index 1.
[2,3,2] is the result of removing the element at index 2.
[2,3,1] is the result of removing the element at index 3.
No resulting array is strictly increasing, so return false.
Example 3:
Input: nums = [1,1,1]
Output: false
Explanation: The result of removing any element is [1,1].
[1,1] is not strictly increasing, so return false.
Constraints:
2 <= nums.length <= 1000
1 <= nums[i] <= 1000
| Easy | [
"array"
] | [
"const canBeIncreasing = function(nums) {\n\tlet previous = nums[0];\n\tlet used = false;\n\tfor (let i = 1; i < nums.length; i++){\n\t\tif (nums[i] <= previous) {\n if (used) return false;\n used = true;\n if (i === 1 || nums[i] > nums[i - 2]) previous = nums[i];\n\t\t} else previous = nums[i];\n\t}\n\treturn true;\n};"
] |
|
1,910 | remove-all-occurrences-of-a-substring | [
"Note that a new occurrence of pattern can appear if you remove an old one, For example, s = \"ababcc\" and pattern = \"abc\".",
"You can maintain a stack of characters and if the last character of the pattern size in the stack match the pattern remove them"
] | /**
* @param {string} s
* @param {string} part
* @return {string}
*/
var removeOccurrences = function(s, part) {
}; | Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:
Find the leftmost occurrence of the substring part and remove it from s.
Return s after removing all occurrences of part.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "daabcbaabcbc", part = "abc"
Output: "dab"
Explanation: The following operations are done:
- s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc".
- s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc".
- s = "dababc", remove "abc" starting at index 3, so s = "dab".
Now s has no occurrences of "abc".
Example 2:
Input: s = "axxxxyyyyb", part = "xy"
Output: "ab"
Explanation: The following operations are done:
- s = "axxxxyyyyb", remove "xy" starting at index 4 so s = "axxxyyyb".
- s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb".
- s = "axxyyb", remove "xy" starting at index 2 so s = "axyb".
- s = "axyb", remove "xy" starting at index 1 so s = "ab".
Now s has no occurrences of "xy".
Constraints:
1 <= s.length <= 1000
1 <= part.length <= 1000
s and part consists of lowercase English letters.
| Medium | [
"string"
] | [
"var removeOccurrences = function(s, part) {\n while(s.indexOf(part) !== -1) {\n const idx = s.indexOf(part)\n s = s.slice(0, idx) + s.slice(idx + part.length)\n // console.log(s)\n }\n return s\n};"
] |
|
1,911 | maximum-alternating-subsequence-sum | [
"Is only tracking a single sum enough to solve the problem?",
"How does tracking an odd sum and an even sum reduce the number of states?"
] | /**
* @param {number[]} nums
* @return {number}
*/
var maxAlternatingSum = function(nums) {
}; | The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.
For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4.
Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence).
A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.
Example 1:
Input: nums = [4,2,5,3]
Output: 7
Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7.
Example 2:
Input: nums = [5,6,7,8]
Output: 8
Explanation: It is optimal to choose the subsequence [8] with alternating sum 8.
Example 3:
Input: nums = [6,2,1,2,4,5]
Output: 10
Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105
| Medium | [
"array",
"dynamic-programming"
] | [
"const maxAlternatingSum = function(nums) {\n let odd = 0, even = 0;\n for (let a of nums) {\n even = Math.max(even, odd + a);\n odd = even - a;\n }\n return even;\n};",
"const maxAlternatingSum = function(nums) {\n let res = nums[0]\n for(let i = 1; i < nums.length; i++) {\n res += Math.max(nums[i] - nums[i - 1], 0)\n }\n return res\n};"
] |
|
1,912 | design-movie-rental-system | [
"You need to maintain a sorted list for each movie and a sorted list for rented movies",
"When renting a movie remove it from its movies sorted list and added it to the rented list and vice versa in the case of dropping a movie"
] | /**
* @param {number} n
* @param {number[][]} entries
*/
var MovieRentingSystem = function(n, entries) {
};
/**
* @param {number} movie
* @return {number[]}
*/
MovieRentingSystem.prototype.search = function(movie) {
};
/**
* @param {number} shop
* @param {number} movie
* @return {void}
*/
MovieRentingSystem.prototype.rent = function(shop, movie) {
};
/**
* @param {number} shop
* @param {number} movie
* @return {void}
*/
MovieRentingSystem.prototype.drop = function(shop, movie) {
};
/**
* @return {number[][]}
*/
MovieRentingSystem.prototype.report = function() {
};
/**
* Your MovieRentingSystem object will be instantiated and called as such:
* var obj = new MovieRentingSystem(n, entries)
* var param_1 = obj.search(movie)
* obj.rent(shop,movie)
* obj.drop(shop,movie)
* var param_4 = obj.report()
*/ | You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array entries where entries[i] = [shopi, moviei, pricei] indicates that there is a copy of movie moviei at shop shopi with a rental price of pricei. Each shop carries at most one copy of a movie moviei.
The system should support the following functions:
Search: Finds the cheapest 5 shops that have an unrented copy of a given movie. The shops should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopi should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.
Rent: Rents an unrented copy of a given movie from a given shop.
Drop: Drops off a previously rented copy of a given movie at a given shop.
Report: Returns the cheapest 5 rented movies (possibly of the same movie ID) as a 2D list res where res[j] = [shopj, moviej] describes that the jth cheapest rented movie moviej was rented from the shop shopj. The movies in res should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopj should appear first, and if there is still tie, the one with the smaller moviej should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned.
Implement the MovieRentingSystem class:
MovieRentingSystem(int n, int[][] entries) Initializes the MovieRentingSystem object with n shops and the movies in entries.
List<Integer> search(int movie) Returns a list of shops that have an unrented copy of the given movie as described above.
void rent(int shop, int movie) Rents the given movie from the given shop.
void drop(int shop, int movie) Drops off a previously rented movie at the given shop.
List<List<Integer>> report() Returns a list of cheapest rented movies as described above.
Note: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie.
Example 1:
Input
["MovieRentingSystem", "search", "rent", "rent", "report", "drop", "search"]
[[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]]
Output
[null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]]
Explanation
MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]);
movieRentingSystem.search(1); // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.
movieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3].
movieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1].
movieRentingSystem.report(); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.
movieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2].
movieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.
Constraints:
1 <= n <= 3 * 105
1 <= entries.length <= 105
0 <= shopi < n
1 <= moviei, pricei <= 104
Each shop carries at most one copy of a movie moviei.
At most 105 calls in total will be made to search, rent, drop and report.
| Hard | [
"array",
"hash-table",
"design",
"heap-priority-queue",
"ordered-set"
] | null | [] |
1,913 | maximum-product-difference-between-two-pairs | [
"If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose?",
"We only need to worry about 4 numbers in the array."
] | /**
* @param {number[]} nums
* @return {number}
*/
var maxProductDifference = function(nums) {
}; | The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).
For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.
Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.
Return the maximum such product difference.
Example 1:
Input: nums = [5,6,2,7,4]
Output: 34
Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 * 7) - (2 * 4) = 34.
Example 2:
Input: nums = [4,2,5,9,7,4,8]
Output: 64
Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 * 8) - (2 * 4) = 64.
Constraints:
4 <= nums.length <= 104
1 <= nums[i] <= 104
| Easy | [
"array",
"sorting"
] | [
"const maxProductDifference = function(nums) {\n nums.sort((a, b) => a - b)\n const n = nums.length\n return nums[n - 1] * nums[n - 2] - nums[0] * nums[1]\n};"
] |
|
1,914 | cyclically-rotating-a-grid | [
"First, you need to consider each layer separately as an array.",
"Just cycle this array and then re-assign it."
] | /**
* @param {number[][]} grid
* @param {number} k
* @return {number[][]}
*/
var rotateGrid = function(grid, k) {
}; | You are given an m x n integer matrix grid, where m and n are both even integers, and an integer k.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:
Return the matrix after applying k cyclic rotations to it.
Example 1:
Input: grid = [[40,10],[30,20]], k = 1
Output: [[10,20],[40,30]]
Explanation: The figures above represent the grid at every state.
Example 2:
Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2
Output: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]
Explanation: The figures above represent the grid at every state.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 50
Both m and n are even integers.
1 <= grid[i][j] <= 5000
1 <= k <= 109
| Medium | [
"array",
"matrix",
"simulation"
] | [
"const rotateGrid = function(grid, k) {\n const m = grid.length, n = grid[0].length\n let top = 0, left = 0, right = n - 1, bottom = m - 1\n while(top < bottom && left < right) {\n const num = (right - left + 1) * 2 + (bottom - top + 1) * 2 - 4\n let rem = k % num\n while(rem) {\n const tmp = grid[top][left]\n // top\n for(let i = left; i < right; i++) {\n grid[top][i] = grid[top][i + 1]\n }\n // right\n for(let i = top; i < bottom; i++) {\n grid[i][right] = grid[i + 1][right]\n }\n // bottom\n for(let i = right; i > left; i--) {\n grid[bottom][i] = grid[bottom][i - 1]\n }\n // left\n for(let i = bottom; i > top; i--) {\n grid[i][left] = grid[i - 1][left]\n }\n grid[top + 1][left] = tmp\n rem--\n }\n left++\n top++\n right--\n bottom--\n }\n return grid\n};",
"var rotateGrid = function(grid, k) {\n var m = grid.length;\n var n = grid[0].length;\n\t\n\t // step1: loop each layer\n var layer = Math.min(n/2, m/2);\n for(l = 0; l<layer; l++) {\n\t // step2: flat layer \"l\" into one-dimension array\n var cur = [];\n // top\n for(var j = l; j<n-l; j++)\n {\n cur.push(grid[l][j]);\n }\n // right\n for(var i = l+1; i<m-l; i++)\n {\n cur.push(grid[i][n-l-1]);\n }\n // bottom\n for(var j = n-l-2; j>=l; j--)\n {\n cur.push(grid[m-l-1][j]);\n }\n // left\n for(var i = m-l-2; i>l; i--)\n {\n cur.push(grid[i][l]);\n }\n\t\t\n // step3: rotation (k%len) on one-dimension array\n var d = cur.length;\n var offset = k % d;\n cur = [...cur.slice(offset, d), ...cur.slice(0, offset)];\n\t\t\n // step4: refill rotated array back to 2D array at current layer\n var index = 0;\n // top\n for(var j = l; j<n-l; j++)\n {\n grid[l][j] = cur[index++];\n }\n // right\n for(var i = l+1; i<m-l; i++)\n {\n grid[i][n-l-1] = cur[index++];\n }\n // bottom\n for(var j = n-l-2; j>=l; j--)\n {\n grid[m-l-1][j] = cur[index++];\n }\n // left\n for(var i = m-l-2; i>l; i--)\n { \n grid[i][l] = cur[index++];\n }\n }\n return grid;\n};"
] |
|
1,915 | number-of-wonderful-substrings | [
"For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask.",
"Find the other prefixes whose masks differs from the current prefix mask by at most one bit."
] | /**
* @param {string} word
* @return {number}
*/
var wonderfulSubstrings = function(word) {
}; | A wonderful string is a string where at most one letter appears an odd number of times.
For example, "ccjjc" and "abab" are wonderful, but "ab" is not.
Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: word = "aba"
Output: 4
Explanation: The four wonderful substrings are underlined below:
- "aba" -> "a"
- "aba" -> "b"
- "aba" -> "a"
- "aba" -> "aba"
Example 2:
Input: word = "aabb"
Output: 9
Explanation: The nine wonderful substrings are underlined below:
- "aabb" -> "a"
- "aabb" -> "aa"
- "aabb" -> "aab"
- "aabb" -> "aabb"
- "aabb" -> "a"
- "aabb" -> "abb"
- "aabb" -> "b"
- "aabb" -> "bb"
- "aabb" -> "b"
Example 3:
Input: word = "he"
Output: 2
Explanation: The two wonderful substrings are underlined below:
- "he" -> "h"
- "he" -> "e"
Constraints:
1 <= word.length <= 105
word consists of lowercase English letters from 'a' to 'j'.
| Medium | [
"hash-table",
"string",
"bit-manipulation",
"prefix-sum"
] | [
"const wonderfulSubstrings = (word) => {\n let res = 0, count = Array(1024).fill(0);\n let cur = 0;\n count[0] = 1;\n for (let i = 0; i < word.length; ++i) {\n const num = word[i].charCodeAt() - 97;\n cur ^= 1 << (num);\n res += count[cur];\n ++count[cur];\n \n for (let j = 0; j < 10; ++j) {\n res += count[cur ^ (1 << j)];\n }\n }\n \n return res;\n};",
"const asi = (c) => c.charCodeAt();\nconst wonderfulSubstrings = (s) => {\n let res = 0;\n let f = Array(2 ** 10).fill(0);\n f[0] = 1; // count array\n let cur = res = 0;\n for (const c of s) {\n cur ^= 1 << asi(c) - 97; // get Hash (the set bit for a character.), update prefix parity\n res += f[cur];\n for (let i = 0; i < 10; i++) { // a ~ j\n res += f[cur ^ 1 << i]; // 1 << i get Hash\n }\n f[cur]++;\n }\n return res;\n};"
] |
|
1,916 | count-ways-to-build-rooms-in-an-ant-colony | [
"Use dynamic programming.",
"Let dp[i] be the number of ways to solve the problem for the subtree of node i.",
"Imagine you are trying to fill an array with the order of traversal, dp[i] equals the multiplications of the number of ways to distribute the subtrees of the children of i on the array using combinatorics, multiplied bu their dp values."
] | /**
* @param {number[]} prevRoom
* @return {number}
*/
var waysToBuildRooms = function(prevRoom) {
}; | You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly. Room 0 is already built, so prevRoom[0] = -1. The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0.
You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected. You can choose to build any room as long as its previous room is already built.
Return the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo 109 + 7.
Example 1:
Input: prevRoom = [-1,0,1]
Output: 1
Explanation: There is only one way to build the additional rooms: 0 → 1 → 2
Example 2:
Input: prevRoom = [-1,0,0,1,2]
Output: 6
Explanation:
The 6 ways are:
0 → 1 → 3 → 2 → 4
0 → 2 → 4 → 1 → 3
0 → 1 → 2 → 3 → 4
0 → 1 → 2 → 4 → 3
0 → 2 → 1 → 3 → 4
0 → 2 → 1 → 4 → 3
Constraints:
n == prevRoom.length
2 <= n <= 105
prevRoom[0] == -1
0 <= prevRoom[i] < n for all 1 <= i < n
Every room is reachable from room 0 once all the rooms are built.
| Hard | [
"math",
"dynamic-programming",
"tree",
"graph",
"topological-sort",
"combinatorics"
] | [
"const waysToBuildRooms = function (prevRoom) {\n return brute(prevRoom);\n};\nfunction brute(prevRoom) {\n const power = function (a, b, n) {\n a = a % n;\n let result = 1n;\n let x = a;\n while (b > 0) {\n let leastSignificantBit = b % 2n;\n b = b / 2n;\n if (leastSignificantBit == 1n) {\n result = result * x;\n result = result % n;\n }\n x = x * x;\n x = x % n;\n }\n return result;\n };\n const modInverse = function (aa, mm) {\n return power(BigInt(aa), BigInt(mm - 2), BigInt(mm));\n };\n const mod = Math.pow(10, 9) + 7;\n let nodes = {};\n for (let i = 0; i < prevRoom.length; i++) {\n nodes[i] = { val: i, edges: {} };\n }\n for (let i = 1; i < prevRoom.length; i++) {\n nodes[prevRoom[i]].edges[i] = true;\n }\n let memo = {};\n const numNodes = function (root) {\n var key = root.val;\n if (memo[key] !== undefined) {\n return memo[key];\n }\n var res = 1;\n for (var x in root.edges) {\n res += numNodes(nodes[x]);\n }\n memo[key] = res;\n return res;\n };\n let den = 1;\n for (let x in nodes) {\n let size = numNodes(nodes[x]);\n den = (den * size) % mod;\n }\n let numerator = 1;\n for (let i = 1; i < prevRoom.length; i++) {\n numerator = (numerator * (i + 1)) % mod;\n }\n let denInverse = modInverse(den, mod);\n return (BigInt(numerator) * denInverse) % BigInt(mod);\n}"
] |
|
1,920 | build-array-from-permutation | [
"Just apply what's said in the statement.",
"Notice that you can't apply it on the same array directly since some elements will change after application"
] | /**
* @param {number[]} nums
* @return {number[]}
*/
var buildArray = function(nums) {
}; | Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.
A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).
Example 1:
Input: nums = [0,2,1,5,3,4]
Output: [0,1,2,4,5,3]
Explanation: The array ans is built as follows:
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
= [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]
= [0,1,2,4,5,3]
Example 2:
Input: nums = [5,0,1,2,3,4]
Output: [4,5,0,1,2,3]
Explanation: The array ans is built as follows:
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
= [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]
= [4,5,0,1,2,3]
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] < nums.length
The elements in nums are distinct.
Follow-up: Can you solve it without using an extra space (i.e., O(1) memory)?
| Easy | [
"array",
"simulation"
] | [
"const buildArray = function(nums) {\n const res = []\n for(let i = 0, n = nums.length; i < n; i++) {\n res[i] = nums[nums[i]]\n }\n return res\n};"
] |
|
1,921 | eliminate-maximum-number-of-monsters | [
"Find the amount of time it takes each monster to arrive.",
"Find the order in which the monsters will arrive."
] | /**
* @param {number[]} dist
* @param {number[]} speed
* @return {number}
*/
var eliminateMaximum = function(dist, speed) {
}; | You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city.
The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute.
You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start.
You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon.
Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.
Example 1:
Input: dist = [1,3,4], speed = [1,1,1]
Output: 3
Explanation:
In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.
After a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.
After a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster.
All 3 monsters can be eliminated.
Example 2:
Input: dist = [1,1,2,3], speed = [1,1,1,1]
Output: 1
Explanation:
In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.
After a minute, the distances of the monsters are [X,0,1,2], so you lose.
You can only eliminate 1 monster.
Example 3:
Input: dist = [3,2,4], speed = [5,3,2]
Output: 1
Explanation:
In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.
After a minute, the distances of the monsters are [X,0,2], so you lose.
You can only eliminate 1 monster.
Constraints:
n == dist.length == speed.length
1 <= n <= 105
1 <= dist[i], speed[i] <= 105
| Medium | [
"array",
"greedy",
"sorting"
] | [
"const eliminateMaximum = function(dist, speed) {\n const pq = new PriorityQueue((a, b) => a[0] / a[1] < b[0] / b[1])\n const n = dist.length\n for(let i = 0; i < n; i++) {\n pq.push([dist[i], speed[i]])\n }\n let res = 0\n while(true) {\n if(pq.isEmpty()) break\n if(pq.peek()[0] < 0) break\n const tmp = pq.pop()\n if(tmp[0] <= res * tmp[1]) break\n res++\n }\n \n return res\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}"
] |
|
1,922 | count-good-numbers | [
"Is there a formula we can use to find the count of all the good numbers?",
"Exponentiation can be done very fast if we looked at the binary bits of n."
] | /**
* @param {number} n
* @return {number}
*/
var countGoodNumbers = function(n) {
}; | A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7).
For example, "2582" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 is at an even index but is not even.
Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7.
A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.
Example 1:
Input: n = 1
Output: 5
Explanation: The good numbers of length 1 are "0", "2", "4", "6", "8".
Example 2:
Input: n = 4
Output: 400
Example 3:
Input: n = 50
Output: 564908303
Constraints:
1 <= n <= 1015
| Medium | [
"math",
"recursion"
] | [
"const countGoodNumbers = function (n) {\n n = BigInt(n)\n const MOD = BigInt(10 ** 9 + 7)\n let res =\n quick_pow(5n, (n + 1n) / 2n ) * quick_pow(4n, n / 2n)\n res %= MOD\n return res\n\n function quick_pow(b, m) {\n let ans = 1n\n while (m) {\n if (m % 2n === 1n) ans = (ans * b) % MOD\n m = m / 2n\n b = (b * b) % MOD\n }\n return ans\n }\n}"
] |
|
1,923 | longest-common-subpath | [
"If there is a common path with length x, there is for sure a common path of length y where y < x.",
"We can use binary search over the answer with the range [0, min(path[i].length)].",
"Using binary search, we want to verify if we have a common path of length m. We can achieve this using hashing."
] | /**
* @param {number} n
* @param {number[][]} paths
* @return {number}
*/
var longestCommonSubpath = function(n, paths) {
}; | There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities.
There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively.
Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all.
A subpath of a path is a contiguous sequence of cities within that path.
Example 1:
Input: n = 5, paths = [[0,1,2,3,4],
[2,3,4],
[4,0,1,2,3]]
Output: 2
Explanation: The longest common subpath is [2,3].
Example 2:
Input: n = 3, paths = [[0],[1],[2]]
Output: 0
Explanation: There is no common subpath shared by the three paths.
Example 3:
Input: n = 5, paths = [[0,1,2,3,4],
[4,3,2,1,0]]
Output: 1
Explanation: The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.
Constraints:
1 <= n <= 105
m == paths.length
2 <= m <= 105
sum(paths[i].length) <= 105
0 <= paths[i][j] < n
The same city is not listed multiple times consecutively in paths[i].
| Hard | [
"array",
"binary-search",
"rolling-hash",
"suffix-array",
"hash-function"
] | [
"const longestCommonSubpath = function(n, paths) {\n if (!paths.length) return 0\n let arr = paths[0]\n for (const path of paths) if (path.length < arr.length) arr = path\n return new Sam(arr).longestCommonSubpath(paths) \n};\n\nclass State {\n constructor(len, link, next) {\n this.len = len\n this.link = link\n this.next = new Map(next)\n this.ans = len\n this.revLink = []\n this.max = 0\n }\n}\n\n\nfunction dfs(p) {\n let hasNext = false\n for (const q of p.revLink) {\n hasNext = dfs(q) || hasNext\n }\n if (hasNext) p.max = p.len\n return p.max > 0\n}\n\nclass Sam {\n newState(len, link, next) {\n const state = new State(len, link, next)\n this.container.push(state)\n return state\n }\n\n constructor(path) {\n this.container = []\n const root = this.newState(0, null)\n let last = root\n for (const x of path) {\n const cur = this.newState(last.len + 1, root)\n for (let p = last; p; p = p.link) {\n const q = p.next.get(x)\n if (!q) {\n p.next.set(x, cur)\n continue\n }\n if (q.len === p.len + 1) {\n cur.link = q\n } else {\n const clone = this.newState(p.len + 1, q.link, q.next)\n for (; p && p.next.get(x) === q; p = p.link) p.next.set(x, clone)\n cur.link = q.link = clone\n }\n break\n }\n last = cur\n }\n for (const state of this.container)\n if (state.link) state.link.revLink.push(state)\n }\n\n visit(path) {\n for (const state of this.container) state.max = 0\n const root = this.container[0]\n let p = root\n let len = 0\n for (const x of path) {\n for (; ; p = p.link, len = p.len) {\n const q = p.next.get(x)\n if (q) {\n p = q\n p.max = Math.max(p.max, ++len)\n break\n }\n if (!p.link) break\n }\n }\n dfs(root)\n for (const state of this.container)\n state.ans = Math.min(state.ans, state.max)\n }\n\n longestCommonSubpath(paths) {\n for (const path of paths) this.visit(path)\n let ans = 0\n for (const state of this.container) ans = Math.max(ans, state.ans)\n return ans\n }\n}"
] |
|
1,925 | count-square-sum-triples | [
"Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n",
"You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt"
] | /**
* @param {number} n
* @return {number}
*/
var countTriples = function(n) {
}; | A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.
Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.
Example 1:
Input: n = 5
Output: 2
Explanation: The square triples are (3,4,5) and (4,3,5).
Example 2:
Input: n = 10
Output: 4
Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).
Constraints:
1 <= n <= 250
| Easy | [
"math",
"enumeration"
] | [
"const countTriples = function(n) {\n let res = 0\n const hash = {}\n for(let i = 1; i<= n; i++) {\n hash[i * i] = 1\n }\n \n for(let i = 1; i <= n; i++) {\n for(let j = i; i * i + j * j <= n * n; j++) {\n res += (hash[i * i + j * j] || 0) * 2\n }\n }\n\n return res\n};"
] |
|
1,926 | nearest-exit-from-entrance-in-maze | [
"Which type of traversal lets you find the distance from a point?",
"Try using a Breadth First Search."
] | /**
* @param {character[][]} maze
* @param {number[]} entrance
* @return {number}
*/
var nearestExit = function(maze, entrance) {
}; | You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.
Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.
Example 1:
Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
Output: 1
Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].
Initially, you are at the entrance cell [1,2].
- You can reach [1,0] by moving 2 steps left.
- You can reach [0,2] by moving 1 step up.
It is impossible to reach [2,3] from the entrance.
Thus, the nearest exit is [0,2], which is 1 step away.
Example 2:
Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
Output: 2
Explanation: There is 1 exit in this maze at [1,2].
[1,0] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell [1,0].
- You can reach [1,2] by moving 2 steps right.
Thus, the nearest exit is [1,2], which is 2 steps away.
Example 3:
Input: maze = [[".","+"]], entrance = [0,0]
Output: -1
Explanation: There are no exits in this maze.
Constraints:
maze.length == m
maze[i].length == n
1 <= m, n <= 100
maze[i][j] is either '.' or '+'.
entrance.length == 2
0 <= entrancerow < m
0 <= entrancecol < n
entrance will always be an empty cell.
| Medium | [
"array",
"breadth-first-search",
"matrix"
] | null | [] |
1,927 | sum-game | [
"Bob can always make the total sum of both sides equal in mod 9.",
"Why does the difference between the number of question marks on the left and right side matter?"
] | /**
* @param {string} num
* @return {boolean}
*/
var sumGame = function(num) {
}; | Alice and Bob take turns playing a game, with Alice starting first.
You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num:
Choose an index i where num[i] == '?'.
Replace num[i] with any digit between '0' and '9'.
The game ends when there are no more '?' characters in num.
For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal.
For example, if the game ended with num = "243801", then Bob wins because 2+4+3 = 8+0+1. If the game ended with num = "243803", then Alice wins because 2+4+3 != 8+0+3.
Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.
Example 1:
Input: num = "5023"
Output: false
Explanation: There are no moves to be made.
The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.
Example 2:
Input: num = "25??"
Output: true
Explanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.
Example 3:
Input: num = "?3295???"
Output: false
Explanation: It can be proven that Bob will always win. One possible outcome is:
- Alice replaces the first '?' with '9'. num = "93295???".
- Bob replaces one of the '?' in the right half with '9'. num = "932959??".
- Alice replaces one of the '?' in the right half with '2'. num = "9329592?".
- Bob replaces the last '?' in the right half with '7'. num = "93295927".
Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.
Constraints:
2 <= num.length <= 105
num.length is even.
num consists of only digits and '?'.
| Medium | [
"math",
"greedy",
"game-theory"
] | null | [] |
1,928 | minimum-cost-to-reach-destination-in-time | [
"Consider a new graph where each node is one of the old nodes at a specific time. For example, node 0 at time 5.",
"You need to find the shortest path in the new graph."
] | /**
* @param {number} maxTime
* @param {number[][]} edges
* @param {number[]} passingFees
* @return {number}
*/
var minCost = function(maxTime, edges, passingFees) {
}; | There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself.
Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j.
In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities).
Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes.
Example 1:
Input: maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
Output: 11
Explanation: The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.
Example 2:
Input: maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
Output: 48
Explanation: The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.
You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.
Example 3:
Input: maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
Output: -1
Explanation: There is no way to reach city 5 from city 0 within 25 minutes.
Constraints:
1 <= maxTime <= 1000
n == passingFees.length
2 <= n <= 1000
n - 1 <= edges.length <= 1000
0 <= xi, yi <= n - 1
1 <= timei <= 1000
1 <= passingFees[j] <= 1000
The graph may contain multiple edges between two nodes.
The graph does not contain self loops.
| Hard | [
"dynamic-programming",
"graph"
] | [
"const minCost = function(maxTime, edges, passingFees) {\n const n = passingFees.length\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n const graph = {}\n for(let [s, e, t] of edges) {\n if(graph[s] == null) graph[s] = []\n if(graph[e] == null) graph[e] = []\n graph[s].push([e, t])\n graph[e].push([s, t])\n }\n \n const times = {}\n \n pq.push([passingFees[0], 0, 0])\n while(!pq.isEmpty()) {\n const [cost, node, time] = pq.pop()\n \n if(time > maxTime) continue\n if(node === n - 1) return cost\n \n if(times[node] == null || times[node] > time) {\n times[node] = time\n for(let [nxt, ext] of graph[node]) {\n pq.push([cost + passingFees[nxt], nxt, time + ext])\n }\n }\n \n }\n \n return -1\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}"
] |
|
1,929 | concatenation-of-array | [
"Build an array of size 2 * n and assign num[i] to ans[i] and ans[i + n]"
] | /**
* @param {number[]} nums
* @return {number[]}
*/
var getConcatenation = function(nums) {
}; | Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
Specifically, ans is the concatenation of two nums arrays.
Return the array ans.
Example 1:
Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [1,2,1,1,2,1]
Example 2:
Input: nums = [1,3,2,1]
Output: [1,3,2,1,1,3,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
- ans = [1,3,2,1,1,3,2,1]
Constraints:
n == nums.length
1 <= n <= 1000
1 <= nums[i] <= 1000
| Easy | [
"array"
] | [
"const getConcatenation = function(nums) {\n return nums.concat(nums)\n};"
] |
|
1,930 | unique-length-3-palindromic-subsequences | [
"What is the maximum number of length-3 palindromic strings?",
"How can we keep track of the characters that appeared to the left of a given position?"
] | /**
* @param {string} s
* @return {number}
*/
var countPalindromicSubsequence = function(s) {
}; | Given a string s, return the number of unique palindromes of length three that are a subsequence of s.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.
A palindrome is a string that reads the same forwards and backwards.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a subsequence of "abcde".
Example 1:
Input: s = "aabca"
Output: 3
Explanation: The 3 palindromic subsequences of length 3 are:
- "aba" (subsequence of "aabca")
- "aaa" (subsequence of "aabca")
- "aca" (subsequence of "aabca")
Example 2:
Input: s = "adc"
Output: 0
Explanation: There are no palindromic subsequences of length 3 in "adc".
Example 3:
Input: s = "bbcbaba"
Output: 4
Explanation: The 4 palindromic subsequences of length 3 are:
- "bbb" (subsequence of "bbcbaba")
- "bcb" (subsequence of "bbcbaba")
- "bab" (subsequence of "bbcbaba")
- "aba" (subsequence of "bbcbaba")
Constraints:
3 <= s.length <= 105
s consists of only lowercase English letters.
| Medium | [
"hash-table",
"string",
"prefix-sum"
] | [
"const countPalindromicSubsequence = function(s) {\n const first = Array(26).fill(Infinity), last = Array(26).fill(0)\n let res = 0\n const n = s.length, a = 'a'.charCodeAt(0)\n for(let i = 0; i < n; i++) {\n const code = s[i].charCodeAt(0)\n first[code - a] = Math.min(i, first[code - a])\n last[code - a] = i\n }\n\n for(let i = 0; i < 26; i++) {\n if(last[i] - 1 > first[i]) {\n const tmp = s.slice(first[i] + 1, last[i])\n const set = new Set()\n for(let ch of tmp) set.add(ch)\n res += set.size\n }\n }\n\n return res\n};",
"const countPalindromicSubsequence = (s) => {\n let res = 0;\n for (let i = 0; i < 26; i++) {\n for (let j = 0; j < 26; j++) {\n let len = 0;\n for (const c of s) {\n if(len === 3) break\n if (len == 0) {\n if (c.charCodeAt() - 97 == i) len++; // first char\n } else if (len == 1) {\n if (c.charCodeAt() - 97 == j) len++; // second char\n } else if (len == 2) {\n if (c.charCodeAt() - 97 == i) len++; // third char\n }\n }\n if (len == 3) res++;\n }\n }\n return res;\n};"
] |
|
1,931 | painting-a-grid-with-three-different-colors | [
"Represent each colored column by a bitmask based on each cell color.",
"Use bitmasks DP with state (currentCell, prevColumn)."
] | /**
* @param {number} m
* @param {number} n
* @return {number}
*/
var colorTheGrid = function(m, n) {
}; | You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.
Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.
Example 1:
Input: m = 1, n = 1
Output: 3
Explanation: The three possible colorings are shown in the image above.
Example 2:
Input: m = 1, n = 2
Output: 6
Explanation: The six possible colorings are shown in the image above.
Example 3:
Input: m = 5, n = 5
Output: 580986
Constraints:
1 <= m <= 5
1 <= n <= 1000
| Hard | [
"dynamic-programming"
] | [
"const colorTheGrid = function(m, n) {\n // Get color of the `mask` at `pos`, 2 bit store 1 color\n function getColor(mask, pos) {\n return (mask >> (2 * pos)) & 3\n }\n // Set `color` to the `mask` at `pos`, 2 bit store 1 color\n function setColor(mask, pos, color) {\n return mask | (color << (2 * pos))\n }\n function dfs(r, curColMask, prevColMask, out) {\n // Filled full color for a row\n if(r === m) {\n out.push(curColMask)\n return\n }\n // Try colors i in [1=RED, 2=GREEN, 3=BLUE]\n for(let i = 1; i <= 3; i++) {\n if(getColor(prevColMask, r) !== i && (r === 0 || getColor(curColMask, r - 1) !== i)) {\n dfs(r + 1, setColor(curColMask, r, i), prevColMask, out)\n }\n }\n }\n // Generate all possible columns we can draw, if the previous col is `prevColMask`\n function neighbor(prevColMask) {\n let out = []\n dfs(0, 0, prevColMask, out)\n return out\n }\n const mod = 10 ** 9 + 7\n const memo = {}\n function dp(c, prevColMask) {\n // Found a valid way\n if(c === n) return 1\n if(memo[`${c},${prevColMask}`] != null) return memo[`${c},${prevColMask}`]\n let res = 0\n const arr = neighbor(prevColMask)\n for(let e of arr) {\n res = (res + dp(c + 1, e)) % mod\n }\n memo[`${c},${prevColMask}`] = res\n return res\n }\n \n return dp(0, 0)\n \n};",
"const colorTheGrid = function(m, n) {\n const mod = 10 ** 9 + 7\n const colors = [1, 2, 3]\n const memoDp = {}, memoOpts = {}\n function getColor(pos, preMask) {\n return (preMask >> (pos * 2)) & 3\n }\n function setColor(pos, color, curMask) {\n return curMask | (color << (pos * 2))\n }\n function dfs(pos, curMask, preMask, res) {\n if(pos === m) {\n res.push(curMask)\n return\n }\n for(let c of colors) {\n if(getColor(pos, preMask) !== c && (pos === 0 || getColor(pos - 1, curMask) !== c)) {\n dfs(pos + 1, setColor(pos, c, curMask), preMask, res)\n }\n }\n }\n function curOpts(preMask) {\n if (memoOpts[preMask]) return memoOpts[preMask]\n const res = []\n dfs(0, 0, preMask, res)\n memoOpts[preMask] = res\n return res\n }\n function dp(col, preMask) {\n const k = `${col},${preMask}`\n if(col === n) return 1\n if(memoDp[k]) return memoDp[k]\n let res = 0\n const cur = curOpts(preMask)\n for(let mask of cur) {\n res = (res + dp(col + 1, mask)) % mod\n }\n memoDp[k] = res\n return res\n }\n\n return dp(0, 0)\n};",
"const colorTheGrid = function(m, n) {\n const mod = 1e9 + 7\n const limit = 1 << (2 * m)\n const memo = Array.from({ length: n }, () => Array(limit))\n \n return dp(0, 0)\n \n function dp(col, preColMask) {\n if(col === n) return 1\n let res = 0\n \n if(memo[col][preColMask] != null) return memo[col][preColMask]\n const curColMasks = []\n dfs(preColMask, 0, 0, curColMasks)\n for(const colMask of curColMasks) {\n res = (res + dp(col + 1, colMask)) % mod\n }\n return memo[col][preColMask] = res\n }\n \n function dfs(preColMask, curColMask, row, res) {\n if(row === m) {\n res.push(curColMask)\n return\n }\n for(let i = 1; i <= 3; i++) {\n if(getColor(preColMask, row) !== i && (row === 0 || getColor(curColMask, row - 1) !== i)) {\n dfs(preColMask, setColor(curColMask, row, i) ,row + 1, res)\n }\n }\n }\n \n function getColor(mask, row) {\n return (mask >> (2 * row)) & 3 \n }\n function setColor(mask, row, val) {\n return mask | (val << (2 * row)) \n }\n};"
] |
|
1,932 | merge-bsts-to-create-single-bst | [
"Is it possible to have multiple leaf nodes with the same values?",
"How many possible positions are there for each tree?",
"The root value of the final tree does not occur as a value in any of the leaves of the original tree."
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode[]} trees
* @return {TreeNode}
*/
var canMerge = function(trees) {
}; | You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can:
Select two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j].
Replace the leaf node in trees[i] with trees[j].
Remove trees[j] from trees.
Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST.
A BST (binary search tree) is a binary tree where each node satisfies the following property:
Every node in the node's left subtree has a value strictly less than the node's value.
Every node in the node's right subtree has a value strictly greater than the node's value.
A leaf is a node that has no children.
Example 1:
Input: trees = [[2,1],[3,2,5],[5,4]]
Output: [3,2,5,1,null,4]
Explanation:
In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].
Delete trees[0], so trees = [[3,2,5,1],[5,4]].
In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].
Delete trees[1], so trees = [[3,2,5,1,null,4]].
The resulting tree, shown above, is a valid BST, so return its root.
Example 2:
Input: trees = [[5,3,8],[3,2,6]]
Output: []
Explanation:
Pick i=0 and j=1 and merge trees[1] into trees[0].
Delete trees[1], so trees = [[5,3,8,2,6]].
The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.
Example 3:
Input: trees = [[5,4],[3]]
Output: []
Explanation: It is impossible to perform any operations.
Constraints:
n == trees.length
1 <= n <= 5 * 104
The number of nodes in each tree is in the range [1, 3].
Each node in the input may have children but no grandchildren.
No two roots of trees have the same value.
All the trees in the input are valid BSTs.
1 <= TreeNode.val <= 5 * 104.
| Hard | [
"hash-table",
"binary-search",
"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 canMerge = function (trees) {\n const mapRoots = {}\n const mapLeaves = {}\n let prev\n\n //check all trees and hashMap all available roots and leaves\n for (let node of trees) {\n mapRoots[node.val] = node\n if (node.left != null) {\n if (mapLeaves[node.left.val] != null)\n //different nodes can't refer to the same node -> abnormal BST\n return null\n mapLeaves[node.left.val] = node.left\n }\n if (node.right != null) {\n if (mapLeaves[node.right.val] != null)\n //different nodes can't refer to the same node -> abnormal BST\n return null\n mapLeaves[node.right.val] = node.right\n }\n }\n\n let rootRes = null\n let count = trees.length\n\n //find potential root-result of the merged entire tree\n //that is node without any references from the parent leaf nodes\n for (let node of trees) {\n if (mapLeaves[node.val] == null) {\n rootRes = node\n break\n }\n }\n\n //if there are no nodes like that -> abnormal BST\n if (rootRes == null) return rootRes\n\n const q = []\n\n //put root-result leaves into queue\n if (rootRes.left != null) q.push(rootRes.left)\n if (rootRes.right != null) q.push(rootRes.right)\n count--\n\n while (q.length) {\n //get leaf from the queue and check if there is correponding available root\n let leaf = q.pop()\n let root = mapRoots[leaf.val]\n if (root != null) {\n //there is root matched to leaf, so let's merge it\n count--\n leaf.left = root.left\n leaf.right = root.right\n //add new leaves into the queue\n if (root.left != null) q.push(root.left)\n if (root.right != null) q.push(root.right)\n }\n }\n\n prev = 0\n //if we have merged all inputed trees and that is valid BST by values, then return rootRes\n return count == 0 && recSanity(rootRes) ? rootRes : null\n\n function recSanity(node) {\n if (node == null) return true\n\n if (!recSanity(node.left)) return false\n\n if (prev >= node.val) return false\n prev = node.val\n\n return recSanity(node.right)\n }\n}"
] |
1,935 | maximum-number-of-words-you-can-type | [
"Check each word separately if it can be typed.",
"A word can be typed if all its letters are not broken."
] | /**
* @param {string} text
* @param {string} brokenLetters
* @return {number}
*/
var canBeTypedWords = function(text, brokenLetters) {
}; | There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard.
Example 1:
Input: text = "hello world", brokenLetters = "ad"
Output: 1
Explanation: We cannot type "world" because the 'd' key is broken.
Example 2:
Input: text = "leet code", brokenLetters = "lt"
Output: 1
Explanation: We cannot type "leet" because the 'l' and 't' keys are broken.
Example 3:
Input: text = "leet code", brokenLetters = "e"
Output: 0
Explanation: We cannot type either word because the 'e' key is broken.
Constraints:
1 <= text.length <= 104
0 <= brokenLetters.length <= 26
text consists of words separated by a single space without any leading or trailing spaces.
Each word only consists of lowercase English letters.
brokenLetters consists of distinct lowercase English letters.
| Easy | [
"hash-table",
"string"
] | [
"const canBeTypedWords = function(text, brokenLetters) {\n const set = new Set(brokenLetters.split(''))\n const arr = text.split(' ')\n let res = 0\n for(let e of arr) {\n let ok = true\n for(let c of e) {\n if(set.has(c)) {\n ok = false\n break\n }\n }\n if(ok) res++\n }\n \n return res\n};"
] |
|
1,936 | add-minimum-number-of-rungs | [
"Go as far as you can on the available rungs before adding new rungs.",
"If you have to add a new rung, add it as high up as possible.",
"Try using division to decrease the number of computations."
] | /**
* @param {number[]} rungs
* @param {number} dist
* @return {number}
*/
var addRungs = function(rungs, dist) {
}; | You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung.
You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there.
Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.
Example 1:
Input: rungs = [1,3,5,10], dist = 2
Output: 2
Explanation:
You currently cannot reach the last rung.
Add rungs at heights 7 and 8 to climb this ladder.
The ladder will now have rungs at [1,3,5,7,8,10].
Example 2:
Input: rungs = [3,6,8,10], dist = 3
Output: 0
Explanation:
This ladder can be climbed without adding additional rungs.
Example 3:
Input: rungs = [3,4,6,7], dist = 2
Output: 1
Explanation:
You currently cannot reach the first rung from the ground.
Add a rung at height 1 to climb this ladder.
The ladder will now have rungs at [1,3,4,6,7].
Constraints:
1 <= rungs.length <= 105
1 <= rungs[i] <= 109
1 <= dist <= 109
rungs is strictly increasing.
| Medium | [
"array",
"greedy"
] | [
"const addRungs = function(rungs, dist) {\n let res = 0\n let pre = 0\n const { floor, ceil } = Math\n for(let r of rungs) {\n if(r - pre > dist) {\n // console.log(r, pre)\n res += ceil((r - pre) / dist) - 1\n }\n pre = r\n }\n return res\n};"
] |
|
1,937 | maximum-number-of-points-with-cost | [
"Try using dynamic programming.",
"dp[i][j] is the maximum number of points you can have if points[i][j] is the most recent cell you picked."
] | /**
* @param {number[][]} points
* @return {number}
*/
var maxPoints = function(points) {
}; | You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.
To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.
Return the maximum number of points you can achieve.
abs(x) is defined as:
x for x >= 0.
-x for x < 0.
Example 1:
Input: points = [[1,2,3],[1,5,1],[3,1,1]]
Output: 9
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
You add 3 + 5 + 3 = 11 to your score.
However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
Your final score is 11 - 2 = 9.
Example 2:
Input: points = [[1,5],[2,3],[4,2]]
Output: 11
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
You add 5 + 3 + 4 = 12 to your score.
However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
Your final score is 12 - 1 = 11.
Constraints:
m == points.length
n == points[r].length
1 <= m, n <= 105
1 <= m * n <= 105
0 <= points[r][c] <= 105
| Medium | [
"array",
"dynamic-programming"
] | [
"const maxPoints = function(points) {\n const m = points.length, n = points[0].length\n let prev = points[0].slice()\n for(let i = 1; i < m; i++) {\n const left = []\n left[0] = prev[0]\n // left to right\n for(let j = 1; j < n; j++) {\n left[j] = Math.max(prev[j], left[j - 1] - 1)\n }\n const right = []\n right[n - 1] = prev[n - 1]\n // right to left\n for(let j = n - 2; j >= 0; j--) {\n right[j] = Math.max(prev[j], right[j + 1] - 1)\n }\n\n const cur = []\n for(let j = 0; j < n; j++) {\n cur[j] = Math.max(left[j], right[j]) + points[i][j]\n }\n prev = cur\n }\n\n return Math.max(...prev)\n};",
"const maxPoints = function(points) {\n let m = points.length, n = points[0].length;\n let result = 0;\n // dp\n const dp = Array.from({ length: m }, () => Array(n).fill(0));\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (i == 0) {\n dp[i][j] = points[i][j];\n } else {\n dp[i][j] = Math.max(points[i][j] + dp[i - 1][j], dp[i][j]);\n }\n }\n for (let j = 0; j < n; j++) {\n // right\n for (let k = 1; k < n - j; k++) {\n if (dp[i][j + k] >= dp[i][j] - k) {\n break;\n }\n dp[i][j + k] = dp[i][j] - k;\n }\n for (let k = 1; k <= j; k++) {\n if (dp[i][j - k] >= dp[i][j] - k) {\n break;\n }\n dp[i][j - k] = dp[i][j] - k;\n }\n }\n }\n for (let j = 0; j < n; j++) {\n result = Math.max(result, dp[m - 1][j]);\n }\n return result;\n};"
] |
|
1,938 | maximum-genetic-difference-query | [
"How can we use a trie to store all the XOR values in the path from a node to the root?",
"How can we dynamically add the XOR values with a DFS search?"
] | /**
* @param {number[]} parents
* @param {number[][]} queries
* @return {number[]}
*/
var maxGeneticDifference = function(parents, queries) {
}; | There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes its unique genetic value (i.e. the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1.
You are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi.
Return an array ans where ans[i] is the answer to the ith query.
Example 1:
Input: parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]
Output: [2,3,7]
Explanation: The queries are processed as follows:
- [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.
- [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.
- [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.
Example 2:
Input: parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]
Output: [6,14,7]
Explanation: The queries are processed as follows:
- [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.
- [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.
- [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.
Constraints:
2 <= parents.length <= 105
0 <= parents[i] <= parents.length - 1 for every node i that is not the root.
parents[root] == -1
1 <= queries.length <= 3 * 104
0 <= nodei <= parents.length - 1
0 <= vali <= 2 * 105
| Hard | [
"array",
"bit-manipulation",
"trie"
] | [
"const maxGeneticDifference = function (parents, queries) {\n let pn = parents.length,\n qn = queries.length\n let root = parents.indexOf(-1)\n let children = initializeGraph(pn)\n for (let i = 0; i < pn; i++) {\n if (i != root) {\n children[parents[i]].push(i)\n }\n }\n let freq = Array(1 << 20).fill(0)\n let queriesByNode = initializeGraph(pn)\n for (let i = 0; i < qn; i++) {\n let query = queries[i]\n queriesByNode[query[0]].push(new Query(i, query[1]))\n }\n\n let res = Array(qn).fill(0)\n const dfs = (idx) => {\n let y = (1 << 19) + idx\n while (y > 0) {\n freq[y]++\n y >>= 1\n }\n for (const qnode of queriesByNode[idx]) {\n let j = qnode.index,\n x = qnode.val\n let cum = 0\n let bit = 1 << 18\n while (bit > 0) {\n let ii = (((1 << 19) ^ cum ^ x ^ bit) / bit) >> 0\n if (freq[ii] > 0) cum += bit\n bit >>= 1\n }\n res[j] = cum\n }\n for (const child of children[idx]) dfs(child)\n y = (1 << 19) + idx\n while (y > 0) {\n freq[y]--\n y >>= 1\n }\n }\n dfs(root)\n return res\n}\n\nconst initializeGraph = (n) => {\n let G = []\n for (let i = 0; i < n; i++) G.push([])\n return G\n}\n\nfunction Query(index, val) {\n this.index = index\n this.val = val\n}"
] |
|
1,941 | check-if-all-characters-have-equal-number-of-occurrences | [
"Build a dictionary containing the frequency of each character appearing in s",
"Check if all values in the dictionary are the same."
] | /**
* @param {string} s
* @return {boolean}
*/
var areOccurrencesEqual = function(s) {
}; | Given a string s, return true if s is a good string, or false otherwise.
A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).
Example 1:
Input: s = "abacbc"
Output: true
Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.
Example 2:
Input: s = "aaabb"
Output: false
Explanation: The characters that appear in s are 'a' and 'b'.
'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.
Constraints:
1 <= s.length <= 1000
s consists of lowercase English letters.
| Easy | [
"hash-table",
"string",
"counting"
] | [
"var areOccurrencesEqual = function(s) {\n const n = s.length\n const arr = Array(26).fill(0), a = 'a'.charCodeAt(0)\n for(const ch of s) {\n arr[ch.charCodeAt(0) - a]++\n }\n const set = new Set()\n for(const e of arr) {\n if(e !== 0) set.add(e)\n if(set.size > 1) return false\n }\n return true\n};"
] |
|
1,942 | the-number-of-the-smallest-unoccupied-chair | [
"Sort times by arrival time.",
"for each arrival_i find the smallest unoccupied chair and mark it as occupied until leaving_i."
] | /**
* @param {number[][]} times
* @param {number} targetFriend
* @return {number}
*/
var smallestChair = function(times, targetFriend) {
}; | There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number.
For example, if chairs 0, 1, and 5 are occupied when a friend comes, they will sit on chair number 2.
When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.
You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct.
Return the chair number that the friend numbered targetFriend will sit on.
Example 1:
Input: times = [[1,4],[2,3],[4,6]], targetFriend = 1
Output: 1
Explanation:
- Friend 0 arrives at time 1 and sits on chair 0.
- Friend 1 arrives at time 2 and sits on chair 1.
- Friend 1 leaves at time 3 and chair 1 becomes empty.
- Friend 0 leaves at time 4 and chair 0 becomes empty.
- Friend 2 arrives at time 4 and sits on chair 0.
Since friend 1 sat on chair 1, we return 1.
Example 2:
Input: times = [[3,10],[1,5],[2,6]], targetFriend = 0
Output: 2
Explanation:
- Friend 1 arrives at time 1 and sits on chair 0.
- Friend 2 arrives at time 2 and sits on chair 1.
- Friend 0 arrives at time 3 and sits on chair 2.
- Friend 1 leaves at time 5 and chair 0 becomes empty.
- Friend 2 leaves at time 6 and chair 1 becomes empty.
- Friend 0 leaves at time 10 and chair 2 becomes empty.
Since friend 0 sat on chair 2, we return 2.
Constraints:
n == times.length
2 <= n <= 104
times[i].length == 2
1 <= arrivali < leavingi <= 105
0 <= targetFriend <= n - 1
Each arrivali time is distinct.
| Medium | [
"array",
"heap-priority-queue",
"ordered-set"
] | [
"const smallestChair = function(times, targetFriend) {\n const avail = new PQ((a, b) => a[0] < b[0])\n const occupied = new PQ((a, b) => a[1] < b[1])\n const n = times.length\n for(let i = 0; i < n; i++) {\n avail.push([i, 0])\n }\n times.forEach((e, i) => e.push(i))\n times.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])\n \n for(let i = 0; i < n; i++) {\n let res = -1\n const [s, e, idx] = times[i]\n while(!occupied.isEmpty() && occupied.peek()[1] <= s) {\n avail.push(occupied.pop())\n }\n \n const c = avail.pop()\n res = c[0]\n c[1] = e\n occupied.push(c)\n \n if(idx === targetFriend) {\n return res\n }\n }\n};\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}",
"const smallestChair = function (times, targetFriend) {\n const targetArrival = times[targetFriend][0]\n let seatNum = 0\n let res = 0\n const n = times.length\n \n times.sort((a, b) => a[0] - b[0])\n \n const occupied = new PriorityQueue((a, b) => a[0] < b[0])\n const available = new PriorityQueue((a, b) => a < b)\n \n for(let i = 0; i < n; i++) {\n const [arrival, leaving] = times[i]\n while(!occupied.isEmpty() && occupied.peek()[0] <= arrival) {\n available.push(occupied.pop()[1]) \n }\n let seat\n if(!available.isEmpty()) {\n seat = available.pop()\n } else {\n seat = seatNum\n seatNum++\n }\n occupied.push([leaving, seat])\n if(arrival === targetArrival) {\n res = seat\n break\n }\n }\n \n return res\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}",
"var smallestChair = function (times, targetFriend) {\n const [targetArrival] = times[targetFriend]\n const arrivalQueue = times\n const leavingQueue = [...times]\n arrivalQueue.sort((a, b) => a[0] - b[0])\n leavingQueue.sort((a, b) => a[1] - b[1] || a[0] - b[0])\n const chairsByLeaveTime = new Map()\n let chairsCount = 0\n let arriving = 0,\n leaving = 0\n\n while (arriving < arrivalQueue.length) {\n let chairIdx\n const arrival = arrivalQueue[arriving][0]\n const leave = leavingQueue[leaving][1]\n if (arrival < leave) {\n chairIdx = chairsCount++\n } else {\n let freeChairIdx = leaving\n chairIdx = chairsByLeaveTime.get(leavingQueue[freeChairIdx++][0])\n while (arrival >= leavingQueue[freeChairIdx][1]) {\n const nextChair = chairsByLeaveTime.get(leavingQueue[freeChairIdx][0])\n if (chairIdx > nextChair) {\n ;[leavingQueue[leaving], leavingQueue[freeChairIdx]] = [\n leavingQueue[freeChairIdx],\n leavingQueue[leaving],\n ]\n chairIdx = nextChair\n }\n ++freeChairIdx\n }\n ++leaving\n }\n if (targetArrival === arrival) {\n return chairIdx\n }\n chairsByLeaveTime.set(arrival, chairIdx)\n arriving++\n }\n}"
] |
|
1,943 | describe-the-painting | [
"Can we sort the segments in a way to help solve the problem?",
"How can we dynamically keep track of the sum of the current segment(s)?"
] | /**
* @param {number[][]} segments
* @return {number[][]}
*/
var splitPainting = function(segments) {
}; | There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color.
The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors.
For example, if colors 2, 4, and 6 are mixed, then the resulting mixed color is {2,4,6}.
For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set.
You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj.
For example, the painting created with segments = [[1,4,5],[1,7,7]] can be described by painting = [[1,4,12],[4,7,7]] because:
[1,4) is colored {5,7} (with a sum of 12) from both the first and second segments.
[4,7) is colored {7} from only the second segment.
Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order.
A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.
Example 1:
Input: segments = [[1,4,5],[4,7,7],[1,7,9]]
Output: [[1,4,14],[4,7,16]]
Explanation: The painting can be described as follows:
- [1,4) is colored {5,9} (with a sum of 14) from the first and third segments.
- [4,7) is colored {7,9} (with a sum of 16) from the second and third segments.
Example 2:
Input: segments = [[1,7,9],[6,8,15],[8,10,7]]
Output: [[1,6,9],[6,7,24],[7,8,15],[8,10,7]]
Explanation: The painting can be described as follows:
- [1,6) is colored 9 from the first segment.
- [6,7) is colored {9,15} (with a sum of 24) from the first and second segments.
- [7,8) is colored 15 from the second segment.
- [8,10) is colored 7 from the third segment.
Example 3:
Input: segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]
Output: [[1,4,12],[4,7,12]]
Explanation: The painting can be described as follows:
- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.
- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.
Note that returning a single segment [1,7) is incorrect because the mixed color sets are different.
Constraints:
1 <= segments.length <= 2 * 104
segments[i].length == 3
1 <= starti < endi <= 105
1 <= colori <= 109
Each colori is distinct.
| Medium | [
"array",
"prefix-sum"
] | [
"const splitPainting = function(segments) {\n const hash = {}\n for(let [s, e, c] of segments) {\n if(hash[s] == null) hash[s] = 0\n if(hash[e] == null) hash[e] = 0\n hash[s] += c\n hash[e] -= c\n }\n const keys = Object.keys(hash)\n keys.sort((a, b) => a - b)\n let prev, color = 0\n const res = []\n for(let k of keys) {\n if(prev != null && color !== 0) res.push([prev,k,color])\n\n prev = k\n color += hash[k]\n } \n return res\n};",
"const splitPainting = function(segments) {\n const sum = {}\n for(const [s, e, v] of segments) {\n if(sum[s] == null) sum[s] = 0\n if(sum[e] == null) sum[e] = 0\n sum[s] += v\n sum[e] -= v\n }\n const keys = Object.keys(sum).map(e => +e)\n keys.sort((a, b) => a - b)\n const res = []\n let pre = 0, s = 0, n = keys.length\n for(let i = 0; i < n; i++) {\n const k = keys[i]\n \n if(s) {\n res.push([pre, k, s])\n }\n s += sum[k]\n pre = k\n }\n \n return res\n};"
] |
|
1,944 | number-of-visible-people-in-a-queue | [
"How to solve this problem in quadratic complexity ?",
"For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found.",
"Since the limits are high, you need a linear solution.",
"Use a stack to keep the values of the array sorted as you iterate the array from the end to the start.",
"Keep popping from the stack the elements in sorted order until a value larger than arr[i] is found, these are the ones that person i can see."
] | /**
* @param {number[]} heights
* @return {number[]}
*/
var canSeePersonsCount = function(heights) {
}; | There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person.
A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]).
Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.
Example 1:
Input: heights = [10,6,8,5,11,9]
Output: [3,1,2,1,1,0]
Explanation:
Person 0 can see person 1, 2, and 4.
Person 1 can see person 2.
Person 2 can see person 3 and 4.
Person 3 can see person 4.
Person 4 can see person 5.
Person 5 can see no one since nobody is to the right of them.
Example 2:
Input: heights = [5,1,2,3,10]
Output: [4,1,1,1,0]
Constraints:
n == heights.length
1 <= n <= 105
1 <= heights[i] <= 105
All the values of heights are unique.
| Hard | [
"array",
"stack",
"monotonic-stack"
] | [
"const canSeePersonsCount = function(heights) {\n const res = []\n if(heights.length === 0) return res\n \n const n = heights.length\n const stk = []\n for(let i = n - 1; i >= 0; i--) {\n let del = 0\n while(stk.length && heights[i] > heights[stk[stk.length - 1]]) {\n stk.pop()\n del++\n }\n res.push(del + (stk.length ? 1 : 0))\n stk.push(i)\n }\n \n return res.reverse()\n};",
"const canSeePersonsCount = function(heights) {\n const ans = new Uint32Array(heights.length);\n \n const stack = [];\n for (let i = heights.length - 1; i >= 0; i--) {\n const h = heights[i];\n \n let del = 0;\n while (stack.length && stack[stack.length - 1] <= h) {\n del++;\n stack.pop();\n }\n \n ans[i] = del + (stack.length ? 1 : 0);\n stack.push(h);\n }\n\n return ans;\n};",
"const canSeePersonsCount = function(heights) {\n const stack = [], n = heights.length, res = Array(n)\n for(let i = n - 1; i >= 0; i--) {\n const h = heights[i]\n let del = 0\n while(stack.length && stack[stack.length - 1] <= h) {\n stack.pop()\n del++\n }\n res[i] = stack.length ? del + 1 : del\n stack.push(h)\n }\n\n return res\n};"
] |
|
1,945 | sum-of-digits-of-string-after-convert | [
"First, let's note that after the first transform the value will be at most 100 * 9 which is not much",
"After The first transform, we can just do the rest of the transforms by brute force"
] | /**
* @param {string} s
* @param {number} k
* @return {number}
*/
var getLucky = function(s, k) {
}; | You are given a string s consisting of lowercase English letters, and an integer k.
First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total.
For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:
Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124
Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17
Transform #2: 17 ➝ 1 + 7 ➝ 8
Return the resulting integer after performing the operations described above.
Example 1:
Input: s = "iiii", k = 1
Output: 36
Explanation: The operations are as follows:
- Convert: "iiii" ➝ "(9)(9)(9)(9)" ➝ "9999" ➝ 9999
- Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36
Thus the resulting integer is 36.
Example 2:
Input: s = "leetcode", k = 2
Output: 6
Explanation: The operations are as follows:
- Convert: "leetcode" ➝ "(12)(5)(5)(20)(3)(15)(4)(5)" ➝ "12552031545" ➝ 12552031545
- Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33
- Transform #2: 33 ➝ 3 + 3 ➝ 6
Thus the resulting integer is 6.
Example 3:
Input: s = "zbax", k = 2
Output: 8
Constraints:
1 <= s.length <= 100
1 <= k <= 10
s consists of lowercase English letters.
| Easy | [
"string",
"simulation"
] | [
"const getLucky = function(s, k) {\n let res = 0\n const a = 'a'.charCodeAt(0)\n const arr = []\n for(let ch of s) {\n arr.push(ch.charCodeAt(0) - a + 1)\n }\n let str = arr.join('').split('').map(e => +e)\n let prev = str, sum = 0\n while(k > 0) {\n // let tmp = 0\n let tmp = prev.reduce((ac, e) => ac + e, 0)\n // console.log(tmp)\n prev = `${tmp}`.split('').map(e => +e)\n sum = tmp\n k--\n }\n \n return sum\n};"
] |
|
1,946 | largest-number-after-mutating-substring | [
"Should you change a digit if the new digit is smaller than the original?",
"If changing the first digit and the last digit both make the number bigger, but you can only change one of them; which one should you change?",
"Changing numbers closer to the front is always better"
] | /**
* @param {string} num
* @param {number[]} change
* @return {string}
*/
var maximumNumber = function(num, change) {
}; | You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d].
You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]).
Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num.
A substring is a contiguous sequence of characters within the string.
Example 1:
Input: num = "132", change = [9,8,5,0,3,6,4,2,6,8]
Output: "832"
Explanation: Replace the substring "1":
- 1 maps to change[1] = 8.
Thus, "132" becomes "832".
"832" is the largest number that can be created, so return it.
Example 2:
Input: num = "021", change = [9,4,3,5,7,2,1,9,0,6]
Output: "934"
Explanation: Replace the substring "021":
- 0 maps to change[0] = 9.
- 2 maps to change[2] = 3.
- 1 maps to change[1] = 4.
Thus, "021" becomes "934".
"934" is the largest number that can be created, so return it.
Example 3:
Input: num = "5", change = [1,4,7,5,3,2,5,6,9,4]
Output: "5"
Explanation: "5" is already the largest number that can be created, so return it.
Constraints:
1 <= num.length <= 105
num consists of only digits 0-9.
change.length == 10
0 <= change[d] <= 9
| Medium | [
"array",
"string",
"greedy"
] | [
"const maximumNumber = function(num, change) {\n let res = ''\n const arr = num.split('')\n let prev = false, cnt = 0\n for(let i = 0, n = num.length; i < n; i++) {\n const cur = +num[i]\n if(change[cur] > cur) {\n cnt++\n prev = true\n arr[i] = change[cur]\n }\n if(change[cur] < cur) {\n if(cnt <= 0) continue\n else break\n }\n }\n \n return arr.join('')\n};"
] |
|
1,947 | maximum-compatibility-score-sum | [
"Calculate the compatibility score for each student-mentor pair.",
"Try every permutation of students with the original mentors array."
] | /**
* @param {number[][]} students
* @param {number[][]} mentors
* @return {number}
*/
var maxCompatibilitySum = function(students, mentors) {
}; | There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes).
The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed).
Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor.
For example, if the student's answers were [1, 0, 1] and the mentor's answers were [0, 0, 1], then their compatibility score is 2 because only the second and the third answers are the same.
You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores.
Given students and mentors, return the maximum compatibility score sum that can be achieved.
Example 1:
Input: students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]
Output: 8
Explanation: We assign students to mentors in the following way:
- student 0 to mentor 2 with a compatibility score of 3.
- student 1 to mentor 0 with a compatibility score of 2.
- student 2 to mentor 1 with a compatibility score of 3.
The compatibility score sum is 3 + 2 + 3 = 8.
Example 2:
Input: students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]
Output: 0
Explanation: The compatibility score of any student-mentor pair is 0.
Constraints:
m == students.length == mentors.length
n == students[i].length == mentors[j].length
1 <= m, n <= 8
students[i][k] is either 0 or 1.
mentors[j][k] is either 0 or 1.
| Medium | [
"array",
"dynamic-programming",
"backtracking",
"bit-manipulation",
"bitmask"
] | [
"const maxCompatibilitySum = function(students, mentors) {\n const m = students.length, n = students[0].length\n const limit = 1 << m\n const dp = Array(limit).fill(0)\n for(let mask = 1; mask < limit; mask++) {\n for(let i = 0; i < m; i++) {\n if(mask & (1 << i)) {\n dp[mask] = Math.max(\n dp[mask],\n dp[mask ^ (1 << i)] + calc(bitCnt(mask) - 1, i)\n )\n }\n }\n }\n \n \n return dp[limit - 1]\n \n function bitCnt(num) {\n let res = 0\n while(num) {\n num = num & (num - 1)\n res++\n }\n \n return res\n }\n // student, mentor\n function calc(i, j) {\n let res = 0\n for(let k = 0; k < n; k++) {\n if(students[i][k] === mentors[j][k]) {\n res++\n }\n }\n \n return res\n }\n};",
"const maxCompatibilitySum = function(students, mentors) {\n const n = students.length, dp = Array(1 << n).fill(-Infinity)\n const m = students[0].length\n return dfs(0, 0)\n \n function dfs(i, mask) {\n if(i === n) return 0\n if(dp[mask] !== -Infinity) return dp[mask]\n for(let j = 0; j < n; j++) {\n if((mask & (1 << j)) === 0) {\n dp[mask] = Math.max(dp[mask], calc(i, j) + dfs(i + 1, mask | (1 << j)))\n }\n }\n \n return dp[mask]\n }\n \n function calc(i, j) {\n let res = 0\n const a = students[i], b = mentors[j]\n for(let k = 0; k < m; k++) {\n if(a[k] === b[k]) res++\n }\n return res\n }\n};",
"const maxCompatibilitySum = function(students, mentors) {\n const obj = { res: 0 }, hash = {}\n bt(students, mentors, 0, 0, obj, hash)\n\n return obj.res\n};\n\nfunction bt(stu, men, i, score, obj, hash) {\n\n if(i === stu.length) {\n if(score > obj.res) {\n obj.res = score\n }\n return\n }\n \n for(let j = 0; j < men.length; j++) {\n const k = `${j}`\n if(hash[k] === 1) continue\n hash[k] = 1\n bt(stu, men, i + 1, score + calc(stu[i], men[j]), obj, hash)\n delete hash[k]\n }\n}\n\nfunction calc(a1, a2) {\n const n = a1.length\n let res = 0\n for(let i = 0; i < n; i++) {\n if(a1[i] === a2[i]) res++\n }\n return res\n}"
] |
|
1,948 | delete-duplicate-folders-in-system | [
"Can we use a trie to build the folder structure?",
"Can we utilize hashing to hash the folder structures?"
] | /**
* @param {string[][]} paths
* @return {string[][]}
*/
var deleteDuplicateFolder = function(paths) {
}; | Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system.
For example, ["one", "two", "three"] represents the path "/one/two/three".
Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical, then mark the folders as well as all their subfolders.
For example, folders "/a" and "/b" in the file structure below are identical. They (as well as their subfolders) should all be marked:
/a
/a/x
/a/x/y
/a/z
/b
/b/x
/b/x/y
/b/z
However, if the file structure also included the path "/b/w", then the folders "/a" and "/b" would not be identical. Note that "/a/x" and "/b/x" would still be considered identical even with the added folder.
Once all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted.
Return the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order.
Example 1:
Input: paths = [["a"],["c"],["d"],["a","b"],["c","b"],["d","a"]]
Output: [["d"],["d","a"]]
Explanation: The file structure is as shown.
Folders "/a" and "/c" (and their subfolders) are marked for deletion because they both contain an empty
folder named "b".
Example 2:
Input: paths = [["a"],["c"],["a","b"],["c","b"],["a","b","x"],["a","b","x","y"],["w"],["w","y"]]
Output: [["c"],["c","b"],["a"],["a","b"]]
Explanation: The file structure is as shown.
Folders "/a/b/x" and "/w" (and their subfolders) are marked for deletion because they both contain an empty folder named "y".
Note that folders "/a" and "/c" are identical after the deletion, but they are not deleted because they were not marked beforehand.
Example 3:
Input: paths = [["a","b"],["c","d"],["c"],["a"]]
Output: [["c"],["c","d"],["a"],["a","b"]]
Explanation: All folders are unique in the file system.
Note that the returned array can be in a different order as the order does not matter.
Constraints:
1 <= paths.length <= 2 * 104
1 <= paths[i].length <= 500
1 <= paths[i][j].length <= 10
1 <= sum(paths[i][j].length) <= 2 * 105
path[i][j] consists of lowercase English letters.
No two paths lead to the same folder.
For any folder not at the root level, its parent folder will also be in the input.
| Hard | [
"array",
"hash-table",
"string",
"trie",
"hash-function"
] | [
"const deleteDuplicateFolder = function(paths) {\n const trie = new Trie()\n for (const path of paths) {\n let cur = trie.trie\n cur.countPrefix++\n for (const name of path) {\n if(cur.children[name] == null) cur.children[name] = new TrieNode(name)\n cur = cur.children[name]\n cur.countPrefix++\n }\n }\n const folders = new Map()\n dfs1(trie.trie)\n for (const value of folders.values()) {\n if (value.length > 1) {\n // found the same dir, mark as to be deleted\n for (const node of value) {\n node.countPrefix = 0\n }\n }\n }\n const ans = []\n // traverse un-deleted dir, put them to result\n dfs2(trie.trie, [])\n return ans\n function dfs1 (node) {\n if (Object.keys(node.children).length === 0) {\n return `(${node.char})`\n }\n const childrenExp = []\n for (const key in node.children) {\n childrenExp.push(dfs1(node.children[key]))\n }\n const exp = childrenExp.sort((a, b) => a.localeCompare(b)).join('')\n if (!folders.has(exp)) {\n folders.set(exp, [])\n }\n folders.get(exp).push(node)\n return `(${node.char}${childrenExp.join('')})`\n }\n function dfs2 (node, path) {\n // already deleted, no need go further\n if (node.countPrefix === 0) {\n return\n }\n if (node.char !== '/') { path.push(node.char) }\n if (path.length) ans.push([...path])\n for (const key in node.children) {\n dfs2(node.children[key], path)\n }\n path.pop()\n } \n};\nclass TrieNode {\n constructor (char) {\n this.char = char\n this.count = 0\n this.countPrefix = 0\n this.children = {}\n }\n};\nclass Trie {\n \n constructor () {\n this.trie = new TrieNode('/')\n }\n\n \n insert (str, count = 1) {\n let cur = this.trie\n for (const char of str) {\n cur.children[char] ??= new TrieNode(char)\n cur = cur.children[char]\n cur.countPrefix += count\n }\n cur.count += count\n }\n\n \n traverse (str, callbackfn, thisArg) {\n let cur = this.trie\n for (let i = 0; i < str.length; i++) {\n const retChar = callbackfn.call(thisArg, str[i], i, cur)\n const tmp = cur.children[retChar]\n if (!tmp || tmp.countPrefix <= 0) return\n cur = tmp\n }\n }\n\n \n count (str) {\n let ans = 0\n this.traverse(str, (char, idx, node) => {\n const nextNode = node.children[char]\n if (idx === str.length - 1 && nextNode) {\n ans = nextNode.count\n }\n return char\n })\n return ans\n }\n\n \n countPrefix (str) {\n let ans = 0\n this.traverse(str, (char, idx, node) => {\n const nextNode = node.children[char]\n ans += nextNode?.countPrefix ?? 0\n return char\n })\n return ans\n }\n};"
] |
|
1,952 | three-divisors | [
"You can count the number of divisors and just check that they are 3",
"Beware of the case of n equal 1 as some solutions might fail in it"
] | /**
* @param {number} n
* @return {boolean}
*/
var isThree = function(n) {
}; | Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.
An integer m is a divisor of n if there exists an integer k such that n = k * m.
Example 1:
Input: n = 2
Output: false
Explantion: 2 has only two divisors: 1 and 2.
Example 2:
Input: n = 4
Output: true
Explantion: 4 has three divisors: 1, 2, and 4.
Constraints:
1 <= n <= 104
| Easy | [
"math"
] | [
"const isThree = function(n) {\n if(n == 1) return false;\n let a = ~~Math.sqrt(n);\n if(n != a * a) return false;\n for(let i = 2; i < a; i++) {\n if (n % i == 0)\n return false;\n }\n return true;\n};"
] |
|
1,953 | maximum-number-of-weeks-for-which-you-can-work | [
"Work on the project with the largest number of milestones as long as it is possible.",
"Does the project with the largest number of milestones affect the number of weeks?"
] | /**
* @param {number[]} milestones
* @return {number}
*/
var numberOfWeeks = function(milestones) {
}; | There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has.
You can work on the projects following these two rules:
Every week, you will finish exactly one milestone of one project. You must work every week.
You cannot work on two milestones from the same project for two consecutive weeks.
Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints.
Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.
Example 1:
Input: milestones = [1,2,3]
Output: 6
Explanation: One possible scenario is:
- During the 1st week, you will work on a milestone of project 0.
- During the 2nd week, you will work on a milestone of project 2.
- During the 3rd week, you will work on a milestone of project 1.
- During the 4th week, you will work on a milestone of project 2.
- During the 5th week, you will work on a milestone of project 1.
- During the 6th week, you will work on a milestone of project 2.
The total number of weeks is 6.
Example 2:
Input: milestones = [5,2,1]
Output: 7
Explanation: One possible scenario is:
- During the 1st week, you will work on a milestone of project 0.
- During the 2nd week, you will work on a milestone of project 1.
- During the 3rd week, you will work on a milestone of project 0.
- During the 4th week, you will work on a milestone of project 1.
- During the 5th week, you will work on a milestone of project 0.
- During the 6th week, you will work on a milestone of project 2.
- During the 7th week, you will work on a milestone of project 0.
The total number of weeks is 7.
Note that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules.
Thus, one milestone in project 0 will remain unfinished.
Constraints:
n == milestones.length
1 <= n <= 105
1 <= milestones[i] <= 109
| Medium | [
"array",
"greedy"
] | [
"const numberOfWeeks = function(milestones) {\n let max = -Infinity\n let res = 0, sum = 0\n for(const e of milestones) {\n max = Math.max(e, max)\n sum += e\n }\n \n return Math.min(sum, (sum - max) * 2 + 1)\n};",
"const numberOfWeeks = function(milestones) {\n let sum = 0;\n for (let i = 0; i < milestones.length; i++) {\n sum += milestones[i];\n }\n\n let cantWork = 0;\n for (let i = 0; i < milestones.length; i++) {\n cantWork = Math.max(cantWork, milestones[i] - (sum - milestones[i]) - 1);\n }\n\n return sum - cantWork;\n};",
"const numberOfWeeks = function(milestones) {\n const max = Math.max(...milestones)\n let sum = 0\n for(let i = 0; i < milestones.length; i++) {\n sum += milestones[i]\n }\n const res = sum - max\n \n return Math.min(sum, res * 2 + 1)\n};"
] |
|
1,954 | minimum-garden-perimeter-to-collect-enough-apples | [
"Find a formula for the number of apples inside a square with a side length L.",
"Iterate over the possible lengths of the square until enough apples are collected."
] | /**
* @param {number} neededApples
* @return {number}
*/
var minimumPerimeter = function(neededApples) {
}; | In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it.
You will buy an axis-aligned square plot of land that is centered at (0, 0).
Given an integer neededApples, return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot.
The value of |x| is defined as:
x if x >= 0
-x if x < 0
Example 1:
Input: neededApples = 1
Output: 8
Explanation: A square plot of side length 1 does not contain any apples.
However, a square plot of side length 2 has 12 apples inside (as depicted in the image above).
The perimeter is 2 * 4 = 8.
Example 2:
Input: neededApples = 13
Output: 16
Example 3:
Input: neededApples = 1000000000
Output: 5040
Constraints:
1 <= neededApples <= 1015
| Medium | [
"math",
"binary-search"
] | [
"var minimumPerimeter = function(neededApples) {\n let l = 0, r = 100000;\n while (l + 1 < r) {\n let w = (l + r) >> 1;\n let apples = 2 * w * (w + 1) * (2 * w + 1);\n if (apples >= neededApples) {\n r = w;\n } else {\n l = w;\n }\n }\n\n return r * 8; \n};"
] |
|
1,955 | count-number-of-special-subsequences | [
"Can we first solve a simpler problem? Counting the number of subsequences with 1s followed by 0s.",
"How can we keep track of the partially matched subsequences to help us find the answer?"
] | /**
* @param {number[]} nums
* @return {number}
*/
var countSpecialSubsequences = function(nums) {
}; | A sequence is special if it consists of a positive number of 0s, followed by a positive number of 1s, then a positive number of 2s.
For example, [0,1,2] and [0,0,1,1,1,2] are special.
In contrast, [2,1,0], [1], and [0,1,2,0] are not special.
Given an array nums (consisting of only integers 0, 1, and 2), return the number of different subsequences that are special. Since the answer may be very large, return it modulo 109 + 7.
A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different.
Example 1:
Input: nums = [0,1,2,2]
Output: 3
Explanation: The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2].
Example 2:
Input: nums = [2,2,0,0]
Output: 0
Explanation: There are no special subsequences in [2,2,0,0].
Example 3:
Input: nums = [0,1,2,0,1,2]
Output: 7
Explanation: The special subsequences are bolded:
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 2
| Hard | [
"array",
"dynamic-programming"
] | [
"// @lc code=start\n\nconst countSpecialSubsequences = function (nums) {\n const dp = Array(3).fill(0),\n mod = 10 ** 9 + 7\n for (let e of nums) {\n dp[e] = (((dp[e] + dp[e]) % mod) + (e > 0 ? dp[e - 1] : 1)) % mod\n }\n return dp[2]\n}",
"const countSpecialSubsequences = function(nums) {\n const mod = 10 ** 9 + 7\n const dp = Array.from({length: 10 **5 + 1}, () => Array(4).fill(-1))\n let n = nums.length, a = nums\n return f(0, 0)\n function f(index, firstMandatory) {\n if (index == n && firstMandatory == 3) {\n return 1;\n }\n if (index == n) {\n return 0;\n }\n if (dp[index][firstMandatory] >= 0) {\n return dp[index][firstMandatory];\n }\n let result = 0;\n if (a[index] == firstMandatory) {\n result = (result +\n f(index + 1, firstMandatory) +\n f(index + 1, firstMandatory + 1)\n ) % mod;\n }\n result = (result + f(index + 1, firstMandatory)) % mod;\n\n return dp[index][firstMandatory] = result;\n }\n};"
] |
|
1,957 | delete-characters-to-make-fancy-string | [
"What's the optimal way to delete characters if three or more consecutive characters are equal?",
"If three or more consecutive characters are equal, keep two of them and delete the rest."
] | /**
* @param {string} s
* @return {string}
*/
var makeFancyString = function(s) {
}; | A fancy string is a string where no three consecutive characters are equal.
Given a string s, delete the minimum possible number of characters from s to make it fancy.
Return the final string after the deletion. It can be shown that the answer will always be unique.
Example 1:
Input: s = "leeetcode"
Output: "leetcode"
Explanation:
Remove an 'e' from the first group of 'e's to create "leetcode".
No three consecutive characters are equal, so return "leetcode".
Example 2:
Input: s = "aaabaaaa"
Output: "aabaa"
Explanation:
Remove an 'a' from the first group of 'a's to create "aabaaaa".
Remove two 'a's from the second group of 'a's to create "aabaa".
No three consecutive characters are equal, so return "aabaa".
Example 3:
Input: s = "aab"
Output: "aab"
Explanation: No three consecutive characters are equal, so return "aab".
Constraints:
1 <= s.length <= 105
s consists only of lowercase English letters.
| Easy | [
"string"
] | null | [] |
1,958 | check-if-move-is-legal | [
"For each line starting at the given cell check if it's a good line",
"To do that iterate over all directions horizontal, vertical, and diagonals then check good lines naively"
] | /**
* @param {character[][]} board
* @param {number} rMove
* @param {number} cMove
* @param {character} color
* @return {boolean}
*/
var checkMove = function(board, rMove, cMove, color) {
}; | You are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.', white cells are represented by 'W', and black cells are represented by 'B'.
Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal).
A good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color, and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below:
Given two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal.
Example 1:
Input: board = [[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],["W","B","B",".","W","W","W","B"],[".",".",".","B",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."]], rMove = 4, cMove = 3, color = "B"
Output: true
Explanation: '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.
The two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.
Example 2:
Input: board = [[".",".",".",".",".",".",".","."],[".","B",".",".","W",".",".","."],[".",".","W",".",".",".",".","."],[".",".",".","W","B",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".","B","W",".","."],[".",".",".",".",".",".","W","."],[".",".",".",".",".",".",".","B"]], rMove = 4, cMove = 4, color = "W"
Output: false
Explanation: While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.
Constraints:
board.length == board[r].length == 8
0 <= rMove, cMove < 8
board[rMove][cMove] == '.'
color is either 'B' or 'W'.
| Medium | [
"array",
"matrix",
"enumeration"
] | null | [] |
1,959 | minimum-total-space-wasted-with-k-resizing-operations | [
"Given a range, how can you find the minimum waste if you can't perform any resize operations?",
"Can we build our solution using dynamic programming using the current index and the number of resizing operations performed as the states?"
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var minSpaceWastedKResizing = function(nums, k) {
}; | You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size).
The size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at time t is defined as sizet - nums[t], and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length.
Return the minimum total space wasted if you can resize the array at most k times.
Note: The array can have any size at the start and does not count towards the number of resizing operations.
Example 1:
Input: nums = [10,20], k = 0
Output: 10
Explanation: size = [20,20].
We can set the initial size to be 20.
The total wasted space is (20 - 10) + (20 - 20) = 10.
Example 2:
Input: nums = [10,20,30], k = 1
Output: 10
Explanation: size = [20,20,30].
We can set the initial size to be 20 and resize to 30 at time 2.
The total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10.
Example 3:
Input: nums = [10,20,15,30,20], k = 2
Output: 15
Explanation: size = [10,20,20,30,30].
We can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3.
The total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.
Constraints:
1 <= nums.length <= 200
1 <= nums[i] <= 106
0 <= k <= nums.length - 1
| Medium | [
"array",
"dynamic-programming"
] | [
"const minSpaceWastedKResizing = function(nums, k) {\n const n = nums.length, INF = 200 * 1e6\n const memo = Array.from({length: n}, () => Array(k))\n return dp(0, k)\n \n function dp(i, k) {\n if(i === n) return 0\n if(k < 0) return INF\n if(memo[i][k] != null) return memo[i][k]\n let res = INF, max = nums[i], sum = 0\n for(let j = i; j < n; j++) {\n max = Math.max(max, nums[j])\n sum += nums[j]\n const waste = max * (j - i + 1) - sum\n res = Math.min(res, dp(j + 1, k - 1) + waste)\n }\n return memo[i][k] = res\n }\n};"
] |
|
1,960 | maximum-product-of-the-length-of-two-palindromic-substrings | [
"You can use Manacher's algorithm to get the maximum palindromic substring centered at each index",
"After using Manacher's for each center use a line sweep from the center to the left and from the center to the right to find for each index the farthest center to it with distance ≤ palin[center]",
"After that, find the maximum palindrome size for each prefix in the string and for each suffix and the answer would be max(prefix[i] * suffix[i + 1])"
] | /**
* @param {string} s
* @return {number}
*/
var maxProduct = function(s) {
}; | You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized.
More formally, you want to choose four integers i, j, k, l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive.
Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings.
A palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "ababbb"
Output: 9
Explanation: Substrings "aba" and "bbb" are palindromes with odd length. product = 3 * 3 = 9.
Example 2:
Input: s = "zaaaxbbby"
Output: 9
Explanation: Substrings "aaa" and "bbb" are palindromes with odd length. product = 3 * 3 = 9.
Constraints:
2 <= s.length <= 105
s consists of lowercase English letters.
| Hard | [
"string",
"rolling-hash",
"hash-function"
] | [
"const maxProduct = function (s) {\n const t1 = helper(s),\n t2 = helper(reverse(s))\n let res = 0\n for (let n = s.length, i = 0, j = n - 2; i < n - 1; ++i, --j)\n res = Math.max(res, t1[i] * t2[j])\n\n return res\n}\nfunction reverse(s) {\n return [...s].reverse().join('')\n}\nfunction helper(s) {\n const man = manachers(s).filter(\n (e, i, ar) => i >= 2 && i < ar.length - 2 && i % 2 === 0\n )\n const n = s.length,\n { max } = Math\n const ints = man.map((e, i) => [i - ~~(e / 2), i + ~~(e / 2)])\n const arr = Array(n).fill(0)\n for (const [a, b] of ints) {\n arr[b] = max(arr[b], b - a + 1)\n }\n for (let i = n - 2; i >= 0; i--) {\n arr[i] = max(arr[i], arr[i + 1] - 2)\n }\n let tmp = 0\n for (let i = 0; i < n; i++) {\n if (arr[i] > tmp) {\n tmp = arr[i]\n } else arr[i] = tmp\n }\n return arr\n}\nfunction manachers(s) {\n const str = `@#${s.split('').join('#')}#$`\n const arr = Array(str.length).fill(0)\n\n let center = 0,\n right = 0\n for (let i = 1, n = str.length; i < n - 1; i++) {\n if (i < right) {\n arr[i] = Math.min(right - i, arr[2 * center - i])\n }\n while (str[i + arr[i] + 1] === str[i - arr[i] - 1]) {\n arr[i] += 1\n }\n if (i + arr[i] > right) {\n center = i\n right = i + arr[i]\n }\n }\n\n return arr\n}"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.