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 |
---|---|---|---|---|---|---|---|---|
2,218 | maximum-value-of-k-coins-from-piles | [
"For each pile i, what will be the total value of coins we can collect if we choose the first j coins?",
"How can we use dynamic programming to combine the results from different piles to find the most optimal answer?"
] | /**
* @param {number[][]} piles
* @param {number} k
* @return {number}
*/
var maxValueOfCoins = function(piles, k) {
}; | There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations.
In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet.
Given a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally.
Example 1:
Input: piles = [[1,100,3],[7,8,9]], k = 2
Output: 101
Explanation:
The above diagram shows the different ways we can choose k coins.
The maximum total we can obtain is 101.
Example 2:
Input: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7
Output: 706
Explanation:
The maximum total can be obtained if we choose all coins from the last pile.
Constraints:
n == piles.length
1 <= n <= 1000
1 <= piles[i][j] <= 105
1 <= k <= sum(piles[i].length) <= 2000
| Hard | [
"array",
"dynamic-programming",
"prefix-sum"
] | [
"var maxValueOfCoins = function(piles, k) {\n let dp = Array(k + 1).fill(0);\n for (let i = 0; i < piles.length; i++) {\n const next = Array(k + 1).fill(0);\n for (let l = 1; l <= k; l++) {\n let sum = 0;\n next[l] = dp[l];\n for (let j = 0; j < Math.min(piles[i].length, l); j++) {\n sum += piles[i][j];\n next[l] = Math.max(next[l], dp[l - j - 1] + sum);\n }\n }\n dp = next;\n }\n return dp[k]; \n};",
"const maxValueOfCoins = function(piles, k) {\n const n = piles.length\n const memo = Array.from({ length: n + 1 }, () => Array(k + 1).fill(null))\n return helper(0, k)\n\n // TC: O(k * m)\n // k: k\n // n: length of piles\n // m: sum(piles[i]), total elements of all piles\n function helper(i, k) {\n if(k == 0 || i === n) return 0\n if(memo[i][k] != null) return memo[i][k]\n let res = helper(i + 1, k)\n let cur = 0\n\n for(let j = 0; j < Math.min(piles[i].length, k); j++) {\n cur += piles[i][j]\n res = Math.max(res, cur + helper(i + 1, k - j - 1))\n }\n return memo[i][k] = res\n }\n};"
] |
|
2,220 | minimum-bit-flips-to-convert-number | [
"If the value of a bit in start and goal differ, then we need to flip that bit.",
"Consider using the XOR operation to determine which bits need a bit flip."
] | /**
* @param {number} start
* @param {number} goal
* @return {number}
*/
var minBitFlips = function(start, goal) {
}; | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0.
For example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110, flip the second bit from the right to get 101, flip the fifth bit from the right (a leading zero) to get 10111, etc.
Given two integers start and goal, return the minimum number of bit flips to convert start to goal.
Example 1:
Input: start = 10, goal = 7
Output: 3
Explanation: The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps:
- Flip the first bit from the right: 1010 -> 1011.
- Flip the third bit from the right: 1011 -> 1111.
- Flip the fourth bit from the right: 1111 -> 0111.
It can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3.
Example 2:
Input: start = 3, goal = 4
Output: 3
Explanation: The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps:
- Flip the first bit from the right: 011 -> 010.
- Flip the second bit from the right: 010 -> 000.
- Flip the third bit from the right: 000 -> 100.
It can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3.
Constraints:
0 <= start, goal <= 109
| Easy | [
"bit-manipulation"
] | null | [] |
2,221 | find-triangular-sum-of-an-array | [
"Try simulating the entire process.",
"To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step."
] | /**
* @param {number[]} nums
* @return {number}
*/
var triangularSum = function(nums) {
}; | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive).
The triangular sum of nums is the value of the only element present in nums after the following process terminates:
Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n - 1.
For each index i, where 0 <= i < n - 1, assign the value of newNums[i] as (nums[i] + nums[i+1]) % 10, where % denotes modulo operator.
Replace the array nums with newNums.
Repeat the entire process starting from step 1.
Return the triangular sum of nums.
Example 1:
Input: nums = [1,2,3,4,5]
Output: 8
Explanation:
The above diagram depicts the process from which we obtain the triangular sum of the array.
Example 2:
Input: nums = [5]
Output: 5
Explanation:
Since there is only one element in nums, the triangular sum is the value of that element itself.
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 9
| Medium | [
"array",
"math",
"simulation",
"combinatorics"
] | [
"const triangularSum = function(nums) {\n while(nums.length > 1) {\n const arr = []\n for(let i = 0, n = nums.length; i < n - 1; i++) {\n arr.push((nums[i] + nums[i + 1]) % 10)\n }\n nums = arr\n }\n return nums[0]\n};"
] |
|
2,222 | number-of-ways-to-select-buildings | [
"There are only 2 valid patterns: ‘101’ and ‘010’. Think about how we can construct these 2 patterns from smaller patterns.",
"Count the number of subsequences of the form ‘01’ or ‘10’ first. Let n01[i] be the number of ‘01’ subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]?",
"Let n0[i] and n1[i] be the number of ‘0’s and ‘1’s that exists in the prefix of s up to i respectively. Then n01[i] = n01[i – 1] if s[i] == ‘0’, otherwise n01[i] = n01[i – 1] + n0[i – 1].",
"The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of ‘101’ and ‘010‘ subsequences."
] | /**
* @param {string} s
* @return {number}
*/
var numberOfWays = function(s) {
}; | You are given a 0-indexed binary string s which represents the types of buildings along a street where:
s[i] = '0' denotes that the ith building is an office and
s[i] = '1' denotes that the ith building is a restaurant.
As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type.
For example, given s = "001101", we cannot select the 1st, 3rd, and 5th buildings as that would form "011" which is not allowed due to having two consecutive buildings of the same type.
Return the number of valid ways to select 3 buildings.
Example 1:
Input: s = "001101"
Output: 6
Explanation:
The following sets of indices selected are valid:
- [0,2,4] from "001101" forms "010"
- [0,3,4] from "001101" forms "010"
- [1,2,4] from "001101" forms "010"
- [1,3,4] from "001101" forms "010"
- [2,4,5] from "001101" forms "101"
- [3,4,5] from "001101" forms "101"
No other selection is valid. Thus, there are 6 total ways.
Example 2:
Input: s = "11100"
Output: 0
Explanation: It can be shown that there are no valid selections.
Constraints:
3 <= s.length <= 105
s[i] is either '0' or '1'.
| Medium | [
"string",
"dynamic-programming",
"prefix-sum"
] | [
"const numberOfWays = function(s) {\n let one = 0, zero = 0\n for(const ch of s) {\n if(ch === '1') one++\n else zero++\n }\n let preOne = 0, preZero = 0\n let res = 0\n \n for(const ch of s) {\n if(ch === '1') {\n res += preZero * zero\n preOne++\n one--\n } else {\n res += preOne * one\n preZero++\n zero--\n }\n }\n \n return res\n};"
] |
|
2,223 | sum-of-scores-of-built-strings | [
"Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix.",
"Could you use the Z array from the Z algorithm to find the score of each s_i?"
] | /**
* @param {string} s
* @return {number}
*/
var sumScores = function(s) {
}; | You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si.
For example, for s = "abaca", s1 == "a", s2 == "ca", s3 == "aca", etc.
The score of si is the length of the longest common prefix between si and sn (Note that s == sn).
Given the final string s, return the sum of the score of every si.
Example 1:
Input: s = "babab"
Output: 9
Explanation:
For s1 == "b", the longest common prefix is "b" which has a score of 1.
For s2 == "ab", there is no common prefix so the score is 0.
For s3 == "bab", the longest common prefix is "bab" which has a score of 3.
For s4 == "abab", there is no common prefix so the score is 0.
For s5 == "babab", the longest common prefix is "babab" which has a score of 5.
The sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9.
Example 2:
Input: s = "azbazbzaz"
Output: 14
Explanation:
For s2 == "az", the longest common prefix is "az" which has a score of 2.
For s6 == "azbzaz", the longest common prefix is "azb" which has a score of 3.
For s9 == "azbazbzaz", the longest common prefix is "azbazbzaz" which has a score of 9.
For all other si, the score is 0.
The sum of the scores is 2 + 3 + 9 = 14, so we return 14.
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
| Hard | [
"string",
"binary-search",
"rolling-hash",
"suffix-array",
"string-matching",
"hash-function"
] | [
"var sumScores = function(s) {\n function z_function(s) {\n let n = s.length\n let z = Array(n).fill(0)\n let l = 0, r = 0\n for (let i = 1; i < n; i++) {\n if (i <= r) z[i] = Math.min(r - i + 1, z[i - l])\n while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {\n z[i] += 1 \n }\n\n if (i + z[i] - 1 > r) {\n l = i\n r = i + z[i] - 1 \n }\n\n }\n return z \n }\n\n const sum = z_function(s).reduce((ac, e) => ac + e, 0)\n return sum + s.length \n};\n "
] |
|
2,224 | minimum-number-of-operations-to-convert-time | [
"Convert the times to minutes.",
"Use the operation with the biggest value possible at each step."
] | /**
* @param {string} current
* @param {string} correct
* @return {number}
*/
var convertTime = function(current, correct) {
}; | You are given two strings current and correct representing two 24-hour times.
24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.
In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times.
Return the minimum number of operations needed to convert current to correct.
Example 1:
Input: current = "02:30", correct = "04:35"
Output: 3
Explanation:
We can convert current to correct in 3 operations as follows:
- Add 60 minutes to current. current becomes "03:30".
- Add 60 minutes to current. current becomes "04:30".
- Add 5 minutes to current. current becomes "04:35".
It can be proven that it is not possible to convert current to correct in fewer than 3 operations.
Example 2:
Input: current = "11:00", correct = "11:01"
Output: 1
Explanation: We only have to add one minute to current, so the minimum number of operations needed is 1.
Constraints:
current and correct are in the format "HH:MM"
current <= correct
| Easy | [
"string",
"greedy"
] | [
"var convertTime = function(current, correct) {\n const s = current.split(':').map(e => +e)\n const t = correct.split(':').map(e => +e)\n let res = 0\n // hour\n if(s[0] < t[0]) res += t[0] - s[0]\n else if(s[0] > t[0]) res += (24 - (s[0] - t[0]))\n \n // min\n let delta = t[1] - s[1]\n if(delta > 0) {\n if(delta >= 15) {\n res += ~~(delta / 15)\n delta %= 15\n }\n if(delta >= 5) {\n res += ~~(delta / 5)\n delta %= 5\n }\n res += delta\n } else if(delta < 0) {\n res--\n delta += 60\n if(delta >= 15) {\n res += ~~(delta / 15)\n delta %= 15\n }\n if(delta >= 5) {\n res += ~~(delta / 5)\n delta %= 5\n }\n res += delta\n }\n \n return res\n};"
] |
|
2,225 | find-players-with-zero-or-one-losses | [
"Count the number of times a player loses while iterating through the matches."
] | /**
* @param {number[][]} matches
* @return {number[][]}
*/
var findWinners = function(matches) {
}; | You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match.
Return a list answer of size 2 where:
answer[0] is a list of all players that have not lost any matches.
answer[1] is a list of all players that have lost exactly one match.
The values in the two lists should be returned in increasing order.
Note:
You should only consider the players that have played at least one match.
The testcases will be generated such that no two matches will have the same outcome.
Example 1:
Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]
Output: [[1,2,10],[4,5,7,8]]
Explanation:
Players 1, 2, and 10 have not lost any matches.
Players 4, 5, 7, and 8 each have lost one match.
Players 3, 6, and 9 each have lost two matches.
Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].
Example 2:
Input: matches = [[2,3],[1,3],[5,4],[6,4]]
Output: [[1,2,5,6],[]]
Explanation:
Players 1, 2, 5, and 6 have not lost any matches.
Players 3 and 4 each have lost two matches.
Thus, answer[0] = [1,2,5,6] and answer[1] = [].
Constraints:
1 <= matches.length <= 105
matches[i].length == 2
1 <= winneri, loseri <= 105
winneri != loseri
All matches[i] are unique.
| Medium | [
"array",
"hash-table",
"sorting",
"counting"
] | [
"var findWinners = function(matches) {\n const win = {}, lose = {}, total = new Set(), ls = new Set()\n for(const [w, l] of matches) {\n if(win[w] == null) win[w] = 0\n win[w]++\n if(lose[l] == null) lose[l] = 0\n lose[l]++\n total.add(l)\n total.add(w)\n ls.add(l)\n }\n \n const loseKeys = Object.keys(lose)\n const a0 = []\n for(const e of total) {\n if(!ls.has(e)) a0.push(e)\n }\n const a1 = []\n for(const e of loseKeys) {\n if(lose[e] === 1) a1.push(e)\n }\n a0.sort((a, b) => a - b)\n a1.sort((a, b) => a - b)\n return [a0, a1]\n};"
] |
|
2,226 | maximum-candies-allocated-to-k-children | [
"For a fixed number of candies c, how can you check if each child can get c candies?",
"Use binary search to find the maximum c as the answer."
] | /**
* @param {number[]} candies
* @param {number} k
* @return {number}
*/
var maximumCandies = function(candies, k) {
}; | You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together.
You are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused.
Return the maximum number of candies each child can get.
Example 1:
Input: candies = [5,8,6], k = 3
Output: 5
Explanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.
Example 2:
Input: candies = [2,5], k = 11
Output: 0
Explanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.
Constraints:
1 <= candies.length <= 105
1 <= candies[i] <= 107
1 <= k <= 1012
| Medium | [
"array",
"binary-search"
] | [
"const maximumCandies = function(candies, k) {\n let max = candies.reduce((ac, e) => ac + e, 0);\n let min = 0;\n while (min < max) {\n let mid = max - Math.floor((max - min) / 2);\n let cnt = 0;\n for (let cand of candies) {\n cnt += ~~(cand / mid);\n }\n if (cnt < k) {\n max = mid - 1;\n } else {\n min = mid;\n }\n }\n return min;\n};",
"const maximumCandies = function(candies, k) {\n let max = candies.reduce((ac, e) => ac + e, 0)\n let min = 0\n while(min < max) {\n const mid = max - Math.floor((max - min) /2)\n let num = 0\n for(let e of candies) num += ~~(e / mid)\n if(num < k) max = mid - 1\n else min = mid\n }\n return min\n};"
] |
|
2,227 | encrypt-and-decrypt-strings | [
"For encryption, use hashmap to map each char of word1 to its value.",
"For decryption, use trie to prune when necessary."
] | /**
* @param {character[]} keys
* @param {string[]} values
* @param {string[]} dictionary
*/
var Encrypter = function(keys, values, dictionary) {
};
/**
* @param {string} word1
* @return {string}
*/
Encrypter.prototype.encrypt = function(word1) {
};
/**
* @param {string} word2
* @return {number}
*/
Encrypter.prototype.decrypt = function(word2) {
};
/**
* Your Encrypter object will be instantiated and called as such:
* var obj = new Encrypter(keys, values, dictionary)
* var param_1 = obj.encrypt(word1)
* var param_2 = obj.decrypt(word2)
*/ | You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed string.
A string is encrypted with the following process:
For each character c in the string, we find the index i satisfying keys[i] == c in keys.
Replace c with values[i] in the string.
Note that in case a character of the string is not present in keys, the encryption process cannot be carried out, and an empty string "" is returned.
A string is decrypted with the following process:
For each substring s of length 2 occurring at an even index in the string, we find an i such that values[i] == s. If there are multiple valid i, we choose any one of them. This means a string could have multiple possible strings it can decrypt to.
Replace s with keys[i] in the string.
Implement the Encrypter class:
Encrypter(char[] keys, String[] values, String[] dictionary) Initializes the Encrypter class with keys, values, and dictionary.
String encrypt(String word1) Encrypts word1 with the encryption process described above and returns the encrypted string.
int decrypt(String word2) Returns the number of possible strings word2 could decrypt to that also appear in dictionary.
Example 1:
Input
["Encrypter", "encrypt", "decrypt"]
[[['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]], ["abcd"], ["eizfeiam"]]
Output
[null, "eizfeiam", 2]
Explanation
Encrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]);
encrypter.encrypt("abcd"); // return "eizfeiam".
// 'a' maps to "ei", 'b' maps to "zf", 'c' maps to "ei", and 'd' maps to "am".
encrypter.decrypt("eizfeiam"); // return 2.
// "ei" can map to 'a' or 'c', "zf" maps to 'b', and "am" maps to 'd'.
// Thus, the possible strings after decryption are "abad", "cbad", "abcd", and "cbcd".
// 2 of those strings, "abad" and "abcd", appear in dictionary, so the answer is 2.
Constraints:
1 <= keys.length == values.length <= 26
values[i].length == 2
1 <= dictionary.length <= 100
1 <= dictionary[i].length <= 100
All keys[i] and dictionary[i] are unique.
1 <= word1.length <= 2000
1 <= word2.length <= 200
All word1[i] appear in keys.
word2.length is even.
keys, values[i], dictionary[i], word1, and word2 only contain lowercase English letters.
At most 200 calls will be made to encrypt and decrypt in total.
| Hard | [
"array",
"hash-table",
"string",
"design",
"trie"
] | [
"class Encrypter {\n constructor(keys, values, dictionary) {\n this.mapKeyToValue = {};\n this.mapCount = {};\n const n = keys.length;\n\n for (let i = 0; i < n; i++) {\n const key = keys[i];\n const value = values[i];\n this.mapKeyToValue[key] = value;\n }\n\n for (const dict of dictionary) {\n const encrypted = this.encrypt(dict);\n this.mapCount[encrypted] = (this.mapCount[encrypted] || 0) + 1;\n }\n }\n\n encrypt(word1) {\n let res = '';\n for (const char of word1) {\n res += this.mapKeyToValue[char];\n }\n return res;\n }\n\n decrypt(word2) {\n return this.mapCount[word2] || 0;\n }\n}"
] |
|
2,231 | largest-number-after-digit-swaps-by-parity | [
"The bigger digit should appear first (more to the left) because it contributes more to the value of the number.",
"Get all the even digits, as well as odd digits. Sort them separately.",
"Reconstruct the number by giving the earlier digits the highest available digit of the same parity."
] | /**
* @param {number} num
* @return {number}
*/
var largestInteger = function(num) {
}; | You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits).
Return the largest possible value of num after any number of swaps.
Example 1:
Input: num = 1234
Output: 3412
Explanation: Swap the digit 3 with the digit 1, this results in the number 3214.
Swap the digit 2 with the digit 4, this results in the number 3412.
Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.
Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.
Example 2:
Input: num = 65875
Output: 87655
Explanation: Swap the digit 8 with the digit 6, this results in the number 85675.
Swap the first digit 5 with the digit 7, this results in the number 87655.
Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.
Constraints:
1 <= num <= 109
| Easy | [
"sorting",
"heap-priority-queue"
] | null | [] |
2,232 | minimize-result-by-adding-parentheses-to-expression | [
"The maximum length of expression is very low. We can try every possible spot to place the parentheses.",
"Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them."
] | /**
* @param {string} expression
* @return {string}
*/
var minimizeResult = function(expression) {
}; | You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers.
Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'.
Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them.
The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
Example 1:
Input: expression = "247+38"
Output: "2(47+38)"
Explanation: The expression evaluates to 2 * (47 + 38) = 2 * 85 = 170.
Note that "2(4)7+38" is invalid because the right parenthesis must be to the right of the '+'.
It can be shown that 170 is the smallest possible value.
Example 2:
Input: expression = "12+34"
Output: "1(2+3)4"
Explanation: The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.
Example 3:
Input: expression = "999+999"
Output: "(999+999)"
Explanation: The expression evaluates to 999 + 999 = 1998.
Constraints:
3 <= expression.length <= 10
expression consists of digits from '1' to '9' and '+'.
expression starts and ends with digits.
expression contains exactly one '+'.
The original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
| Medium | [
"string",
"enumeration"
] | null | [] |
2,233 | maximum-product-after-k-increments | [
"If you can increment only once, which number should you increment?",
"We should always prioritize the smallest number. What kind of data structure could we use?",
"Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1."
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var maximumProduct = function(nums, k) {
}; | You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1.
Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Example 1:
Input: nums = [0,4], k = 5
Output: 20
Explanation: Increment the first number 5 times.
Now nums = [5, 4], with a product of 5 * 4 = 20.
It can be shown that 20 is maximum product possible, so we return 20.
Note that there may be other ways to increment nums to have the maximum product.
Example 2:
Input: nums = [6,3,3,2], k = 2
Output: 216
Explanation: Increment the second number 1 time and increment the fourth number 1 time.
Now nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.
It can be shown that 216 is maximum product possible, so we return 216.
Note that there may be other ways to increment nums to have the maximum product.
Constraints:
1 <= nums.length, k <= 105
0 <= nums[i] <= 106
| Medium | [
"array",
"greedy",
"heap-priority-queue"
] | [
"const maximumProduct = function (nums, k) {\n const pq = new PriorityQueue((a, b) => a < b)\n let res = 1\n for(const e of nums) pq.push(e)\n const mod = 1e9 + 7\n while(k) {\n const e = pq.pop()\n pq.push(e + 1)\n k--\n }\n while(!pq.isEmpty()) {\n const e = pq.pop()\n res = (res * e) % mod\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}"
] |
|
2,234 | maximum-total-beauty-of-the-gardens | [
"Say we choose k gardens to be complete, is there an optimal way of choosing which gardens to plant more flowers to achieve this?",
"For a given k, we should greedily fill-up the k gardens with the most flowers planted already. This gives us the most remaining flowers to fill up the other gardens.",
"After sorting flowers, we can thus try every possible k and what is left is to find the highest minimum flowers we can obtain by planting the remaining flowers in the other gardens.",
"To find the highest minimum in the other gardens, we can use binary search to find the most optimal way of planting."
] | /**
* @param {number[]} flowers
* @param {number} newFlowers
* @param {number} target
* @param {number} full
* @param {number} partial
* @return {number}
*/
var maximumBeauty = function(flowers, newFlowers, target, full, partial) {
}; | Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens.
You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial.
A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following:
The number of complete gardens multiplied by full.
The minimum number of flowers in any of the incomplete gardens multiplied by partial. If there are no incomplete gardens, then this value will be 0.
Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
Example 1:
Input: flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1
Output: 14
Explanation: Alice can plant
- 2 flowers in the 0th garden
- 3 flowers in the 1st garden
- 1 flower in the 2nd garden
- 1 flower in the 3rd garden
The gardens will then be [3,6,2,2]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers.
There is 1 garden that is complete.
The minimum number of flowers in the incomplete gardens is 2.
Thus, the total beauty is 1 * 12 + 2 * 1 = 12 + 2 = 14.
No other way of planting flowers can obtain a total beauty higher than 14.
Example 2:
Input: flowers = [2,4,5,3], newFlowers = 10, target = 5, full = 2, partial = 6
Output: 30
Explanation: Alice can plant
- 3 flowers in the 0th garden
- 0 flowers in the 1st garden
- 0 flowers in the 2nd garden
- 2 flowers in the 3rd garden
The gardens will then be [5,4,5,5]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers.
There are 3 gardens that are complete.
The minimum number of flowers in the incomplete gardens is 4.
Thus, the total beauty is 3 * 2 + 4 * 6 = 6 + 24 = 30.
No other way of planting flowers can obtain a total beauty higher than 30.
Note that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty.
Constraints:
1 <= flowers.length <= 105
1 <= flowers[i], target <= 105
1 <= newFlowers <= 1010
1 <= full, partial <= 105
| Hard | [
"array",
"two-pointers",
"binary-search",
"greedy",
"sorting"
] | [
"const maximumBeauty = function (flowers, newFlowers, target, full, partial) {\n flowers.sort((x, y) => x - y)\n flowers = flowers.map((x) => Math.min(x, target))\n let a = flowers,\n n = a.length,\n k = newFlowers,\n pre = preSum(a),\n bi = new Bisect()\n let res = 0\n for (let i = 0; i <= n; i++) {\n if (i < n && a[n - 1 - i] == target) continue\n let step = i * target - (pre[n] - pre[n - i])\n if (step <= k) {\n let beauty\n if (i == n) {\n beauty = i * full\n } else {\n let minPartial = BinarySearch(a[0], target, step, i)\n beauty = i * full + minPartial * partial\n }\n if (beauty > res) res = beauty\n }\n }\n return res\n\n function BinarySearch (low, high, step, i) {\n while (low < high - 1) {\n let mid = low + parseInt((high - low) / 2)\n if (possible(mid, step, i)) {\n low = mid\n } else {\n high = mid\n }\n }\n return low\n }\n\n function possible (m, step, i) {\n let idx = bi.bisect_left(a, m, 0, n - i)\n let need = m * idx - pre[idx]\n return need <= k - step\n }\n}\n\n/////////////////// Template /////////////////////////////////\nfunction Bisect() {\n return { insort_right, insort_left, bisect_left, bisect_right }\n function insort_right(a, x, lo = 0, hi = null) {\n lo = bisect_right(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_right(a, x, lo = 0, hi = null) {\n // > upper_bound\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2)\n a[mid] > x ? (hi = mid) : (lo = mid + 1)\n }\n return lo\n }\n function insort_left(a, x, lo = 0, hi = null) {\n lo = bisect_left(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_left(a, x, lo = 0, hi = null) {\n // >= lower_bound\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2)\n a[mid] < x ? (lo = mid + 1) : (hi = mid)\n }\n return lo\n }\n}\n\nconst preSum = (a) => {\n let pre = [0]\n for (let i = 0; i < a.length; i++) {\n pre.push(pre[i] + a[i])\n }\n return pre\n}\n//////////////////////////////////////////////////////////////////"
] |
|
2,235 | add-two-integers | [] | /**
* @param {number} num1
* @param {number} num2
* @return {number}
*/
var sum = function(num1, num2) {
}; | Given two integers num1 and num2, return the sum of the two integers.
Example 1:
Input: num1 = 12, num2 = 5
Output: 17
Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.
Example 2:
Input: num1 = -10, num2 = 4
Output: -6
Explanation: num1 + num2 = -6, so -6 is returned.
Constraints:
-100 <= num1, num2 <= 100
| Easy | [
"math"
] | [
"var sum = function(num1, num2) {\n return num1 + num2\n};"
] |
|
2,236 | root-equals-sum-of-children | [] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var checkTree = function(root) {
}; | You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child.
Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Example 1:
Input: root = [10,4,6]
Output: true
Explanation: The values of the root, its left child, and its right child are 10, 4, and 6, respectively.
10 is equal to 4 + 6, so we return true.
Example 2:
Input: root = [5,3,1]
Output: false
Explanation: The values of the root, its left child, and its right child are 5, 3, and 1, respectively.
5 is not equal to 3 + 1, so we return false.
Constraints:
The tree consists only of the root, its left child, and its right child.
-100 <= Node.val <= 100
| Easy | [
"tree",
"binary-tree"
] | null | [] |
2,239 | find-closest-number-to-zero | [
"Keep track of the number closest to 0 as you iterate through the array.",
"Ensure that if multiple numbers are closest to 0, you store the one with the largest value."
] | /**
* @param {number[]} nums
* @return {number}
*/
var findClosestNumber = function(nums) {
}; | Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value.
Example 1:
Input: nums = [-4,-2,1,4,8]
Output: 1
Explanation:
The distance from -4 to 0 is |-4| = 4.
The distance from -2 to 0 is |-2| = 2.
The distance from 1 to 0 is |1| = 1.
The distance from 4 to 0 is |4| = 4.
The distance from 8 to 0 is |8| = 8.
Thus, the closest number to 0 in the array is 1.
Example 2:
Input: nums = [2,-1,1]
Output: 1
Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.
Constraints:
1 <= n <= 1000
-105 <= nums[i] <= 105
| Easy | [
"array"
] | null | [] |
2,240 | number-of-ways-to-buy-pens-and-pencils | [
"Fix the number of pencils purchased and calculate the number of ways to buy pens.",
"Sum up the number of ways to buy pens for each amount of pencils purchased to get the answer."
] | /**
* @param {number} total
* @param {number} cost1
* @param {number} cost2
* @return {number}
*/
var waysToBuyPensPencils = function(total, cost1, cost2) {
}; | You are given an integer total indicating the amount of money you have. You are also given two integers cost1 and cost2 indicating the price of a pen and pencil respectively. You can spend part or all of your money to buy multiple quantities (or none) of each kind of writing utensil.
Return the number of distinct ways you can buy some number of pens and pencils.
Example 1:
Input: total = 20, cost1 = 10, cost2 = 5
Output: 9
Explanation: The price of a pen is 10 and the price of a pencil is 5.
- If you buy 0 pens, you can buy 0, 1, 2, 3, or 4 pencils.
- If you buy 1 pen, you can buy 0, 1, or 2 pencils.
- If you buy 2 pens, you cannot buy any pencils.
The total number of ways to buy pens and pencils is 5 + 3 + 1 = 9.
Example 2:
Input: total = 5, cost1 = 10, cost2 = 10
Output: 1
Explanation: The price of both pens and pencils are 10, which cost more than total, so you cannot buy any writing utensils. Therefore, there is only 1 way: buy 0 pens and 0 pencils.
Constraints:
1 <= total, cost1, cost2 <= 106
| Medium | [
"math",
"enumeration"
] | null | [] |
2,241 | design-an-atm-machine | [
"Store the number of banknotes of each denomination.",
"Can you use math to quickly evaluate a withdrawal request?"
] |
var ATM = function() {
};
/**
* @param {number[]} banknotesCount
* @return {void}
*/
ATM.prototype.deposit = function(banknotesCount) {
};
/**
* @param {number} amount
* @return {number[]}
*/
ATM.prototype.withdraw = function(amount) {
};
/**
* Your ATM object will be instantiated and called as such:
* var obj = new ATM()
* obj.deposit(banknotesCount)
* var param_2 = obj.withdraw(amount)
*/ | There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money.
When withdrawing, the machine prioritizes using banknotes of larger values.
For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.
However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100. Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote.
Implement the ATM class:
ATM() Initializes the ATM object.
void deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100, $200, and $500.
int[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that will be handed to the user in the order $20, $50, $100, $200, and $500, and update the number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do not withdraw any banknotes in this case).
Example 1:
Input
["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"]
[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]
Output
[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]
Explanation
ATM atm = new ATM();
atm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,
// and 1 $500 banknote.
atm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote
// and 1 $500 banknote. The banknotes left over in the
// machine are [0,0,0,2,0].
atm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.
// The banknotes in the machine are now [0,1,0,3,1].
atm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote
// and then be unable to complete the remaining $100,
// so the withdraw request will be rejected.
// Since the request is rejected, the number of banknotes
// in the machine is not modified.
atm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote
// and 1 $500 banknote.
Constraints:
banknotesCount.length == 5
0 <= banknotesCount[i] <= 109
1 <= amount <= 109
At most 5000 calls in total will be made to withdraw and deposit.
At least one call will be made to each function withdraw and deposit.
| Medium | [
"array",
"greedy",
"design"
] | null | [] |
2,242 | maximum-score-of-a-node-sequence | [
"For every node sequence of length 4, there are 3 relevant edges. How can we consider valid triplets of edges?",
"Fix the middle 2 nodes connected by an edge in the node sequence. Can you determine the other 2 nodes that will give the highest possible score?",
"The other 2 nodes must each be connected to one of the middle nodes. If we only consider nodes with the highest scores, how many should we store to ensure we don’t choose duplicate nodes?",
"For each node, we should store the 3 adjacent nodes with the highest scores to ensure we can find a sequence with no duplicate nodes via the method above."
] | /**
* @param {number[]} scores
* @param {number[][]} edges
* @return {number}
*/
var maximumScore = function(scores, edges) {
}; | There is an undirected graph with n nodes, numbered from 0 to n - 1.
You are given a 0-indexed integer array scores of length n where scores[i] denotes the score of node i. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.
A node sequence is valid if it meets the following conditions:
There is an edge connecting every pair of adjacent nodes in the sequence.
No node appears more than once in the sequence.
The score of a node sequence is defined as the sum of the scores of the nodes in the sequence.
Return the maximum score of a valid node sequence with a length of 4. If no such sequence exists, return -1.
Example 1:
Input: scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]
Output: 24
Explanation: The figure above shows the graph and the chosen node sequence [0,1,2,3].
The score of the node sequence is 5 + 2 + 9 + 8 = 24.
It can be shown that no other node sequence has a score of more than 24.
Note that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24.
The sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3.
Example 2:
Input: scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]]
Output: -1
Explanation: The figure above shows the graph.
There are no valid node sequences of length 4, so we return -1.
Constraints:
n == scores.length
4 <= n <= 5 * 104
1 <= scores[i] <= 108
0 <= edges.length <= 5 * 104
edges[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
There are no duplicate edges.
| Hard | [
"array",
"graph",
"sorting",
"enumeration"
] | [
"class Heap {\n constructor(data = []) {\n this.data = data\n this.comparator = (a, b) => a[1] - b[1]\n this.heapify()\n }\n\n // O(nlog(n)). In fact, O(n)\n heapify() {\n if (this.size() < 2) return\n for (let i = 1; i < this.size(); i++) {\n this.bubbleUp(i)\n }\n }\n\n // O(1)\n peek() {\n if (this.size() === 0) return null\n return this.data[0]\n }\n\n // O(log(n))\n offer(value) {\n this.data.push(value)\n this.bubbleUp(this.size() - 1)\n }\n\n // O(log(n))\n poll() {\n if (this.size() === 0) return null\n const result = this.data[0]\n const last = this.data.pop()\n if (this.size() !== 0) {\n this.data[0] = last\n this.bubbleDown(0)\n }\n return result\n }\n\n // O(log(n))\n bubbleUp(index) {\n while (index > 0) {\n const parentIndex = (index - 1) >> 1\n if (this.comparator(this.data[index], this.data[parentIndex]) < 0) {\n this.swap(index, parentIndex)\n index = parentIndex\n } else {\n break\n }\n }\n }\n\n // O(log(n))\n bubbleDown(index) {\n const lastIndex = this.size() - 1\n while (true) {\n const leftIndex = index * 2 + 1\n const rightIndex = index * 2 + 2\n let findIndex = index\n if (\n leftIndex <= lastIndex &&\n this.comparator(this.data[leftIndex], this.data[findIndex]) < 0\n ) {\n findIndex = leftIndex\n }\n if (\n rightIndex <= lastIndex &&\n this.comparator(this.data[rightIndex], this.data[findIndex]) < 0\n ) {\n findIndex = rightIndex\n }\n if (index !== findIndex) {\n this.swap(index, findIndex)\n index = findIndex\n } else {\n break\n }\n }\n }\n\n // O(1)\n swap(index1, index2) {\n ;[this.data[index1], this.data[index2]] = [\n this.data[index2],\n this.data[index1],\n ]\n }\n\n // O(1)\n size() {\n return this.data.length\n }\n\n toArray() {\n return this.data.reverse().map((dt) => dt.index)\n }\n}\n\n\nconst maximumScore = (scores, edges) => {\n const n = scores.length\n const top3 = new Array(n).fill().map(() => new Heap())\n\n for (const [u, v] of edges) {\n top3[u].offer([v, scores[v]])\n if (top3[u].size() > 3) top3[u].poll()\n top3[v].offer([u, scores[u]])\n if (top3[v].size() > 3) top3[v].poll()\n }\n\n const top3Array = new Array(n)\n\n for (let i = 0; i < n; i++) {\n top3Array[i] = [...top3[i].data]\n }\n\n let ans = -1\n for (let [b, c] of edges) {\n if (top3[b].size() < 2 || top3[c].size() < 2) {\n continue\n }\n\n const score = scores[b] + scores[c]\n\n for (let [a, scoreA] of top3Array[b]) {\n for (let [d, scoreD] of top3Array[c]) {\n if (a !== b && a !== c && d !== b && d !== c && a !== d) {\n ans = Math.max(ans, scoreA + score + scoreD)\n }\n }\n }\n }\n\n return ans\n}"
] |
|
2,243 | calculate-digit-sum-of-a-string | [
"Try simulating the entire process to find the final answer."
] | /**
* @param {string} s
* @param {number} k
* @return {string}
*/
var digitSum = function(s, k) {
}; | You are given a string s consisting of digits and an integer k.
A round can be completed if the length of s is greater than k. In one round, do the following:
Divide s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on. Note that the size of the last group can be smaller than k.
Replace each group of s with a string representing the sum of all its digits. For example, "346" is replaced with "13" because 3 + 4 + 6 = 13.
Merge consecutive groups together to form a new string. If the length of the string is greater than k, repeat from step 1.
Return s after all rounds have been completed.
Example 1:
Input: s = "11111222223", k = 3
Output: "135"
Explanation:
- For the first round, we divide s into groups of size 3: "111", "112", "222", and "23".
Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5.
So, s becomes "3" + "4" + "6" + "5" = "3465" after the first round.
- For the second round, we divide s into "346" and "5".
Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5.
So, s becomes "13" + "5" = "135" after second round.
Now, s.length <= k, so we return "135" as the answer.
Example 2:
Input: s = "00000000", k = 3
Output: "000"
Explanation:
We divide s into "000", "000", and "00".
Then we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0.
s becomes "0" + "0" + "0" = "000", whose length is equal to k, so we return "000".
Constraints:
1 <= s.length <= 100
2 <= k <= 100
s consists of digits only.
| Easy | [
"string",
"simulation"
] | [
"const digitSum = function(s, k) {\n let cur = s\n while(cur.length > k) {\n const arr = []\n for(let i = 0; i < cur.length; i += k) {\n let tmp = ''\n for(let j = 0; j < k && i + j < cur.length; j++) {\n tmp += cur[i + j]\n }\n arr.push(tmp)\n }\n arr.forEach((e, i) => {\n let res = 0\n for(let ch of e) res += +ch\n arr[i] = '' +res\n })\n cur = arr.join('')\n \n }\n return cur\n};"
] |
|
2,244 | minimum-rounds-to-complete-all-tasks | [
"Which data structure can you use to store the number of tasks of each difficulty level?",
"For any particular difficulty level, what can be the optimal strategy to complete the tasks using minimum rounds?",
"When can we not complete all tasks of a difficulty level?"
] | /**
* @param {number[]} tasks
* @return {number}
*/
var minimumRounds = function(tasks) {
}; | You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.
Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.
Example 1:
Input: tasks = [2,2,3,3,2,4,4,4,4,4]
Output: 4
Explanation: To complete all the tasks, a possible plan is:
- In the first round, you complete 3 tasks of difficulty level 2.
- In the second round, you complete 2 tasks of difficulty level 3.
- In the third round, you complete 3 tasks of difficulty level 4.
- In the fourth round, you complete 2 tasks of difficulty level 4.
It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.
Example 2:
Input: tasks = [2,3,3]
Output: -1
Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.
Constraints:
1 <= tasks.length <= 105
1 <= tasks[i] <= 109
| Medium | [
"array",
"hash-table",
"greedy",
"counting"
] | [
"const minimumRounds = function(tasks) {\n let res = 0\n const hash = {}\n for(let e of tasks) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n const keys = Object.keys(hash).map(e => +e)\n for(const k of keys) {\n if(hash[k] / 3 >= 1) res += ~~(hash[k] / 3)\n if(hash[k] % 3 === 2) res++\n if(hash[k] % 3 === 1) {\n if(hash[k] >= 4) res++\n else return -1\n }\n }\n \n return res\n};"
] |
|
2,245 | maximum-trailing-zeros-in-a-cornered-path | [
"What actually tells us the trailing zeros of the product of a path?",
"It is the sum of the exponents of 2 and sum of the exponents of 5 of the prime factorizations of the numbers on that path. The smaller of the two is the answer for that path.",
"We can then treat each cell as the elbow point and calculate the largest minimum (sum of 2 exponents, sum of 5 exponents) from the combination of top-left, top-right, bottom-left and bottom-right.",
"To do this efficiently, we should use the prefix sum technique."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var maxTrailingZeros = function(grid) {
}; | You are given a 2D integer array grid of size m x n, where each cell contains a positive integer.
A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell.
The product of a path is defined as the product of all the values in the path.
Return the maximum number of trailing zeros in the product of a cornered path found in grid.
Note:
Horizontal movement means moving in either the left or right direction.
Vertical movement means moving in either the up or down direction.
Example 1:
Input: grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]]
Output: 3
Explanation: The grid on the left shows a valid cornered path.
It has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.
It can be shown that this is the maximum trailing zeros in the product of a cornered path.
The grid in the middle is not a cornered path as it has more than one turn.
The grid on the right is not a cornered path as it requires a return to a previously visited cell.
Example 2:
Input: grid = [[4,3,2],[7,6,1],[8,8,8]]
Output: 0
Explanation: The grid is shown in the figure above.
There are no cornered paths in the grid that result in a product with a trailing zero.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
1 <= grid[i][j] <= 1000
| Medium | [
"array",
"matrix",
"prefix-sum"
] | [
"const maxTrailingZeros = function maxTrailingZeros(grid) {\n const m = grid.length\n const n = grid[0].length\n\n const factors = (num, k) => {\n let sum = 0\n while (!(num % k)) {\n num /= k\n sum += 1\n }\n\n return sum\n }\n\n const getRowPrefixSum = (k) => {\n const rowPrefixSum = []\n for (let i = 0; i < m; i++) {\n rowPrefixSum.push([factors(grid[i][0], k)])\n for (let j = 1; j < n; j++) {\n rowPrefixSum[i][j] = factors(grid[i][j], k) + rowPrefixSum[i][j - 1]\n }\n }\n\n return rowPrefixSum\n }\n\n const getColPrefixSum = (k) => {\n const colPrefixSum = [[factors(grid[0][0], k)]]\n for (let i = 1; i < m; i++) {\n colPrefixSum.push([factors(grid[i][0], k) + colPrefixSum[i - 1][0]])\n }\n\n for (let j = 1; j < n; j++) {\n colPrefixSum[0][j] = factors(grid[0][j], k)\n for (let i = 1; i < m; i++) {\n colPrefixSum[i][j] = factors(grid[i][j], k) + colPrefixSum[i - 1][j]\n }\n }\n\n return colPrefixSum\n }\n\n const twoRow = getRowPrefixSum(2)\n const fiveRow = getRowPrefixSum(5)\n const twoCol = getColPrefixSum(2)\n const fiveCol = getColPrefixSum(5)\n\n let max = 0\n\n // now check every cell in the whole grid\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n const twoLeft = twoRow[i][j]\n const twoRight = twoRow[i][n - 1] - (j && twoRow[i][j - 1])\n const twoUp = i && twoCol[i - 1][j]\n const twoDown = twoCol[m - 1][j] - twoCol[i][j]\n\n const fiveLeft = fiveRow[i][j]\n const fiveRight = fiveRow[i][n - 1] - (j && fiveRow[i][j - 1])\n const fiveUp = i && fiveCol[i - 1][j]\n const fiveDown = fiveCol[m - 1][j] - fiveCol[i][j]\n\n const corneredPaths = [\n Math.min(twoLeft + twoUp, fiveLeft + fiveUp),\n Math.min(twoLeft + twoDown, fiveLeft + fiveDown),\n Math.min(twoRight + twoUp, fiveRight + fiveUp),\n Math.min(twoRight + twoDown, fiveRight + fiveDown),\n ]\n\n const trailingZeros = Math.max(...corneredPaths)\n\n if (trailingZeros > max) {\n max = trailingZeros\n }\n }\n }\n\n return max\n}",
"const maxTrailingZeros = function(grid) {\n const g = grid\n const m = g.length;\n const n = g[0].length;\n const ta = [...Array(m)].map(i => Array(n).fill(1));\n const tb = [...Array(m)].map(i => Array(n).fill(1));\n const tc = [...Array(m)].map(i => Array(n).fill(1));\n const td = [...Array(m)].map(i => Array(n).fill(1));\n \n const c52 = (s) => {\n let c5 = 0;\n let c2 = 0;\n while (s % 2 === 0) {\n s = s / 2;\n c2++;\n }\n while (s % 5 === 0) {\n s = s / 5;\n c5++;\n }\n return [c5, c2];\n }\n \n const c10 = ([c5, c2]) => {\n return Math.min(c5, c2);\n }\n \n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n ta[i][j] = (j === 0) ? c52(g[i][j]) : [c52(g[i][j])[0] + ta[i][j-1][0], c52(g[i][j])[1] + ta[i][j-1][1]];\n tb[i][j] = (i === 0) ? c52(g[i][j]) : [c52(g[i][j])[0] + tb[i-1][j][0], c52(g[i][j])[1] + tb[i-1][j][1]];\n }\n }\n \n for (let i = m-1; i >= 0; i--) {\n for (let j = n-1; j >= 0; j--) {\n tc[i][j] = (j === n-1) ? c52(g[i][j]) : [c52(g[i][j])[0] + tc[i][j+1][0], c52(g[i][j])[1] + tc[i][j+1][1]]; // : ctz(hg(g[i][j]) * tc[i][j+1][0], tc[i][j+1][1]); // hg(g[i][j]) * tc[i][j+1];\n td[i][j] = (i === m-1) ? c52(g[i][j]) : [c52(g[i][j])[0] + td[i+1][j][0], c52(g[i][j])[1] + td[i+1][j][1]]; // : ctz(hg(g[i][j]) * td[i+1][j][0], td[i+1][j][1]); // hg(g[i][j]) * td[i+1][j];\n }\n }\n \n let ret = 0;\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n let s1 = i === 0 ? c10(ta[i][j]) : c10([ta[i][j][0] + tb[i-1][j][0], ta[i][j][1] + tb[i-1][j][1]]);\n let s2 = i === m - 1 ? c10(ta[i][j]) : c10([ta[i][j][0] + td[i+1][j][0], ta[i][j][1] + td[i+1][j][1]]); \n let s3 = i === 0 ? c10(tc[i][j]) : c10([tc[i][j][0] + tb[i-1][j][0], tc[i][j][1] + tb[i-1][j][1]]);\n let s4 = i === m - 1 ? c10(tc[i][j]) : c10([tc[i][j][0] + td[i+1][j][0], tc[i][j][1] + td[i+1][j][1]]); \n ret = Math.max(ret, s1, s2, s3, s4);\n }\n }\n return ret;\n};"
] |
|
2,246 | longest-path-with-different-adjacent-characters | [
"Do a DFS from the root. At each node, calculate the longest path we can make from two branches of that subtree.",
"To do that, we need to find the length of the longest path from each of the node’s children."
] | /**
* @param {number[]} parent
* @param {string} s
* @return {number}
*/
var longestPath = function(parent, s) {
}; | You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.
You are also given a string s of length n, where s[i] is the character assigned to node i.
Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.
Example 1:
Input: parent = [-1,0,0,1,1,2], s = "abacbe"
Output: 3
Explanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.
It can be proven that there is no longer path that satisfies the conditions.
Example 2:
Input: parent = [-1,0,0,0], s = "aabc"
Output: 3
Explanation: The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.
Constraints:
n == parent.length == s.length
1 <= n <= 105
0 <= parent[i] <= n - 1 for all i >= 1
parent[0] == -1
parent represents a valid tree.
s consists of only lowercase English letters.
| Hard | [
"array",
"string",
"tree",
"depth-first-search",
"graph",
"topological-sort"
] | [
"var longestPath = function(parent, s) {\n const n = parent.length\n const hash = {}\n for(let i = 1; i < n; i++) {\n if(hash[parent[i]] == null) hash[parent[i]] = []\n hash[parent[i]].push(i)\n }\n\n let res = 0\n dfs(0)\n return res\n \n function dfs(i) {\n let max1 = 0, max2 = 0\n for(const j of (hash[i] || [])) {\n const len = dfs(j)\n if(s[i] === s[j]) continue\n if(len > max1) {\n const tmp = max1\n max1 = len\n max2 = tmp\n } else if(len > max2) {\n max2 = len\n }\n }\n res = Math.max(res, max1 + max2 + 1) \n return max1 + 1\n }\n};",
"var longestPath = function(parent, s) {\n let n = s.length, res = 0;\n const {max} = Math\n let children = Array.from({ length: n}, () => Array());\n for (let i = 1; i < n; ++i) children[parent[i]].push(i);\n dfs(children, s, 0);\n return res;\n \n function dfs(children, s, i) {\n let big1 = 0, big2 = 0;\n for (let j of (children[i] || [])) {\n let cur = dfs(children, s, j);\n if (s[i] == s[j]) continue;\n if (cur > big2) big2 = cur;\n if (big2 > big1) {\n let tmp = big1\n big1 = big2\n big2 = tmp\n };\n }\n res = max(res, big1 + big2 + 1);\n return big1 + 1;\n } \n};"
] |
|
2,248 | intersection-of-multiple-arrays | [
"Keep a count of the number of times each integer occurs in nums.",
"Since all integers of nums[i] are distinct, if an integer is present in each array, its count will be equal to the total number of arrays."
] | /**
* @param {number[][]} nums
* @return {number[]}
*/
var intersection = function(nums) {
}; | Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order.
Example 1:
Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]
Output: [3,4]
Explanation:
The only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4].
Example 2:
Input: nums = [[1,2,3],[4,5,6]]
Output: []
Explanation:
There does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].
Constraints:
1 <= nums.length <= 1000
1 <= sum(nums[i].length) <= 1000
1 <= nums[i][j] <= 1000
All the values of nums[i] are unique.
| Easy | [
"array",
"hash-table",
"counting"
] | [
"var intersection = function(nums) {\n let set = new Set(nums[0])\n for (let i = 1; i < nums.length; i++) {\n const r = nums[i]\n const tmp = new Set()\n for(let e of r) {\n if(set.has(e)) tmp.add(e)\n }\n set = tmp\n }\n return Array.from(set).sort((a, b) => a - b)\n};"
] |
|
2,249 | count-lattice-points-inside-a-circle | [
"For each circle, how can you check whether or not a lattice point lies inside it?",
"Since you need to reduce the search space, consider the minimum and maximum possible values of the coordinates of a lattice point contained in any circle."
] | /**
* @param {number[][]} circles
* @return {number}
*/
var countLatticePoints = function(circles) {
}; | Given a 2D integer array circles where circles[i] = [xi, yi, ri] represents the center (xi, yi) and radius ri of the ith circle drawn on a grid, return the number of lattice points that are present inside at least one circle.
Note:
A lattice point is a point with integer coordinates.
Points that lie on the circumference of a circle are also considered to be inside it.
Example 1:
Input: circles = [[2,2,1]]
Output: 5
Explanation:
The figure above shows the given circle.
The lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green.
Other points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle.
Hence, the number of lattice points present inside at least one circle is 5.
Example 2:
Input: circles = [[2,2,2],[3,4,1]]
Output: 16
Explanation:
The figure above shows the given circles.
There are exactly 16 lattice points which are present inside at least one circle.
Some of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4).
Constraints:
1 <= circles.length <= 200
circles[i].length == 3
1 <= xi, yi <= 100
1 <= ri <= min(xi, yi)
| Medium | [
"array",
"hash-table",
"math",
"geometry",
"enumeration"
] | [
"var countLatticePoints = function(circles) {\n const set = new Set()\n for(let arr of circles) helper(arr)\n return set.size\n \n function helper(arr) {\n const [cx, cy, r] = arr\n let bottomLeftX = cx - r, bottomLeftY = cy - r\n let topRightX = cx + r, topRightY = cy + r\n for(let i = bottomLeftX; i <= topRightX; i++) {\n for(let j = bottomLeftY; j <= topRightY; j++) {\n if (Math.sqrt((i - cx) ** 2 + (j - cy) ** 2) <= r) {\n set.add(`${i},${j}`)\n }\n }\n }\n }\n};"
] |
|
2,250 | count-number-of-rectangles-containing-each-point | [
"The heights of the rectangles and the y-coordinates of the points are only at most 100, so for each point, we can iterate over the possible heights of the rectangles that contain a given point.",
"For a given point and height, can we efficiently count how many rectangles with that height contain our point?",
"Sort the rectangles at each height and use binary search."
] | /**
* @param {number[][]} rectangles
* @param {number[][]} points
* @return {number[]}
*/
var countRectangles = function(rectangles, points) {
}; | You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith rectangle has a length of li and a height of hi. You are also given a 2D integer array points where points[j] = [xj, yj] is a point with coordinates (xj, yj).
The ith rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right corner point at (li, hi).
Return an integer array count of length points.length where count[j] is the number of rectangles that contain the jth point.
The ith rectangle contains the jth point if 0 <= xj <= li and 0 <= yj <= hi. Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle.
Example 1:
Input: rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]]
Output: [2,1]
Explanation:
The first rectangle contains no points.
The second rectangle contains only the point (2, 1).
The third rectangle contains the points (2, 1) and (1, 4).
The number of rectangles that contain the point (2, 1) is 2.
The number of rectangles that contain the point (1, 4) is 1.
Therefore, we return [2, 1].
Example 2:
Input: rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]]
Output: [1,3]
Explanation:
The first rectangle contains only the point (1, 1).
The second rectangle contains only the point (1, 1).
The third rectangle contains the points (1, 3) and (1, 1).
The number of rectangles that contain the point (1, 3) is 1.
The number of rectangles that contain the point (1, 1) is 3.
Therefore, we return [1, 3].
Constraints:
1 <= rectangles.length, points.length <= 5 * 104
rectangles[i].length == points[j].length == 2
1 <= li, xj <= 109
1 <= hi, yj <= 100
All the rectangles are unique.
All the points are unique.
| Medium | [
"array",
"binary-search",
"binary-indexed-tree",
"sorting"
] | [
"const countRectangles = function(rectangles, points) {\n const rect = rectangles\n const matrix = Array.from({ length: 101 }, () => [])\n for(const [x, y] of rect) {\n matrix[y].push(x)\n }\n for(const row of matrix) row.sort((a, b) => a - b)\n const res = []\n \n for(const [x, y] of points) {\n \n let cnt = 0\n for(let i = y; i <= 100; i++) {\n const arr = matrix[i], n = arr.length\n let l = 0, r = n\n while(l < r) {\n const mid = l + Math.floor((r - l) / 2)\n if(mid === n || arr[mid] >= x) r = mid\n else l = mid + 1\n }\n cnt += n - l\n }\n \n res.push(cnt)\n }\n \n return res\n};",
"function countRectangles(rect, points) {\n const hash = {}\n for(let [y, x] of rect) {\n if(hash[x] == null) hash[x] = []\n hash[x].push(y)\n }\n const keys = Object.keys(hash).map(e => +e)\n for(const k of keys) {\n hash[k].sort((a, b) => a - b)\n }\n keys.sort((a, b) => a - b)\n const res = []\n const n = keys.length\n // console.log(keys, hash)\n for(const [y, x] of points) {\n let v = 0\n const idx = helper(keys, x)\n for(let i = idx; i < n; i++) {\n const k = keys[i]\n const p = helper(hash[k], y)\n v += p === hash[k].length ? 0 : hash[k].length - p\n }\n res.push(v)\n }\n\n return res\n\n function helper(arr, val) {\n let l = 0, r = arr.length\n while(l < r) {\n const mid = l + Math.floor((r - l) / 2)\n if(valid(mid)) r = mid\n else l = mid + 1\n }\n // console.log(arr, val, l)\n return l\n\n function valid(mid) {\n return arr[mid] >= val\n }\n }\n}"
] |
|
2,251 | number-of-flowers-in-full-bloom | [
"Notice that for any given time t, the number of flowers blooming at time t is equal to the number of flowers that have started blooming minus the number of flowers that have already stopped blooming.",
"We can obtain these values efficiently using binary search.",
"We can store the starting times in sorted order, which then allows us to binary search to find how many flowers have started blooming for a given time t.",
"We do the same for the ending times to find how many flowers have stopped blooming at time t."
] | /**
* @param {number[][]} flowers
* @param {number[]} people
* @return {number[]}
*/
var fullBloomFlowers = function(flowers, people) {
}; | You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where poeple[i] is the time that the ith person will arrive to see the flowers.
Return an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.
Example 1:
Input: flowers = [[1,6],[3,7],[9,12],[4,13]], poeple = [2,3,7,11]
Output: [1,2,2,2]
Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.
For each person, we return the number of flowers in full bloom during their arrival.
Example 2:
Input: flowers = [[1,10],[3,3]], poeple = [3,3,2]
Output: [2,2,1]
Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.
For each person, we return the number of flowers in full bloom during their arrival.
Constraints:
1 <= flowers.length <= 5 * 104
flowers[i].length == 2
1 <= starti <= endi <= 109
1 <= people.length <= 5 * 104
1 <= people[i] <= 109
| Hard | [
"array",
"hash-table",
"binary-search",
"sorting",
"prefix-sum",
"ordered-set"
] | [
"const fullBloomFlowers = function(flowers, persons) {\n const arr = []\n for(const [s, e] of flowers) {\n arr.push([s, 1])\n arr.push([e, 3])\n }\n for(let i = 0; i < persons.length; i++) {\n arr.push([persons[i], 2, i])\n }\n arr.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])\n const res = []\n let cnt = 0\n for(let e of arr) {\n if(e[1] === 1) cnt++\n else if(e[1] === 3) cnt--\n else {\n res[e[2]] = cnt\n }\n }\n\n return res\n};"
] |
|
2,255 | count-prefixes-of-a-given-string | [
"For each string in words, check if it is a prefix of s. If true, increment the answer by 1."
] | /**
* @param {string[]} words
* @param {string} s
* @return {number}
*/
var countPrefixes = function(words, s) {
}; | You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.
Return the number of strings in words that are a prefix of s.
A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.
Example 1:
Input: words = ["a","b","c","ab","bc","abc"], s = "abc"
Output: 3
Explanation:
The strings in words which are a prefix of s = "abc" are:
"a", "ab", and "abc".
Thus the number of strings in words which are a prefix of s is 3.
Example 2:
Input: words = ["a","a"], s = "aa"
Output: 2
Explanation:
Both of the strings are a prefix of s.
Note that the same string can occur multiple times in words, and it should be counted each time.
Constraints:
1 <= words.length <= 1000
1 <= words[i].length, s.length <= 10
words[i] and s consist of lowercase English letters only.
| Easy | [
"array",
"string"
] | null | [] |
2,256 | minimum-average-difference | [
"How can we use precalculation to efficiently calculate the average difference at an index?",
"Create a prefix and/or suffix sum array."
] | /**
* @param {number[]} nums
* @return {number}
*/
var minimumAverageDifference = function(nums) {
}; | You are given a 0-indexed integer array nums of length n.
The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.
Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.
Note:
The absolute difference of two numbers is the absolute value of their difference.
The average of n elements is the sum of the n elements divided (integer division) by n.
The average of 0 elements is considered to be 0.
Example 1:
Input: nums = [2,5,3,9,5,3]
Output: 3
Explanation:
- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.
- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.
- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.
- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.
- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.
- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.
The average difference of index 3 is the minimum average difference so return 3.
Example 2:
Input: nums = [0]
Output: 0
Explanation:
The only index is 0 so return 0.
The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 105
| Medium | [
"array",
"prefix-sum"
] | null | [] |
2,257 | count-unguarded-cells-in-the-grid | [
"Create a 2D array to represent the grid. Can you mark the tiles that can be seen by a guard?",
"Iterate over the guards, and for each of the 4 directions, advance the current tile and mark the tile. When should you stop advancing?"
] | /**
* @param {number} m
* @param {number} n
* @param {number[][]} guards
* @param {number[][]} walls
* @return {number}
*/
var countUnguarded = function(m, n, guards, walls) {
}; | You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively.
A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it.
Return the number of unoccupied cells that are not guarded.
Example 1:
Input: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]
Output: 7
Explanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram.
There are a total of 7 unguarded cells, so we return 7.
Example 2:
Input: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]
Output: 4
Explanation: The unguarded cells are shown in green in the above diagram.
There are a total of 4 unguarded cells, so we return 4.
Constraints:
1 <= m, n <= 105
2 <= m * n <= 105
1 <= guards.length, walls.length <= 5 * 104
2 <= guards.length + walls.length <= m * n
guards[i].length == walls[j].length == 2
0 <= rowi, rowj < m
0 <= coli, colj < n
All the positions in guards and walls are unique.
| Medium | [
"array",
"matrix",
"simulation"
] | null | [] |
2,258 | escape-the-spreading-fire | [
"For some tile (x, y), how can we determine when, if ever, the fire will reach it?",
"We can use multi-source BFS to find the earliest time the fire will reach each cell.",
"Then, starting with a given t minutes of staying in the initial position, we can check if there is a safe path to the safehouse using the obtained information about the fire.",
"We can use binary search to efficiently find the maximum t that allows us to reach the safehouse."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var maximumMinutes = function(grid) {
}; | You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values:
0 represents grass,
1 represents fire,
2 represents a wall that you and fire cannot pass through.
You are situated in the top-left cell, (0, 0), and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1). Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls.
Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse. If this is impossible, return -1. If you can always reach the safehouse regardless of the minutes stayed, return 109.
Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse.
A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).
Example 1:
Input: grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]]
Output: 3
Explanation: The figure above shows the scenario where you stay in the initial position for 3 minutes.
You will still be able to safely reach the safehouse.
Staying for more than 3 minutes will not allow you to safely reach the safehouse.
Example 2:
Input: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]
Output: -1
Explanation: The figure above shows the scenario where you immediately move towards the safehouse.
Fire will spread to any cell you move towards and it is impossible to safely reach the safehouse.
Thus, -1 is returned.
Example 3:
Input: grid = [[0,0,0],[2,2,0],[1,2,0]]
Output: 1000000000
Explanation: The figure above shows the initial grid.
Notice that the fire is contained by walls and you will always be able to safely reach the safehouse.
Thus, 109 is returned.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 300
4 <= m * n <= 2 * 104
grid[i][j] is either 0, 1, or 2.
grid[0][0] == grid[m - 1][n - 1] == 0
| Hard | [
"array",
"binary-search",
"breadth-first-search",
"matrix"
] | [
"const maximumMinutes = function (grid) {\n const [m, n] = [grid.length, grid[0].length]\n const dir = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ]\n\n function isValidCell(x, y) {\n return x >= 0 && x < m && y >= 0 && y < n\n }\n\n const fireDist = new Array(m)\n for (let i = 0; i < m; i++) {\n fireDist[i] = new Array(n).fill(Infinity)\n }\n\n const firePoints = []\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 1) {\n firePoints.push([i, j])\n fireDist[i][j] = 0\n }\n }\n }\n\n while (firePoints.length) {\n const [x0, y0] = firePoints.shift()\n\n for (const [dx, dy] of dir) {\n const [x1, y1] = [x0 + dx, y0 + dy]\n\n if (\n isValidCell(x1, y1) &&\n grid[x1][y1] === 0 &&\n fireDist[x0][y0] + 1 < fireDist[x1][y1]\n ) {\n fireDist[x1][y1] = fireDist[x0][y0] + 1\n firePoints.push([x1, y1])\n }\n }\n }\n\n function canEscape(delay) {\n const visited = new Array(m)\n for (let i = 0; i < m; i++) {\n visited[i] = new Array(n).fill(false)\n }\n\n const queue = [[0, 0]]\n let currMinutes = delay\n\n while (queue.length) {\n currMinutes++\n\n for (let i = queue.length; i > 0; i--) {\n const [i0, j0] = queue.shift()\n visited[i0][j0] = true\n\n for (const [di, dj] of dir) {\n const [i1, j1] = [i0 + di, j0 + dj]\n\n if (\n isValidCell(i1, j1) &&\n grid[i1][j1] === 0 &&\n !visited[i1][j1] &&\n (currMinutes < fireDist[i1][j1] ||\n (currMinutes === fireDist[i1][j1] &&\n i1 === m - 1 &&\n j1 === n - 1))\n ) {\n if (i1 === m - 1 && j1 === n - 1) {\n return true\n }\n queue.push([i1, j1])\n }\n }\n }\n }\n\n return false\n }\n\n let [left, right] = [-1, 1_000_000_000]\n\n while (left < right) {\n const middle = Math.floor((left + right + 1) / 2)\n\n if (canEscape(middle)) {\n left = middle\n } else {\n right = middle - 1\n }\n }\n\n return left\n}"
] |
|
2,259 | remove-digit-from-number-to-maximize-result | [
"The maximum length of number is really small.",
"Iterate through the digits of number and every time we see digit, try removing it.",
"To remove a character at index i, concatenate the substring from index 0 to i - 1 and the substring from index i + 1 to number.length - 1."
] | /**
* @param {string} number
* @param {character} digit
* @return {string}
*/
var removeDigit = function(number, digit) {
}; | You are given a string number representing a positive integer and a character digit.
Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in number.
Example 1:
Input: number = "123", digit = "3"
Output: "12"
Explanation: There is only one '3' in "123". After removing '3', the result is "12".
Example 2:
Input: number = "1231", digit = "1"
Output: "231"
Explanation: We can remove the first '1' to get "231" or remove the second '1' to get "123".
Since 231 > 123, we return "231".
Example 3:
Input: number = "551", digit = "5"
Output: "51"
Explanation: We can remove either the first or second '5' from "551".
Both result in the string "51".
Constraints:
2 <= number.length <= 100
number consists of digits from '1' to '9'.
digit is a digit from '1' to '9'.
digit occurs at least once in number.
| Easy | [
"string",
"greedy",
"enumeration"
] | [
"const removeDigit = function(number, digit) {\n const arr = number.split('')\n const idxArr = []\n arr.forEach((e,i) => {\n if(e === digit) idxArr.push(i)\n })\n const res = []\n for(const i of idxArr) {\n const clone = arr.slice()\n clone.splice(i, 1)\n res.push(clone.join(''))\n }\n return res.reduce((ac, e) => e > ac ? e : ac, res[0])\n};"
] |
|
2,260 | minimum-consecutive-cards-to-pick-up | [
"Iterate through the cards and store the location of the last occurrence of each number.",
"What data structure could you use to get the last occurrence of a number in O(1) or O(log n)?"
] | /**
* @param {number[]} cards
* @return {number}
*/
var minimumCardPickup = function(cards) {
}; | You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value.
Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1.
Example 1:
Input: cards = [3,4,2,3,4,7]
Output: 4
Explanation: We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal.
Example 2:
Input: cards = [1,0,5,3]
Output: -1
Explanation: There is no way to pick up a set of consecutive cards that contain a pair of matching cards.
Constraints:
1 <= cards.length <= 105
0 <= cards[i] <= 106
| Medium | [
"array",
"hash-table",
"sliding-window"
] | [
"var minimumCardPickup = function(cards) {\n const hash = {}, n = cards.length\n for(let i = 0; i < n; i++) {\n const cur = cards[i]\n if(hash[cur] == null) hash[cur] = []\n hash[cur].push(i)\n }\n let res = Infinity\n \n Object.keys(hash).forEach(k => {\n const arr = hash[k]\n const len = arr.length\n for(let i = 1; i < len; i++) {\n res = Math.min(res, arr[i] - arr[i - 1] + 1)\n }\n \n })\n \n \n return res === Infinity ? -1 : res\n};"
] |
|
2,261 | k-divisible-elements-subarrays | [
"Enumerate all subarrays and find the ones that satisfy all the conditions.",
"Use any suitable method to hash the subarrays to avoid duplicates."
] | /**
* @param {number[]} nums
* @param {number} k
* @param {number} p
* @return {number}
*/
var countDistinct = function(nums, k, p) {
}; | Given an integer array nums and two integers k and p, return the number of distinct subarrays, which have at most k elements that are divisible by p.
Two arrays nums1 and nums2 are said to be distinct if:
They are of different lengths, or
There exists at least one index i where nums1[i] != nums2[i].
A subarray is defined as a non-empty contiguous sequence of elements in an array.
Example 1:
Input: nums = [2,3,3,2,2], k = 2, p = 2
Output: 11
Explanation:
The elements at indices 0, 3, and 4 are divisible by p = 2.
The 11 distinct subarrays which have at most k = 2 elements divisible by 2 are:
[2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2].
Note that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once.
The subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2.
Example 2:
Input: nums = [1,2,3,4], k = 4, p = 1
Output: 10
Explanation:
All element of nums are divisible by p = 1.
Also, every subarray of nums will have at most 4 elements that are divisible by 1.
Since all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.
Constraints:
1 <= nums.length <= 200
1 <= nums[i], p <= 200
1 <= k <= nums.length
Follow up:
Can you solve this problem in O(n2) time complexity?
| Medium | [
"array",
"hash-table",
"trie",
"rolling-hash",
"hash-function",
"enumeration"
] | [
"const countDistinct = function(nums, k, p) {\n let ans = 0;\n const se = new Set();\n let n = nums.length;\n for (let i = 0; i < n; i++) {\n let tmp = \"\";\n let cnt = 0;\n for (let j = i; j < n; j++) {\n if (nums[j] % p == 0)\n cnt++;\n if (cnt <= k) {\n tmp = tmp + (nums[j]) + \"-\";\n se.add(tmp);\n } else break;\n }\n }\n return se.size;\n};"
] |
|
2,262 | total-appeal-of-a-string | [
"Consider the set of substrings that end at a certain index i. Then, consider a specific alphabetic character. How do you count the number of substrings ending at index i that contain that character?",
"The number of substrings that contain the alphabetic character is equivalent to 1 plus the index of the last occurrence of the character before index i + 1.",
"The total appeal of all substrings ending at index i is the total sum of the number of substrings that contain each alphabetic character.",
"To find the total appeal of all substrings, we simply sum up the total appeal for each index."
] | /**
* @param {string} s
* @return {number}
*/
var appealSum = function(s) {
}; | The appeal of a string is the number of distinct characters found in the string.
For example, the appeal of "abbca" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'.
Given a string s, return the total appeal of all of its substrings.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "abbca"
Output: 28
Explanation: The following are the substrings of "abbca":
- Substrings of length 1: "a", "b", "b", "c", "a" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5.
- Substrings of length 2: "ab", "bb", "bc", "ca" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7.
- Substrings of length 3: "abb", "bbc", "bca" have an appeal of 2, 2, and 3 respectively. The sum is 7.
- Substrings of length 4: "abbc", "bbca" have an appeal of 3 and 3 respectively. The sum is 6.
- Substrings of length 5: "abbca" has an appeal of 3. The sum is 3.
The total sum is 5 + 7 + 7 + 6 + 3 = 28.
Example 2:
Input: s = "code"
Output: 20
Explanation: The following are the substrings of "code":
- Substrings of length 1: "c", "o", "d", "e" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4.
- Substrings of length 2: "co", "od", "de" have an appeal of 2, 2, and 2 respectively. The sum is 6.
- Substrings of length 3: "cod", "ode" have an appeal of 3 and 3 respectively. The sum is 6.
- Substrings of length 4: "code" has an appeal of 4. The sum is 4.
The total sum is 4 + 6 + 6 + 4 = 20.
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
| Hard | [
"hash-table",
"string",
"dynamic-programming"
] | [
"const appealSum = function (s) {\n const n = s.length, pos = Array(26).fill(-1)\n let res = 0\n const a = 'a'.charCodeAt(0)\n for(let i = 0; i < n; i++) {\n let tmp = n - i, idx = s.charCodeAt(i) - a\n if(pos[idx] !== -1) {\n tmp += (i - pos[idx] - 1) * (n - i)\n } else tmp += i * (n - i)\n res += tmp\n pos[idx] = i\n }\n \n return res\n}",
"var appealSum = function(s) {\n const cnt = Array(26).fill(-1);\n let ans = 0;\n let n = s.length;\n const a = 'a'.charCodeAt(0)\n for (let i = 0; i < n; i++) {\n let tmp = n - i;\n if (cnt[s[i].charCodeAt(0) - a] !== -1) tmp += (i - cnt[s[i].charCodeAt(0) - a] - 1) * (n - i);\n else tmp += i * (n - i);\n ans += tmp;\n cnt[s[i].charCodeAt(0) - a] = i;\n }\n return ans;\n};"
] |
|
2,264 | largest-3-same-digit-number-in-string | [
"We can sequentially check if “999”, “888”, “777”, … , “000” exists in num in that order. The first to be found is the maximum good integer.",
"If we cannot find any of the above integers, we return an empty string “”."
] | /**
* @param {string} num
* @return {string}
*/
var largestGoodInteger = function(num) {
}; | You are given a string num representing a large integer. An integer is good if it meets the following conditions:
It is a substring of num with length 3.
It consists of only one unique digit.
Return the maximum good integer as a string or an empty string "" if no such integer exists.
Note:
A substring is a contiguous sequence of characters within a string.
There may be leading zeroes in num or a good integer.
Example 1:
Input: num = "6777133339"
Output: "777"
Explanation: There are two distinct good integers: "777" and "333".
"777" is the largest, so we return "777".
Example 2:
Input: num = "2300019"
Output: "000"
Explanation: "000" is the only good integer.
Example 3:
Input: num = "42352338"
Output: ""
Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.
Constraints:
3 <= num.length <= 1000
num only consists of digits.
| Easy | [
"string"
] | [
"var largestGoodInteger = function(num) {\n let res = ''\n const n = num.length\n const isDigit = ch => ch >= '0' && ch <= '9'\n for(let i = 1; i < n - 1; i++) {\n const ch = num[i]\n if(!isDigit(ch)) continue\n if(!isDigit(num[i - 1])) continue\n if(!isDigit(num[i + 1])) continue\n if(num[i - 1] == num[i] && num[i] === num[i + 1]) {\n if(ch.repeat(3) > res) res = ch.repeat(3)\n }\n }\n \n return res\n};"
] |
|
2,265 | count-nodes-equal-to-average-of-subtree | [
"What information do we need to calculate the average? We need the sum of the values and the number of values.",
"Create a recursive function that returns the size of a node’s subtree, and the sum of the values of its subtree."
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var averageOfSubtree = function(root) {
}; | Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree.
Note:
The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.
A subtree of root is a tree consisting of root and all of its descendants.
Example 1:
Input: root = [4,8,5,0,1,null,6]
Output: 5
Explanation:
For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.
For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.
For the node with value 0: The average of its subtree is 0 / 1 = 0.
For the node with value 1: The average of its subtree is 1 / 1 = 1.
For the node with value 6: The average of its subtree is 6 / 1 = 6.
Example 2:
Input: root = [1]
Output: 1
Explanation: For the node with value 1: The average of its subtree is 1 / 1 = 1.
Constraints:
The number of nodes in the tree is in the range [1, 1000].
0 <= Node.val <= 1000
| Medium | [
"tree",
"depth-first-search",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"var averageOfSubtree = function(root) {\n let res = 0\n dfs(root)\n return res\n \n function dfs(node) {\n if(node == null) return [0, 0]\n let [lSum, lNum] = dfs(node.left)\n let [rSum, rNum] = dfs(node.right)\n if(node.val === Math.floor((node.val + lSum + rSum) / (lNum + rNum + 1))) {\n res++\n }\n return [node.val + lSum + rSum, lNum + rNum + 1]\n }\n};"
] |
2,266 | count-number-of-texts | [
"For a substring consisting of the same digit, how can we count the number of texts it could have originally represented?",
"How can dynamic programming help us calculate the required answer?"
] | /**
* @param {string} pressedKeys
* @return {number}
*/
var countTexts = function(pressedKeys) {
}; | Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below.
In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key.
For example, to add the letter 's', Alice has to press '7' four times. Similarly, to add the letter 'k', Alice has to press '5' twice.
Note that the digits '0' and '1' do not map to any letters, so Alice does not use them.
However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead.
For example, when Alice sent the message "bob", Bob received the string "2266622".
Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: pressedKeys = "22233"
Output: 8
Explanation:
The possible text messages Alice could have sent are:
"aaadd", "abdd", "badd", "cdd", "aaae", "abe", "bae", and "ce".
Since there are 8 possible messages, we return 8.
Example 2:
Input: pressedKeys = "222222222222222222222222222222222222"
Output: 82876089
Explanation:
There are 2082876103 possible text messages Alice could have sent.
Since we need to return the answer modulo 109 + 7, we return 2082876103 % (109 + 7) = 82876089.
Constraints:
1 <= pressedKeys.length <= 105
pressedKeys only consists of digits from '2' - '9'.
| Medium | [
"hash-table",
"math",
"string",
"dynamic-programming"
] | [
"var countTexts = function(pressedKeys) {\n const s = pressedKeys\n const mod = 1e9 + 7\n\n let n = s.length\n let dp = Array(n + 1).fill(0)\n dp[0] = 1\n dp[1] = 1\n let counter = Array(10).fill(3)\n counter[0] = 0\n counter[1] = 0\n counter[7] = 4\n counter[9] = 4\n for(let i = 2; i <= n; i++) {\n let x = +(s[i - 1])\n let j = 0\n while (j < counter[x] && i - 1 >= j && s[i - 1 - j] == s[i - 1]) {\n dp[i] += dp[i - 1 - j]\n j += 1 \n }\n\n dp[i] %= mod\n }\n\n return dp[n]\n \n};"
] |
|
2,267 | check-if-there-is-a-valid-parentheses-string-path | [
"What observations can you make about the number of open brackets and close brackets for any prefix of a valid bracket sequence?",
"The number of open brackets must always be greater than or equal to the number of close brackets.",
"Could you use dynamic programming?"
] | /**
* @param {character[][]} grid
* @return {boolean}
*/
var hasValidPath = function(grid) {
}; | A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true:
It is ().
It can be written as AB (A concatenated with B), where A and B are valid parentheses strings.
It can be written as (A), where A is a valid parentheses string.
You are given an m x n matrix of parentheses grid. A valid parentheses string path in the grid is a path satisfying all of the following conditions:
The path starts from the upper left cell (0, 0).
The path ends at the bottom-right cell (m - 1, n - 1).
The path only ever moves down or right.
The resulting parentheses string formed by the path is valid.
Return true if there exists a valid parentheses string path in the grid. Otherwise, return false.
Example 1:
Input: grid = [["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]]
Output: true
Explanation: The above diagram shows two possible paths that form valid parentheses strings.
The first path shown results in the valid parentheses string "()(())".
The second path shown results in the valid parentheses string "((()))".
Note that there may be other valid parentheses string paths.
Example 2:
Input: grid = [[")",")"],["(","("]]
Output: false
Explanation: The two possible paths form the parentheses strings "))(" and ")((". Since neither of them are valid parentheses strings, we return false.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
grid[i][j] is either '(' or ')'.
| Hard | [
"array",
"dynamic-programming",
"matrix"
] | [
"const hasValidPath = function (grid) {\n const m = grid.length\n const n = grid[0].length\n if (grid[0][0] != '(' || grid[m - 1][n - 1] != ')') return false\n const dp = kdArr(-1, [m, n, ~~((m + n) / 2) + 1])\n\n\n function dfs(i, j, left) {\n if (i >= m || j >= n) return false\n if (grid[i][j] === '(') left++\n else left--\n if (left < 0 || left > Math.floor((m + n) / 2)) return false\n if (dp[i][j][left] != -1) return dp[i][j][left]\n if (i == m - 1 && j == n - 1 && left == 0) return (dp[i][j][left] = true)\n return (dp[i][j][left] = dfs(i, j + 1, left) || dfs(i + 1, j, left))\n }\n return dfs(0, 0, 0)\n \n function kdArr(defaultVal, arr) {\n if(arr.length === 1) return Array(arr[0]).fill(defaultVal)\n \n const res = []\n for(let i = 0, len = arr[0]; i < len; i++) {\n res.push(kdArr(defaultVal, arr.slice(1)))\n }\n \n return res\n }\n}",
"var hasValidPath = function(grid) {\n if (grid[0][0] == \")\") return false\n let m = grid.length, n = grid[0].length\n const dirs = [[0, 1], [1, 0]]\n\n if ((m + n - 1) % 2 == 1) return false\n const a = Array.from({ length: m }, () => Array(n).fill(null))\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j] === '(') a[i][j] = 1\n else a[i][j] = -1\n }\n }\n \n \n const visited = new Set([`0,0,1`])\n let q = [[0, 0, 1]]\n\n while (q.length){\n const tmp = []\n for (const [x, y, v] of q) {\n if (`${x},${y},${v}` == `${m - 1},${n - 1},0`) return true\n for (const [dx, dy] of dirs) {\n let i= x + dx, j = y + dy\n if (0 <= i && i < m && 0 <= j && j < n) {\n let v2 = v + a[i][j]\n if (v2 >= 0 && !visited.has(`${i},${j},${v2}`) ) {\n tmp.push([i, j, v2])\n visited.add(`${i},${j},${v2}`) \n }\n \n }\n }\n }\n q = tmp \n }\n return false\n};"
] |
|
2,269 | find-the-k-beauty-of-a-number | [
"We should check all the substrings of num with a length of k and see if it is a divisor of num.",
"We can more easily obtain the substrings by converting num into a string and converting back to an integer to check for divisibility."
] | /**
* @param {number} num
* @param {number} k
* @return {number}
*/
var divisorSubstrings = function(num, k) {
}; | The k-beauty of an integer num is defined as the number of substrings of num when it is read as a string that meet the following conditions:
It has a length of k.
It is a divisor of num.
Given integers num and k, return the k-beauty of num.
Note:
Leading zeros are allowed.
0 is not a divisor of any value.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: num = 240, k = 2
Output: 2
Explanation: The following are the substrings of num of length k:
- "24" from "240": 24 is a divisor of 240.
- "40" from "240": 40 is a divisor of 240.
Therefore, the k-beauty is 2.
Example 2:
Input: num = 430043, k = 2
Output: 2
Explanation: The following are the substrings of num of length k:
- "43" from "430043": 43 is a divisor of 430043.
- "30" from "430043": 30 is not a divisor of 430043.
- "00" from "430043": 0 is not a divisor of 430043.
- "04" from "430043": 4 is not a divisor of 430043.
- "43" from "430043": 43 is a divisor of 430043.
Therefore, the k-beauty is 2.
Constraints:
1 <= num <= 109
1 <= k <= num.length (taking num as a string)
| Easy | [
"math",
"string",
"sliding-window"
] | null | [] |
2,270 | number-of-ways-to-split-array | [
"For any index i, how can we find the sum of the first (i+1) elements from the sum of the first i elements?",
"If the total sum of the array is known, how can we check if the sum of the first (i+1) elements greater than or equal to the remaining elements?"
] | /**
* @param {number[]} nums
* @return {number}
*/
var waysToSplitArray = function(nums) {
}; | You are given a 0-indexed integer array nums of length n.
nums contains a valid split at index i if the following are true:
The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.
There is at least one element to the right of i. That is, 0 <= i < n - 1.
Return the number of valid splits in nums.
Example 1:
Input: nums = [10,4,-8,7]
Output: 2
Explanation:
There are three ways of splitting nums into two non-empty parts:
- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.
- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.
- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.
Thus, the number of valid splits in nums is 2.
Example 2:
Input: nums = [2,3,1,0]
Output: 2
Explanation:
There are two valid splits in nums:
- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split.
- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.
Constraints:
2 <= nums.length <= 105
-105 <= nums[i] <= 105
| Medium | [
"array",
"prefix-sum"
] | [
"var waysToSplitArray = function(nums) {\n let res = 0, sum = 0\n const n = nums.length\n if(n === 0) return res\n const pre = Array(n).fill(0)\n pre[0] = nums[0]\n sum += nums[0]\n for(let i = 1; i < n; i++) {\n pre[i] = nums[i] + pre[i - 1]\n sum += nums[i]\n }\n for(let i = 0; i < n - 1; i++) {\n if(pre[i] >= sum - pre[i]) res++\n }\n \n return res\n};"
] |
|
2,271 | maximum-white-tiles-covered-by-a-carpet | [
"Think about the potential placements of the carpet in an optimal solution.",
"Can we use Prefix Sum and Binary Search to determine how many tiles are covered for a given placement?"
] | /**
* @param {number[][]} tiles
* @param {number} carpetLen
* @return {number}
*/
var maximumWhiteTiles = function(tiles, carpetLen) {
}; | You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in the range li <= j <= ri is colored white.
You are also given an integer carpetLen, the length of a single carpet that can be placed anywhere.
Return the maximum number of white tiles that can be covered by the carpet.
Example 1:
Input: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10
Output: 9
Explanation: Place the carpet starting on tile 10.
It covers 9 white tiles, so we return 9.
Note that there may be other places where the carpet covers 9 white tiles.
It can be shown that the carpet cannot cover more than 9 white tiles.
Example 2:
Input: tiles = [[10,11],[1,1]], carpetLen = 2
Output: 2
Explanation: Place the carpet starting on tile 10.
It covers 2 white tiles, so we return 2.
Constraints:
1 <= tiles.length <= 5 * 104
tiles[i].length == 2
1 <= li <= ri <= 109
1 <= carpetLen <= 109
The tiles are non-overlapping.
| Medium | [
"array",
"binary-search",
"greedy",
"sorting",
"prefix-sum"
] | [
"const maximumWhiteTiles = function (tiles, carpetLen) {\n const sorted = tiles.sort((a, b) => a[0] - b[0])\n let res = 0\n\n let total = 0\n let right = 0\n\n for (let tile of sorted) {\n const start = tile[0]\n const end = start + carpetLen - 1\n while (right < sorted.length && tiles[right][1] < end) {\n total += tiles[right][1] - tiles[right][0] + 1\n right++\n }\n if (right === sorted.length || sorted[right][0] > end) {\n res = Math.max(res, total)\n } else {\n res = Math.max(res, total + (end - tiles[right][0] + 1))\n }\n total -= tile[1] - tile[0] + 1\n }\n\n return res\n}",
"const maximumWhiteTiles = function (tiles, carpetLen) {\n tiles.sort((a, b) => a[0] - b[0])\n let res = 0, total = 0, right = 0\n const n = tiles.length\n for(let i = 0; i < n; i++) {\n const [l, r] = tiles[i]\n const end = l + carpetLen - 1\n while(right < n && tiles[right][1] <= end) {\n total += tiles[right][1] - tiles[right][0] + 1 \n right++\n }\n \n if(right === n || tiles[right][0] > end) {\n res = Math.max(res, total)\n } else {\n res = Math.max(res, total + end - tiles[right][0] + 1)\n }\n \n total -= r - l + 1\n }\n \n return res\n}"
] |
|
2,272 | substring-with-largest-variance | [
"Think about how to solve the problem if the string had only two distinct characters.",
"If we replace all occurrences of the first character by +1 and those of the second character by -1, can we efficiently calculate the largest possible variance of a string with only two distinct characters?",
"Now, try finding the optimal answer by taking all possible pairs of characters into consideration."
] | /**
* @param {string} s
* @return {number}
*/
var largestVariance = function(s) {
}; | The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same.
Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "aababbb"
Output: 3
Explanation:
All possible variances along with their respective substrings are listed below:
- Variance 0 for substrings "a", "aa", "ab", "abab", "aababb", "ba", "b", "bb", and "bbb".
- Variance 1 for substrings "aab", "aba", "abb", "aabab", "ababb", "aababbb", and "bab".
- Variance 2 for substrings "aaba", "ababbb", "abbb", and "babb".
- Variance 3 for substring "babbb".
Since the largest possible variance is 3, we return it.
Example 2:
Input: s = "abcde"
Output: 0
Explanation:
No letter occurs more than once in s, so the variance of every substring is 0.
Constraints:
1 <= s.length <= 104
s consists of lowercase English letters.
| Hard | [
"array",
"dynamic-programming"
] | [
"const largestVariance = (s) => {\n let se = new Set(s),\n n = s.length,\n res = 0\n for (const x of se) {\n // max\n for (const y of se) {\n // min\n if (x != y) {\n let pre = Array(n + 1).fill(0),\n preX,\n preY,\n diff = 0\n for (let i = 0; i < n; i++) {\n if (s[i] == x) {\n preX = i + 1\n diff++\n }\n if (s[i] == y) {\n preY = i + 1\n diff--\n }\n pre[i + 1] = Math.min(pre[i], diff)\n if (preX == undefined || preY == undefined) continue\n res = Math.max(res, diff - pre[Math.min(preX, preY) - 1])\n }\n }\n }\n }\n return res\n}"
] |
|
2,273 | find-resultant-array-after-removing-anagrams | [
"Instead of removing each repeating anagram, try to find all the strings in words which will not be present in the final answer.",
"For every index i, find the largest index j < i such that words[j] will be present in the final answer.",
"Check if words[i] and words[j] are anagrams. If they are, then it can be confirmed that words[i] will not be present in the final answer."
] | /**
* @param {string[]} words
* @return {string[]}
*/
var removeAnagrams = function(words) {
}; | You are given a 0-indexed string array words, where words[i] consists of lowercase English letters.
In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions.
Return words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, "dacb" is an anagram of "abdc".
Example 1:
Input: words = ["abba","baba","bbaa","cd","cd"]
Output: ["abba","cd"]
Explanation:
One of the ways we can obtain the resultant array is by using the following operations:
- Since words[2] = "bbaa" and words[1] = "baba" are anagrams, we choose index 2 and delete words[2].
Now words = ["abba","baba","cd","cd"].
- Since words[1] = "baba" and words[0] = "abba" are anagrams, we choose index 1 and delete words[1].
Now words = ["abba","cd","cd"].
- Since words[2] = "cd" and words[1] = "cd" are anagrams, we choose index 2 and delete words[2].
Now words = ["abba","cd"].
We can no longer perform any operations, so ["abba","cd"] is the final answer.
Example 2:
Input: words = ["a","b","c","d","e"]
Output: ["a","b","c","d","e"]
Explanation:
No two adjacent strings in words are anagrams of each other, so no operations are performed.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
| Easy | [
"array",
"hash-table",
"string",
"sorting"
] | [
"const removeAnagrams = function(words) {\n const res = []\n const n = words.length\n\n for(let i = 0; i < n;) {\n let j = i + 1\n while(j < n && isAna(words[i], words[j])) j++\n res.push(words[i])\n i = j\n }\n return res\n \n function isAna(s1, s2) {\n const arr = Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n for(let i = 0; i < s1.length; i++) {\n arr[s1.charCodeAt(i) - a]++\n }\n for(let i = 0; i < s2.length; i++) {\n arr[s2.charCodeAt(i) - a]--\n }\n for(const e of arr) {\n if(e !== 0) return false\n }\n return true\n }\n};"
] |
|
2,274 | maximum-consecutive-floors-without-special-floors | [
"Say we have a pair of special floors (x, y) with no other special floors in between. There are x - y - 1 consecutive floors in between them without a special floor.",
"Say there are n special floors. After sorting special, we have answer = max(answer, special[i] – special[i – 1] – 1) for all 0 < i ≤ n.",
"However, there are two special cases left to consider: the floors before special[0] and after special[n-1].",
"To consider these cases, we have answer = max(answer, special[0] – bottom, top – special[n-1])."
] | /**
* @param {number} bottom
* @param {number} top
* @param {number[]} special
* @return {number}
*/
var maxConsecutive = function(bottom, top, special) {
}; | Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors, used for relaxation only.
You are given two integers bottom and top, which denote that Alice has rented all the floors from bottom to top (inclusive). You are also given the integer array special, where special[i] denotes a special floor that Alice has designated for relaxation.
Return the maximum number of consecutive floors without a special floor.
Example 1:
Input: bottom = 2, top = 9, special = [4,6]
Output: 3
Explanation: The following are the ranges (inclusive) of consecutive floors without a special floor:
- (2, 3) with a total amount of 2 floors.
- (5, 5) with a total amount of 1 floor.
- (7, 9) with a total amount of 3 floors.
Therefore, we return the maximum number which is 3 floors.
Example 2:
Input: bottom = 6, top = 8, special = [7,6,8]
Output: 0
Explanation: Every floor rented is a special floor, so we return 0.
Constraints:
1 <= special.length <= 105
1 <= bottom <= special[i] <= top <= 109
All the values of special are unique.
| Medium | [
"array",
"sorting"
] | [
"var maxConsecutive = function(bottom, top, special) {\n special.sort((a, b) => a - b)\n let res = 0\n \n if(bottom < special[0]) {\n res = special[0] - bottom\n }\n for(let i = 1; i < special.length; i++) {\n res = Math.max(res, special[i] - special[i - 1] - 1)\n }\n if(top > special[special.length - 1]) {\n res = Math.max(res, top - special[special.length - 1])\n }\n \n return res\n};"
] |
|
2,275 | largest-combination-with-bitwise-and-greater-than-zero | [
"For the bitwise AND to be greater than zero, at least one bit should be 1 for every number in the combination.",
"The candidates are 24 bits long, so for every bit position, we can calculate the size of the largest combination such that the bitwise AND will have a 1 at that bit position."
] | /**
* @param {number[]} candidates
* @return {number}
*/
var largestCombination = function(candidates) {
}; | The bitwise AND of an array nums is the bitwise AND of all integers in nums.
For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1.
Also, for nums = [7], the bitwise AND is 7.
You are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candidates. Each number in candidates may only be used once in each combination.
Return the size of the largest combination of candidates with a bitwise AND greater than 0.
Example 1:
Input: candidates = [16,17,71,62,12,24,14]
Output: 4
Explanation: The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0.
The size of the combination is 4.
It can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.
Note that more than one combination may have the largest size.
For example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0.
Example 2:
Input: candidates = [8,8]
Output: 2
Explanation: The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0.
The size of the combination is 2, so we return 2.
Constraints:
1 <= candidates.length <= 105
1 <= candidates[i] <= 107
| Medium | [
"array",
"hash-table",
"bit-manipulation",
"counting"
] | [
"const largestCombination = function(candidates) {\n let res = 0\n for(let i = 0; i < 25; i++) {\n let tmp = 0, bit = 1 << i\n for(const e of candidates) {\n if((e & bit) !== 0) tmp++\n }\n res = Math.max(res, tmp)\n }\n return res\n};",
"const largestCombination = function(candidates) {\n const arr = Array(24).fill(0), len = 24\n for(const e of candidates) {\n const str = toBin(e)\n for(let n = str.length, i = n - 1; i >= 0; i--) {\n const cur = str[i]\n if(cur === '1') {\n arr[len - 1 - (n - 1 - i)]++\n }\n }\n }\n \n return Math.max(...arr)\n \n function toBin(num) {\n return (num >>> 0).toString(2)\n }\n};"
] |
|
2,276 | count-integers-in-intervals | [
"How can you efficiently add intervals to the set of intervals? Can a data structure like a Binary Search Tree help?",
"How can you ensure that the intervals present in the set are non-overlapping? Try merging the overlapping intervals whenever a new interval is added.",
"How can you update the count of integers present in at least one interval when a new interval is added to the set?"
] |
var CountIntervals = function() {
};
/**
* @param {number} left
* @param {number} right
* @return {void}
*/
CountIntervals.prototype.add = function(left, right) {
};
/**
* @return {number}
*/
CountIntervals.prototype.count = function() {
};
/**
* Your CountIntervals object will be instantiated and called as such:
* var obj = new CountIntervals()
* obj.add(left,right)
* var param_2 = obj.count()
*/ | Given an empty set of intervals, implement a data structure that can:
Add an interval to the set of intervals.
Count the number of integers that are present in at least one interval.
Implement the CountIntervals class:
CountIntervals() Initializes the object with an empty set of intervals.
void add(int left, int right) Adds the interval [left, right] to the set of intervals.
int count() Returns the number of integers that are present in at least one interval.
Note that an interval [left, right] denotes all the integers x where left <= x <= right.
Example 1:
Input
["CountIntervals", "add", "add", "count", "add", "count"]
[[], [2, 3], [7, 10], [], [5, 8], []]
Output
[null, null, null, 6, null, 8]
Explanation
CountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals.
countIntervals.add(2, 3); // add [2, 3] to the set of intervals.
countIntervals.add(7, 10); // add [7, 10] to the set of intervals.
countIntervals.count(); // return 6
// the integers 2 and 3 are present in the interval [2, 3].
// the integers 7, 8, 9, and 10 are present in the interval [7, 10].
countIntervals.add(5, 8); // add [5, 8] to the set of intervals.
countIntervals.count(); // return 8
// the integers 2 and 3 are present in the interval [2, 3].
// the integers 5 and 6 are present in the interval [5, 8].
// the integers 7 and 8 are present in the intervals [5, 8] and [7, 10].
// the integers 9 and 10 are present in the interval [7, 10].
Constraints:
1 <= left <= right <= 109
At most 105 calls in total will be made to add and count.
At least one call will be made to count.
| Hard | [
"design",
"segment-tree",
"ordered-set"
] | [
"var CountIntervals = function() {\n this.intervals = []\n this.ans = 0\n};\n\n\nCountIntervals.prototype.add = function(left, right) {\n let l = 0, r = this.intervals.length\n while (l < r) {\n const m = Math.floor((l + r) / 2)\n if (this.intervals[m][1] >= left) {\n r = m\n } else {\n l = m + 1\n }\n }\n \n let index = l\n while (index < this.intervals.length && this.intervals[index][0] <= right) {\n left = Math.min(left, this.intervals[index][0])\n right = Math.max(right, this.intervals[index][1])\n this.ans -= this.intervals[index][1] - this.intervals[index][0] + 1\n index += 1\n }\n this.ans += right - left + 1\n this.intervals.splice(l, index - l, [left, right])\n};\n\n\n\nCountIntervals.prototype.count = function() {\n return this.ans\n};",
"function binarySearch(l, r, fn) {\n while (l <= r) {\n const m = Math.floor((l + r) / 2)\n if (fn(m)) {\n l = m + 1\n } else {\n r = m - 1\n }\n }\n return r\n}\n\nvar CountIntervals = function () {\n this.intervals = []\n this.size = 0\n}\n\n\nCountIntervals.prototype.add = function (left, right) {\n const intervals = this.intervals\n if (!intervals.length) {\n intervals.push({ left, right })\n this.size += right - left + 1\n } else if (left > intervals[intervals.length - 1].right) {\n intervals.push({ left, right })\n this.size += right - left + 1\n } else if (right < intervals[0].left) {\n intervals.unshift({ left, right })\n this.size += right - left + 1\n } else {\n const i = binarySearch(0, intervals.length - 1, (x) => {\n return intervals[x].left < left\n })\n let j,\n start,\n end,\n sum = 0\n if (i < 0 || intervals[i].right < left) {\n j = i + 1\n start = left\n end = right\n } else {\n j = i\n start = intervals[j].left\n end = right\n }\n let first = -1\n while (j < intervals.length && right >= intervals[j].left) {\n if (first < 0) first = j\n end = Math.max(end, intervals[j].right)\n sum += intervals[j].right - intervals[j].left + 1\n j++\n }\n // delete [first, j)\n // console.log('delete', j - first, '-', first, j)\n this.size += end - start + 1 - sum\n if (first < 0) {\n this.intervals.splice(i + 1, 0, { left: start, right: end })\n } else {\n this.intervals.splice(first, j - first, { left: start, right: end })\n }\n }\n}\n\n\nCountIntervals.prototype.count = function () {\n return this.size\n}",
"var CountIntervals = function () {\n this.root = new Node(1, 10 ** 9)\n}\n\n\nCountIntervals.prototype.add = function (left, right) {\n this.root.addInterval(left, right)\n}\n\n\nCountIntervals.prototype.count = function () {\n return this.root.total\n}\n\n\n\nclass Node {\n constructor(min, max) {\n this.min = min\n this.max = max\n this.currentMin = -1\n this.currentMax = -1\n this.total = 0\n this.left = null\n this.right = null\n }\n\n addInterval(left, right) {\n if (this.currentMin < 0) {\n this.currentMin = left\n this.currentMax = right\n this.total = right - left + 1\n return this.total\n }\n\n const mid = (this.min + this.max) >> 1\n\n if (this.left) {\n if (left <= mid) this.left.addInterval(left, Math.min(mid, right))\n if (right > mid) this.right.addInterval(Math.max(mid + 1, left), right)\n\n this.total = this.left.total + this.right.total\n return\n }\n\n if (left <= this.currentMax + 1 && right >= this.currentMin - 1) {\n this.currentMin = Math.min(this.currentMin, left)\n this.currentMax = Math.max(this.currentMax, right)\n this.total = this.currentMax - this.currentMin + 1\n return\n }\n this.left = new Node(this.min, mid)\n this.right = new Node(mid + 1, this.max)\n\n if (left <= mid) this.left.addInterval(left, Math.min(mid, right))\n if (right > mid) this.right.addInterval(Math.max(left, mid + 1), right)\n if (this.currentMin <= mid)\n this.left.addInterval(this.currentMin, Math.min(mid, this.currentMax))\n if (this.currentMax > mid)\n this.right.addInterval(\n Math.max(mid + 1, this.currentMin),\n this.currentMax\n )\n\n this.total = this.left.total + this.right.total\n }\n}"
] |
|
2,278 | percentage-of-letter-in-string | [
"Can we count the number of occurrences of letter in s?",
"Recall that the percentage is calculated as (occurrences / total) * 100."
] | /**
* @param {string} s
* @param {character} letter
* @return {number}
*/
var percentageLetter = function(s, letter) {
}; | Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent.
Example 1:
Input: s = "foobar", letter = "o"
Output: 33
Explanation:
The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.
Example 2:
Input: s = "jjjj", letter = "k"
Output: 0
Explanation:
The percentage of characters in s that equal the letter 'k' is 0%, so we return 0.
Constraints:
1 <= s.length <= 100
s consists of lowercase English letters.
letter is a lowercase English letter.
| Easy | [
"string"
] | null | [] |
2,279 | maximum-bags-with-full-capacity-of-rocks | [
"Which bag should you fill completely first?",
"Can you think of a greedy solution?"
] | /**
* @param {number[]} capacity
* @param {number[]} rocks
* @param {number} additionalRocks
* @return {number}
*/
var maximumBags = function(capacity, rocks, additionalRocks) {
}; | You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks. The ith bag can hold a maximum of capacity[i] rocks and currently contains rocks[i] rocks. You are also given an integer additionalRocks, the number of additional rocks you can place in any of the bags.
Return the maximum number of bags that could have full capacity after placing the additional rocks in some bags.
Example 1:
Input: capacity = [2,3,4,5], rocks = [1,2,4,4], additionalRocks = 2
Output: 3
Explanation:
Place 1 rock in bag 0 and 1 rock in bag 1.
The number of rocks in each bag are now [2,3,4,4].
Bags 0, 1, and 2 have full capacity.
There are 3 bags at full capacity, so we return 3.
It can be shown that it is not possible to have more than 3 bags at full capacity.
Note that there may be other ways of placing the rocks that result in an answer of 3.
Example 2:
Input: capacity = [10,2,2], rocks = [2,2,0], additionalRocks = 100
Output: 3
Explanation:
Place 8 rocks in bag 0 and 2 rocks in bag 2.
The number of rocks in each bag are now [10,2,2].
Bags 0, 1, and 2 have full capacity.
There are 3 bags at full capacity, so we return 3.
It can be shown that it is not possible to have more than 3 bags at full capacity.
Note that we did not use all of the additional rocks.
Constraints:
n == capacity.length == rocks.length
1 <= n <= 5 * 104
1 <= capacity[i] <= 109
0 <= rocks[i] <= capacity[i]
1 <= additionalRocks <= 109
| Medium | [
"array",
"greedy",
"sorting"
] | null | [] |
2,280 | minimum-lines-to-represent-a-line-chart | [
"When will three adjacent points lie on the same line? How can we generalize this for all points?",
"Will calculating the slope of lines connecting adjacent points help us find the answer?"
] | /**
* @param {number[][]} stockPrices
* @return {number}
*/
var minimumLines = function(stockPrices) {
}; | You are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] indicates the price of the stock on day dayi is pricei. A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below:
Return the minimum number of lines needed to represent the line chart.
Example 1:
Input: stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]]
Output: 3
Explanation:
The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price.
The following 3 lines can be drawn to represent the line chart:
- Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4).
- Line 2 (in blue) from (4,4) to (5,4).
- Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1).
It can be shown that it is not possible to represent the line chart using less than 3 lines.
Example 2:
Input: stockPrices = [[3,4],[1,2],[7,8],[2,3]]
Output: 1
Explanation:
As shown in the diagram above, the line chart can be represented with a single line.
Constraints:
1 <= stockPrices.length <= 105
stockPrices[i].length == 2
1 <= dayi, pricei <= 109
All dayi are distinct.
| Medium | [
"array",
"math",
"geometry",
"sorting",
"number-theory"
] | [
"var minimumLines = function(stockPrices) {\n let res = 1\n const ma = stockPrices\n const n = ma.length\n if(n === 0 || n === 1) return 0\n ma.sort((a, b) => a[0] - b[0])\n const eps = 1e-30\n let dx = ma[1][0] - ma[0][0], dy = ma[1][1] - ma[0][1]\n for(let i = 2; i < n; i++) {\n const cur = ma[i], pre = ma[i - 1]\n const dxx = cur[0] - pre[0], dyy = cur[1] - pre[1]\n if(BigInt(dxx) * BigInt(dy) !== BigInt(dx) * BigInt(dyy)) res++\n dx = dxx\n dy = dyy\n }\n \n return res\n};\n\nfunction product(p1, p2, p3) {\n // 首先根据坐标计算p1p2和p1p3的向量,然后再计算叉乘\n // p1p2 向量表示为 (p2.x-p1.x,p2.y-p1.y)\n // p1p3 向量表示为 (p3.x-p1.x,p3.y-p1.y)\n return (p2.x-p1.x)*(p3.y-p1.y) - (p2.y-p1.y)*(p3.x-p1.x);\n}"
] |
|
2,281 | sum-of-total-strength-of-wizards | [
"Consider the contribution of each wizard to the answer.",
"Can you efficiently calculate the total contribution to the answer for all subarrays that end at each index?",
"Denote the total contribution of all subarrays ending at index i as solve[i]. Can you express solve[i] in terms of solve[m] for some m < i?"
] | /**
* @param {number[]} strength
* @return {number}
*/
var totalStrength = function(strength) {
}; | As the ruler of a kingdom, you have an army of wizards at your command.
You are given a 0-indexed integer array strength, where strength[i] denotes the strength of the ith wizard. For a contiguous group of wizards (i.e. the wizards' strengths form a subarray of strength), the total strength is defined as the product of the following two values:
The strength of the weakest wizard in the group.
The total of all the individual strengths of the wizards in the group.
Return the sum of the total strengths of all contiguous groups of wizards. Since the answer may be very large, return it modulo 109 + 7.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: strength = [1,3,1,2]
Output: 44
Explanation: The following are all the contiguous groups of wizards:
- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1
- [3] from [1,3,1,2] has a total strength of min([3]) * sum([3]) = 3 * 3 = 9
- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1
- [2] from [1,3,1,2] has a total strength of min([2]) * sum([2]) = 2 * 2 = 4
- [1,3] from [1,3,1,2] has a total strength of min([1,3]) * sum([1,3]) = 1 * 4 = 4
- [3,1] from [1,3,1,2] has a total strength of min([3,1]) * sum([3,1]) = 1 * 4 = 4
- [1,2] from [1,3,1,2] has a total strength of min([1,2]) * sum([1,2]) = 1 * 3 = 3
- [1,3,1] from [1,3,1,2] has a total strength of min([1,3,1]) * sum([1,3,1]) = 1 * 5 = 5
- [3,1,2] from [1,3,1,2] has a total strength of min([3,1,2]) * sum([3,1,2]) = 1 * 6 = 6
- [1,3,1,2] from [1,3,1,2] has a total strength of min([1,3,1,2]) * sum([1,3,1,2]) = 1 * 7 = 7
The sum of all the total strengths is 1 + 9 + 1 + 4 + 4 + 4 + 3 + 5 + 6 + 7 = 44.
Example 2:
Input: strength = [5,4,6]
Output: 213
Explanation: The following are all the contiguous groups of wizards:
- [5] from [5,4,6] has a total strength of min([5]) * sum([5]) = 5 * 5 = 25
- [4] from [5,4,6] has a total strength of min([4]) * sum([4]) = 4 * 4 = 16
- [6] from [5,4,6] has a total strength of min([6]) * sum([6]) = 6 * 6 = 36
- [5,4] from [5,4,6] has a total strength of min([5,4]) * sum([5,4]) = 4 * 9 = 36
- [4,6] from [5,4,6] has a total strength of min([4,6]) * sum([4,6]) = 4 * 10 = 40
- [5,4,6] from [5,4,6] has a total strength of min([5,4,6]) * sum([5,4,6]) = 4 * 15 = 60
The sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213.
Constraints:
1 <= strength.length <= 105
1 <= strength[i] <= 109
| Hard | [
"array",
"stack",
"monotonic-stack",
"prefix-sum"
] | [
"const totalStrength = function (strength) {\n const mod = BigInt(1e9 + 7)\n let res = 0n\n const n = strength.length\n strength = strength.map(e => BigInt(e))\n const leftsum = Array(n + 1).fill(0n),\n rightsum = Array(n + 1).fill(0n),\n leftmul = Array(n + 1).fill(0n),\n rightmul = Array(n + 1).fill(0n)\n const asc = []\n const big = BigInt\n\n for (let i = 0; i < n; i++) {\n leftsum[i + 1] = (leftsum[i] + strength[i]) % mod\n leftmul[i + 1] = (leftmul[i] + big(i + 1) * strength[i]) % mod\n }\n\n for (let i = n - 1; i >= 0; i--) {\n rightsum[i] = (rightsum[i + 1] + strength[i]) % mod\n rightmul[i] = (rightmul[i + 1] + big(n - i) * strength[i]) % mod\n }\n\n // j is the exclusive right index\n for (let j = 0; j <= n; j++) {\n while (\n asc.length &&\n (j === n || strength[asc[asc.length - 1]] >= strength[j])\n ) {\n const k = asc.pop()\n const i = asc.length === 0 ? 0 : asc[asc.length - 1] + 1\n const left =\n (mod +\n leftmul[k + 1] -\n leftmul[i] -\n ((big(i) * (leftsum[k + 1] - leftsum[i])) % mod)) %\n mod\n const right =\n (mod +\n rightmul[k + 1] -\n rightmul[j] -\n ((big(n - j) * (rightsum[k + 1] - rightsum[j])) % mod)) %\n mod\n const sum = (left * big(j - k) + right * big(k - i + 1)) % mod\n res = (res + sum * strength[k]) % mod\n }\n asc.push(j)\n }\n return res\n}"
] |
|
2,283 | check-if-number-has-equal-digit-count-and-digit-value | [
"Count the frequency of each digit in num."
] | /**
* @param {string} num
* @return {boolean}
*/
var digitCount = function(num) {
}; | You are given a 0-indexed string num of length n consisting of digits.
Return true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num, otherwise return false.
Example 1:
Input: num = "1210"
Output: true
Explanation:
num[0] = '1'. The digit 0 occurs once in num.
num[1] = '2'. The digit 1 occurs twice in num.
num[2] = '1'. The digit 2 occurs once in num.
num[3] = '0'. The digit 3 occurs zero times in num.
The condition holds true for every index in "1210", so return true.
Example 2:
Input: num = "030"
Output: false
Explanation:
num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num.
num[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num.
num[2] = '0'. The digit 2 occurs zero times in num.
The indices 0 and 1 both violate the condition, so return false.
Constraints:
n == num.length
1 <= n <= 10
num consists of digits.
| Easy | [
"hash-table",
"string",
"counting"
] | null | [] |
2,284 | sender-with-largest-word-count | [
"The number of words in a message is equal to the number of spaces + 1.",
"Use a hash map to count the total number of words from each sender."
] | /**
* @param {string[]} messages
* @param {string[]} senders
* @return {string}
*/
var largestWordCount = function(messages, senders) {
}; | You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i].
A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message.
Return the sender with the largest word count. If there is more than one sender with the largest word count, return the one with the lexicographically largest name.
Note:
Uppercase letters come before lowercase letters in lexicographical order.
"Alice" and "alice" are distinct.
Example 1:
Input: messages = ["Hello userTwooo","Hi userThree","Wonderful day Alice","Nice day userThree"], senders = ["Alice","userTwo","userThree","Alice"]
Output: "Alice"
Explanation: Alice sends a total of 2 + 3 = 5 words.
userTwo sends a total of 2 words.
userThree sends a total of 3 words.
Since Alice has the largest word count, we return "Alice".
Example 2:
Input: messages = ["How is leetcode for everyone","Leetcode is useful for practice"], senders = ["Bob","Charlie"]
Output: "Charlie"
Explanation: Bob sends a total of 5 words.
Charlie sends a total of 5 words.
Since there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie.
Constraints:
n == messages.length == senders.length
1 <= n <= 104
1 <= messages[i].length <= 100
1 <= senders[i].length <= 10
messages[i] consists of uppercase and lowercase English letters and ' '.
All the words in messages[i] are separated by a single space.
messages[i] does not have leading or trailing spaces.
senders[i] consists of uppercase and lowercase English letters only.
| Medium | [
"array",
"hash-table",
"string",
"counting"
] | null | [] |
2,285 | maximum-total-importance-of-roads | [
"Consider what each city contributes to the total importance of all roads.",
"Based on that, how can you sort the cities such that assigning them values in that order will yield the maximum total importance?"
] | /**
* @param {number} n
* @param {number[][]} roads
* @return {number}
*/
var maximumImportance = function(n, roads) {
}; | You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1.
You are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.
You need to assign each city with an integer value from 1 to n, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects.
Return the maximum total importance of all roads possible after assigning the values optimally.
Example 1:
Input: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]
Output: 43
Explanation: The figure above shows the country and the assigned values of [2,4,5,3,1].
- The road (0,1) has an importance of 2 + 4 = 6.
- The road (1,2) has an importance of 4 + 5 = 9.
- The road (2,3) has an importance of 5 + 3 = 8.
- The road (0,2) has an importance of 2 + 5 = 7.
- The road (1,3) has an importance of 4 + 3 = 7.
- The road (2,4) has an importance of 5 + 1 = 6.
The total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43.
It can be shown that we cannot obtain a greater total importance than 43.
Example 2:
Input: n = 5, roads = [[0,3],[2,4],[1,3]]
Output: 20
Explanation: The figure above shows the country and the assigned values of [4,3,2,5,1].
- The road (0,3) has an importance of 4 + 5 = 9.
- The road (2,4) has an importance of 2 + 1 = 3.
- The road (1,3) has an importance of 3 + 5 = 8.
The total importance of all roads is 9 + 3 + 8 = 20.
It can be shown that we cannot obtain a greater total importance than 20.
Constraints:
2 <= n <= 5 * 104
1 <= roads.length <= 5 * 104
roads[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
There are no duplicate roads.
| Medium | [
"greedy",
"graph",
"sorting",
"heap-priority-queue"
] | null | [] |
2,286 | booking-concert-tickets-in-groups | [
"Since seats are allocated by smallest row and then by smallest seat numbers, how can we keep a record of the smallest seat number vacant in each row?",
"How can range max query help us to check if contiguous seats can be allocated in a range?",
"Similarly, can range sum query help us to check if enough seats are available in a range?",
"Which data structure can be used to implement the above?"
] | /**
* @param {number} n
* @param {number} m
*/
var BookMyShow = function(n, m) {
};
/**
* @param {number} k
* @param {number} maxRow
* @return {number[]}
*/
BookMyShow.prototype.gather = function(k, maxRow) {
};
/**
* @param {number} k
* @param {number} maxRow
* @return {boolean}
*/
BookMyShow.prototype.scatter = function(k, maxRow) {
};
/**
* Your BookMyShow object will be instantiated and called as such:
* var obj = new BookMyShow(n, m)
* var param_1 = obj.gather(k,maxRow)
* var param_2 = obj.scatter(k,maxRow)
*/ | A concert hall has n rows numbered from 0 to n - 1, each with m seats, numbered from 0 to m - 1. You need to design a ticketing system that can allocate seats in the following cases:
If a group of k spectators can sit together in a row.
If every member of a group of k spectators can get a seat. They may or may not sit together.
Note that the spectators are very picky. Hence:
They will book seats only if each member of their group can get a seat with row number less than or equal to maxRow. maxRow can vary from group to group.
In case there are multiple rows to choose from, the row with the smallest number is chosen. If there are multiple seats to choose in the same row, the seat with the smallest number is chosen.
Implement the BookMyShow class:
BookMyShow(int n, int m) Initializes the object with n as number of rows and m as number of seats per row.
int[] gather(int k, int maxRow) Returns an array of length 2 denoting the row and seat number (respectively) of the first seat being allocated to the k members of the group, who must sit together. In other words, it returns the smallest possible r and c such that all [c, c + k - 1] seats are valid and empty in row r, and r <= maxRow. Returns [] in case it is not possible to allocate seats to the group.
boolean scatter(int k, int maxRow) Returns true if all k members of the group can be allocated seats in rows 0 to maxRow, who may or may not sit together. If the seats can be allocated, it allocates k seats to the group with the smallest row numbers, and the smallest possible seat numbers in each row. Otherwise, returns false.
Example 1:
Input
["BookMyShow", "gather", "gather", "scatter", "scatter"]
[[2, 5], [4, 0], [2, 0], [5, 1], [5, 1]]
Output
[null, [0, 0], [], true, false]
Explanation
BookMyShow bms = new BookMyShow(2, 5); // There are 2 rows with 5 seats each
bms.gather(4, 0); // return [0, 0]
// The group books seats [0, 3] of row 0.
bms.gather(2, 0); // return []
// There is only 1 seat left in row 0,
// so it is not possible to book 2 consecutive seats.
bms.scatter(5, 1); // return True
// The group books seat 4 of row 0 and seats [0, 3] of row 1.
bms.scatter(5, 1); // return False
// There is only one seat left in the hall.
Constraints:
1 <= n <= 5 * 104
1 <= m, k <= 109
0 <= maxRow <= n - 1
At most 5 * 104 calls in total will be made to gather and scatter.
| Hard | [
"binary-search",
"design",
"binary-indexed-tree",
"segment-tree"
] | [
"function BookMyShow(n, m) {\n let a = Array(n).fill(0), st = new SegmentTreeRMQ(a), fen = new Fenwick(n + 3);\n for (let i = 0; i < n; i++) fen.update(i, m);\n return { gather, scatter }\n function gather(k, maxRow) {\n let idx = st.indexOf(0, m - k);\n if (idx == -1 || idx > maxRow) return [];\n let min = st.minx(idx, idx + 1);\n st.update(idx, min + k);\n fen.update(idx, -k);\n return [idx, min];\n }\n function scatter(k, maxRow) {\n let totToMaxRow = fen.query(maxRow);\n if (totToMaxRow < k) return false;\n while (k > 0) {\n let idx = st.indexOf(0, m - 1);\n if (idx == -1 || idx > maxRow) break;\n let min = st.minx(idx, idx + 1);\n let use = Math.min(k, m - min);\n k -= use;\n st.update(idx, min + use);\n fen.update(idx, -use);\n }\n return true;\n }\n}\n\n\n////////////////////////////////////////////////// Template ////////////////////////////////////////////////////////////////////\nfunction Fenwick(n) {\n let a = Array(n).fill(0);\n return { query, update, rangeSum, tree }\n function query(i) { // [0, i] prefix sum\n let sum = 0;\n for (i++; i > 0; i = parent(i)) sum += a[i];\n return sum;\n }\n function update(i, v) {\n for (i++; i < n; i = next(i)) a[i] += v;\n }\n function rangeSum(l, r) {\n return query(r) - query(l - 1);\n }\n function parent(x) {\n return x - lowestOneBit(x);\n }\n function next(x) {\n return x + lowestOneBit(x);\n }\n function lowestOneBit(x) {\n return x & -x;\n }\n function tree() {\n return a;\n }\n}\n\nfunction SegmentTreeRMQ(A) {\n let n = A.length, h = Math.ceil(Math.log2(n)), len = 2 * 2 ** h, a = Array(len).fill(Number.MAX_SAFE_INTEGER);\n h = 2 ** h;\n initializeFromArray();\n return { update, minx, indexOf, tree }\n function initializeFromArray() {\n for (let i = 0; i < n; i++) a[h + i] = A[i];\n for (let i = h - 1; i >= 1; i--) propagate(i);\n }\n function update(pos, v) {\n a[h + pos] = v;\n for (let i = parent(h + pos); i >= 1; i = parent(i)) propagate(i);\n }\n function propagate(i) {\n a[i] = Math.min(a[left(i)], a[right(i)]);\n }\n function minx(l, r) {\n let min = Number.MAX_SAFE_INTEGER;\n if (l >= r) return min;\n l += h;\n r += h;\n for (; l < r; l = parent(l), r = parent(r)) {\n if (l & 1) min = Math.min(min, a[l++]);\n if (r & 1) min = Math.min(min, a[--r]);\n }\n return min;\n }\n function indexOf(l, v) {\n if (l >= h) return -1;\n let cur = h + l;\n while (1) {\n if (a[cur] <= v) {\n if (cur >= h) return cur - h;\n cur = left(cur);\n } else {\n cur++;\n if ((cur & cur - 1) == 0) return -1;\n if (cur % 2 == 0) cur = parent(cur);\n }\n }\n }\n function parent(i) {\n return i >> 1;\n }\n function left(i) {\n return 2 * i;\n }\n function right(i) {\n return 2 * i + 1;\n }\n function tree() {\n return a;\n }\n}\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"
] |
|
2,287 | rearrange-characters-to-make-target-string | [
"Count the frequency of each character in s and target.",
"Consider each letter one at a time. If there are x occurrences of a letter in s and y occurrences of the same letter in target, how many copies of this letter can we make?",
"We can make floor(x / y) copies of the letter."
] | /**
* @param {string} s
* @param {string} target
* @return {number}
*/
var rearrangeCharacters = function(s, target) {
}; | You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings.
Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them.
Example 1:
Input: s = "ilovecodingonleetcode", target = "code"
Output: 2
Explanation:
For the first copy of "code", take the letters at indices 4, 5, 6, and 7.
For the second copy of "code", take the letters at indices 17, 18, 19, and 20.
The strings that are formed are "ecod" and "code" which can both be rearranged into "code".
We can make at most two copies of "code", so we return 2.
Example 2:
Input: s = "abcba", target = "abc"
Output: 1
Explanation:
We can make one copy of "abc" by taking the letters at indices 0, 1, and 2.
We can make at most one copy of "abc", so we return 1.
Note that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of "abc".
Example 3:
Input: s = "abbaccaddaeea", target = "aaaaa"
Output: 1
Explanation:
We can make one copy of "aaaaa" by taking the letters at indices 0, 3, 6, 9, and 12.
We can make at most one copy of "aaaaa", so we return 1.
Constraints:
1 <= s.length <= 100
1 <= target.length <= 10
s and target consist of lowercase English letters.
| Easy | [
"hash-table",
"string",
"counting"
] | [
"var rearrangeCharacters = function(s, target) {\n const a = 'a'.charCodeAt(0), arr = Array(26).fill(0)\n for(let ch of target) {\n arr[ch.charCodeAt(0) - a]++\n }\n let min = Math.min(...arr.filter(e => e > 0))\n const sa = Array(26).fill(0)\n for(const e of s) {\n sa[e.charCodeAt(0) - a]++\n }\n let res = -1\n for(let i = 0; i < 26; i++) {\n const sv = sa[i], tv = arr[i]\n if(tv === 0) continue\n const v = ~~(sv / tv)\n if(res === -1) res = v\n else res = Math.min(res, v)\n }\n \n return res\n};"
] |
|
2,288 | apply-discount-to-prices | [
"Extract each word from the sentence and check if it represents a price.",
"For each price, apply the given discount to it and update it."
] | /**
* @param {string} sentence
* @param {number} discount
* @return {string}
*/
var discountPrices = function(sentence, discount) {
}; | A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign.
For example, "$100", "$23", and "$6" represent prices while "100", "$", and "$1e5" do not.
You are given a string sentence representing a sentence and an integer discount. For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places.
Return a string representing the modified sentence.
Note that all prices will contain at most 10 digits.
Example 1:
Input: sentence = "there are $1 $2 and 5$ candies in the shop", discount = 50
Output: "there are $0.50 $1.00 and 5$ candies in the shop"
Explanation:
The words which represent prices are "$1" and "$2".
- A 50% discount on "$1" yields "$0.50", so "$1" is replaced by "$0.50".
- A 50% discount on "$2" yields "$1". Since we need to have exactly 2 decimal places after a price, we replace "$2" with "$1.00".
Example 2:
Input: sentence = "1 2 $3 4 $5 $6 7 8$ $9 $10$", discount = 100
Output: "1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$"
Explanation:
Applying a 100% discount on any price will result in 0.
The words representing prices are "$3", "$5", "$6", and "$9".
Each of them is replaced by "$0.00".
Constraints:
1 <= sentence.length <= 105
sentence consists of lowercase English letters, digits, ' ', and '$'.
sentence does not have leading or trailing spaces.
All words in sentence are separated by a single space.
All prices will be positive numbers without leading zeros.
All prices will have at most 10 digits.
0 <= discount <= 100
| Medium | [
"string"
] | [
"var discountPrices = function(sentence, discount) {\n const arr = sentence.split(' '), n = arr.length\n for(let i = 0; i < n; i++) {\n const cur = arr[i]\n const rest = cur.slice(1)\n if(cur.startsWith('$') && rest.length && !Number.isNaN(+rest)) {\n arr[i] = '$' + ((+rest) * (100 - discount) / 100).toFixed(2)\n }\n }\n return arr.join(' ')\n};"
] |
|
2,289 | steps-to-make-array-non-decreasing | [
"Notice that an element will be removed if and only if there exists a strictly greater element to the left of it in the array.",
"For each element, we need to find the number of rounds it will take for it to be removed. The answer is the maximum number of rounds for all elements. Build an array dp to hold this information where the answer is the maximum value of dp.",
"Use a stack of the indices. While processing element nums[i], remove from the stack all the indices of elements that are smaller than nums[i]. dp[i] should be set to the maximum of dp[i] + 1 and dp[removed index]."
] | /**
* @param {number[]} nums
* @return {number}
*/
var totalSteps = function(nums) {
}; | You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length.
Return the number of steps performed until nums becomes a non-decreasing array.
Example 1:
Input: nums = [5,3,4,4,7,3,6,11,8,5,11]
Output: 3
Explanation: The following are the steps performed:
- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]
- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]
- Step 3: [5,4,7,11,11] becomes [5,7,11,11]
[5,7,11,11] is a non-decreasing array. Therefore, we return 3.
Example 2:
Input: nums = [4,5,7,7,13]
Output: 0
Explanation: nums is already a non-decreasing array. Therefore, we return 0.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
| Medium | [
"array",
"linked-list",
"stack",
"monotonic-stack"
] | [
"var totalSteps = function(nums) {\n const n = nums.length\n let res = 0, j = -1;\n const dp = Array(n).fill(0), stack = Array(n).fill(0);\n for (let i = n - 1; i >= 0; --i) {\n while (j >= 0 && nums[i] > nums[stack[j]]) {\n dp[i] = Math.max(++dp[i], dp[stack[j--]])\n res = Math.max(res, dp[i])\n }\n stack[++j] = i\n }\n return res\n};",
"const totalSteps = function(nums) {\n let res = 0, stk = []\n stk.push([nums[0], 0])\n for(let i = 1, n = nums.length; i < n; i++) {\n let steps = 0\n while(stk.length && stk[stk.length - 1][0] <= nums[i]) {\n const peek = stk.pop() \n steps = Math.max(steps, peek[1])\n }\n if(stk.length === 0) steps = 0\n else steps++\n \n res = Math.max(res, steps)\n stk.push([nums[i], steps])\n } \n \n return res\n};",
"const totalSteps = function(nums) {\n let res = 0\n const stk = []\n for(const e of nums) {\n let steps = 1\n while(stk.length && e >= stk[stk.length - 1][0]) {\n const tmp = stk.pop()\n steps = Math.max(tmp[1] + 1, steps)\n }\n if(stk.length === 0) steps = 0\n else {\n res = Math.max(res, steps)\n }\n stk.push([e, steps])\n }\n return res\n};"
] |
|
2,290 | minimum-obstacle-removal-to-reach-corner | [
"Model the grid as a graph where cells are nodes and edges are between adjacent cells. Edges to cells with obstacles have a cost of 1 and all other edges have a cost of 0.",
"Could you use 0-1 Breadth-First Search or Dijkstra’s algorithm?"
] | /**
* @param {number[][]} grid
* @return {number}
*/
var minimumObstacles = function(grid) {
}; | You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values:
0 represents an empty cell,
1 represents an obstacle that may be removed.
You can move up, down, left, or right from and to an empty cell.
Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1).
Example 1:
Input: grid = [[0,1,1],[1,1,0],[1,1,0]]
Output: 2
Explanation: We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2).
It can be shown that we need to remove at least 2 obstacles, so we return 2.
Note that there may be other ways to remove 2 obstacles to create a path.
Example 2:
Input: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]
Output: 0
Explanation: We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 105
2 <= m * n <= 105
grid[i][j] is either 0 or 1.
grid[0][0] == grid[m - 1][n - 1] == 0
| Hard | [
"array",
"breadth-first-search",
"graph",
"heap-priority-queue",
"matrix",
"shortest-path"
] | [
"var minimumObstacles = function(grid) {\n const m = grid.length, n = grid[0].length\n const dist = Array.from({ length: m }, () => Array(n).fill(Infinity))\n const pq = new MinPriorityQueue({ priority: (x) => x[0] })\n const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n dist[0][0] = 0\n pq.enqueue([dist[0][0], 0, 0])\n while(pq.size()) {\n const [v, i, j] = pq.dequeue().element\n if(i === m - 1 && j === n - 1) return v\n for(const [dx, dy] of dirs) {\n const nx = i + dx, ny = j + dy\n if(nx >= 0 && nx < m && ny >= 0 && ny < n && v + grid[nx][ny] < dist[nx][ny]) {\n dist[nx][ny] = v + grid[nx][ny]\n pq.enqueue([dist[nx][ny], nx, ny])\n }\n }\n }\n};"
] |
|
2,293 | min-max-game | [
"Simply simulate the algorithm.",
"Note that the size of the array decreases exponentially, so the process will terminate after just O(log n) steps."
] | /**
* @param {number[]} nums
* @return {number}
*/
var minMaxGame = function(nums) {
}; | You are given a 0-indexed integer array nums whose length is a power of 2.
Apply the following algorithm on nums:
Let n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n / 2.
For every even index i where 0 <= i < n / 2, assign the value of newNums[i] as min(nums[2 * i], nums[2 * i + 1]).
For every odd index i where 0 <= i < n / 2, assign the value of newNums[i] as max(nums[2 * i], nums[2 * i + 1]).
Replace the array nums with newNums.
Repeat the entire process starting from step 1.
Return the last number that remains in nums after applying the algorithm.
Example 1:
Input: nums = [1,3,5,2,4,8,2,2]
Output: 1
Explanation: The following arrays are the results of applying the algorithm repeatedly.
First: nums = [1,5,4,2]
Second: nums = [1,4]
Third: nums = [1]
1 is the last remaining number, so we return 1.
Example 2:
Input: nums = [3]
Output: 3
Explanation: 3 is already the last remaining number, so we return 3.
Constraints:
1 <= nums.length <= 1024
1 <= nums[i] <= 109
nums.length is a power of 2.
| Easy | [
"array",
"simulation"
] | [
"var minMaxGame = function(nums) {\n let cur = nums\n while(cur.length > 1) {\n const n = cur.length\n const tmp = Array(n / 2)\n for(let i = 0; i < n / 2; i++) {\n const odd = i % 2 === 1\n if(odd) {\n tmp[i] = Math.max(cur[2 * i], cur[2 * i + 1]) \n } else {\n tmp[i] = Math.min(cur[2 * i], cur[2 * i + 1])\n }\n }\n cur = tmp\n }\n \n return cur[0]\n};"
] |
|
2,294 | partition-array-such-that-maximum-difference-is-k | [
"Which values in each subsequence matter? The only values that matter are the maximum and minimum values.",
"Let the maximum and minimum values of a subsequence be Max and Min. It is optimal to place all values in between Max and Min in the original array in the same subsequence as Max and Min.",
"Sort the array."
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var partitionArray = function(nums, k) {
}; | You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences.
Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [3,6,1,2,5], k = 2
Output: 2
Explanation:
We can partition nums into the two subsequences [3,1,2] and [6,5].
The difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2.
The difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1.
Since two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed.
Example 2:
Input: nums = [1,2,3], k = 1
Output: 2
Explanation:
We can partition nums into the two subsequences [1,2] and [3].
The difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1.
The difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0.
Since two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3].
Example 3:
Input: nums = [2,2,4,5], k = 0
Output: 3
Explanation:
We can partition nums into the three subsequences [2,2], [4], and [5].
The difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0.
The difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0.
The difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0.
Since three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 105
0 <= k <= 105
| Medium | [
"array",
"greedy",
"sorting"
] | [
"var partitionArray = function(nums, k) {\n nums.sort((a, b) => a - b)\n let res = 1, pre = nums[0], n = nums.length\n for(let i = 1; i < n; i++) {\n const cur = nums[i]\n if(cur - pre > k) {\n res++\n pre = cur\n }\n }\n \n return res\n};"
] |
|
2,295 | replace-elements-in-an-array | [
"Can you think of a data structure that will allow you to store the position of each number?",
"Use that data structure to instantly replace a number with its new value."
] | /**
* @param {number[]} nums
* @param {number[][]} operations
* @return {number[]}
*/
var arrayChange = function(nums, operations) {
}; | You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1].
It is guaranteed that in the ith operation:
operations[i][0] exists in nums.
operations[i][1] does not exist in nums.
Return the array obtained after applying all the operations.
Example 1:
Input: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]
Output: [3,2,7,1]
Explanation: We perform the following operations on nums:
- Replace the number 1 with 3. nums becomes [3,2,4,6].
- Replace the number 4 with 7. nums becomes [3,2,7,6].
- Replace the number 6 with 1. nums becomes [3,2,7,1].
We return the final array [3,2,7,1].
Example 2:
Input: nums = [1,2], operations = [[1,3],[2,1],[3,2]]
Output: [2,1]
Explanation: We perform the following operations to nums:
- Replace the number 1 with 3. nums becomes [3,2].
- Replace the number 2 with 1. nums becomes [3,1].
- Replace the number 3 with 2. nums becomes [2,1].
We return the array [2,1].
Constraints:
n == nums.length
m == operations.length
1 <= n, m <= 105
All the values of nums are distinct.
operations[i].length == 2
1 <= nums[i], operations[i][0], operations[i][1] <= 106
operations[i][0] will exist in nums when applying the ith operation.
operations[i][1] will not exist in nums when applying the ith operation.
| Medium | [
"array",
"hash-table",
"simulation"
] | [
"var arrayChange = function(nums, operations) {\n const map = new Map(), n = nums.length\n const res = Array(n)\n for(let i = 0; i < n; i++) {\n const cur = nums[i]\n map.set(cur, i)\n res[i] = cur\n }\n \n for(const [v, vv] of operations) {\n const idx = map.get(v)\n res[idx] = vv\n map.set(vv, idx)\n }\n \n return res\n};"
] |
|
2,296 | design-a-text-editor | [
"Making changes in the middle of some data structures is generally harder than changing the front/back of the same data structure.",
"Can you partition your data structure (text with cursor) into two parts, such that each part changes only near its ends?",
"Can you think of a data structure that supports efficient removals/additions to the front/back?",
"Try to solve the problem with two deques by maintaining the prefix and the suffix separately."
] |
var TextEditor = function() {
};
/**
* @param {string} text
* @return {void}
*/
TextEditor.prototype.addText = function(text) {
};
/**
* @param {number} k
* @return {number}
*/
TextEditor.prototype.deleteText = function(k) {
};
/**
* @param {number} k
* @return {string}
*/
TextEditor.prototype.cursorLeft = function(k) {
};
/**
* @param {number} k
* @return {string}
*/
TextEditor.prototype.cursorRight = function(k) {
};
/**
* Your TextEditor object will be instantiated and called as such:
* var obj = new TextEditor()
* obj.addText(text)
* var param_2 = obj.deleteText(k)
* var param_3 = obj.cursorLeft(k)
* var param_4 = obj.cursorRight(k)
*/ | Design a text editor with a cursor that can do the following:
Add text to where the cursor is.
Delete text from where the cursor is (simulating the backspace key).
Move the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds.
Implement the TextEditor class:
TextEditor() Initializes the object with empty text.
void addText(string text) Appends text to where the cursor is. The cursor ends to the right of text.
int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted.
string cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
string cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
Example 1:
Input
["TextEditor", "addText", "deleteText", "addText", "cursorRight", "cursorLeft", "deleteText", "cursorLeft", "cursorRight"]
[[], ["leetcode"], [4], ["practice"], [3], [8], [10], [2], [6]]
Output
[null, null, 4, null, "etpractice", "leet", 4, "", "practi"]
Explanation
TextEditor textEditor = new TextEditor(); // The current text is "|". (The '|' character represents the cursor)
textEditor.addText("leetcode"); // The current text is "leetcode|".
textEditor.deleteText(4); // return 4
// The current text is "leet|".
// 4 characters were deleted.
textEditor.addText("practice"); // The current text is "leetpractice|".
textEditor.cursorRight(3); // return "etpractice"
// The current text is "leetpractice|".
// The cursor cannot be moved beyond the actual text and thus did not move.
// "etpractice" is the last 10 characters to the left of the cursor.
textEditor.cursorLeft(8); // return "leet"
// The current text is "leet|practice".
// "leet" is the last min(10, 4) = 4 characters to the left of the cursor.
textEditor.deleteText(10); // return 4
// The current text is "|practice".
// Only 4 characters were deleted.
textEditor.cursorLeft(2); // return ""
// The current text is "|practice".
// The cursor cannot be moved beyond the actual text and thus did not move.
// "" is the last min(10, 0) = 0 characters to the left of the cursor.
textEditor.cursorRight(6); // return "practi"
// The current text is "practi|ce".
// "practi" is the last min(10, 6) = 6 characters to the left of the cursor.
Constraints:
1 <= text.length, k <= 40
text consists of lowercase English letters.
At most 2 * 104 calls in total will be made to addText, deleteText, cursorLeft and cursorRight.
Follow-up: Could you find a solution with time complexity of O(k) per call?
| Hard | [
"linked-list",
"string",
"stack",
"design",
"simulation",
"doubly-linked-list"
] | [
"const TextEditor = function () {\n this.stk1 = []\n this.stk2 = []\n}\n\n\nTextEditor.prototype.addText = function (text) {\n for (const ch of text) this.stk1.push(ch)\n}\n\n\nTextEditor.prototype.deleteText = function (k) {\n let res = 0\n while (this.stk1.length && k) {\n k--\n res++\n this.stk1.pop()\n }\n return res\n}\n\n\nTextEditor.prototype.cursorLeft = function (k) {\n let res = ''\n while (this.stk1.length && k) {\n const tmp = this.stk1.pop()\n this.stk2.push(tmp)\n k--\n }\n\n return this.slice()\n}\n\n\nTextEditor.prototype.cursorRight = function (k) {\n let res = ''\n\n while (this.stk2.length && k) {\n const tmp = this.stk2.pop()\n this.stk1.push(tmp)\n k--\n }\n\n return this.slice()\n}\n\nTextEditor.prototype.slice = function() {\n let res = ''\n for (\n let len = this.stk1.length, size = Math.min(10, this.stk1.length), i = 0;\n i < size;\n i++\n ) {\n res = this.stk1[len - i - 1] + res\n }\n return res\n}",
"class Node {\n constructor(val) {\n this.val = val\n this.prev = null\n this.next = null\n }\n}\n\nvar TextEditor = function() {\n this.left = []\n this.right = []\n this.idx = 0\n};\n\n\nTextEditor.prototype.addText = function(text) {\n for(const ch of text) this.left.push(ch)\n};\n\n\nTextEditor.prototype.deleteText = function(k) {\n let res = 0\n while(this.left.length && k) {\n res++\n this.left.pop()\n k--\n }\n return res\n};\n\n\nTextEditor.prototype.cursorLeft = function(k) {\n while(k && this.left.length) {\n const tmp = this.left.pop()\n this.right.push(tmp)\n k--\n }\n\n return this.left.slice(Math.max(0, this.left.length - 10), this.left.length).join('')\n};\n\n\nTextEditor.prototype.cursorRight = function(k) {\n while(k && this.right.length) {\n const tmp = this.right.pop()\n this.left.push(tmp) \n k--\n }\n\n return this.left.slice(Math.max(0, this.left.length - 10), this.left.length).join('')\n};"
] |
|
2,299 | strong-password-checker-ii | [
"You can use a boolean flag to define certain types of characters seen in the string.",
"In the end, check if all boolean flags have ended up True, and do not forget to check the \"adjacent\" and \"length\" criteria."
] | /**
* @param {string} password
* @return {boolean}
*/
var strongPasswordCheckerII = function(password) {
}; | A password is said to be strong if it satisfies all the following criteria:
It has at least 8 characters.
It contains at least one lowercase letter.
It contains at least one uppercase letter.
It contains at least one digit.
It contains at least one special character. The special characters are the characters in the following string: "!@#$%^&*()-+".
It does not contain 2 of the same character in adjacent positions (i.e., "aab" violates this condition, but "aba" does not).
Given a string password, return true if it is a strong password. Otherwise, return false.
Example 1:
Input: password = "IloveLe3tcode!"
Output: true
Explanation: The password meets all the requirements. Therefore, we return true.
Example 2:
Input: password = "Me+You--IsMyDream"
Output: false
Explanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.
Example 3:
Input: password = "1aB!"
Output: false
Explanation: The password does not meet the length requirement. Therefore, we return false.
Constraints:
1 <= password.length <= 100
password consists of letters, digits, and special characters: "!@#$%^&*()-+".
| Easy | [
"string"
] | null | [] |
2,300 | successful-pairs-of-spells-and-potions | [
"Notice that if a spell and potion pair is successful, then the spell and all stronger potions will be successful too.",
"Thus, for each spell, we need to find the potion with the least strength that will form a successful pair.",
"We can efficiently do this by sorting the potions based on strength and using binary search."
] | /**
* @param {number[]} spells
* @param {number[]} potions
* @param {number} success
* @return {number[]}
*/
var successfulPairs = function(spells, potions, success) {
}; | You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion.
You are also given an integer success. A spell and potion pair is considered successful if the product of their strengths is at least success.
Return an integer array pairs of length n where pairs[i] is the number of potions that will form a successful pair with the ith spell.
Example 1:
Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7
Output: [4,0,3]
Explanation:
- 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.
- 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.
- 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.
Thus, [4,0,3] is returned.
Example 2:
Input: spells = [3,1,2], potions = [8,5,8], success = 16
Output: [2,0,2]
Explanation:
- 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.
- 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful.
- 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful.
Thus, [2,0,2] is returned.
Constraints:
n == spells.length
m == potions.length
1 <= n, m <= 105
1 <= spells[i], potions[i] <= 105
1 <= success <= 1010
| Medium | [
"array",
"two-pointers",
"binary-search",
"sorting"
] | null | [] |
2,301 | match-substring-after-replacement | [
"Enumerate all substrings of s with the same length as sub, and compare each substring to sub for equality.",
"How can you quickly tell if a character of s can result from replacing the corresponding character in sub?"
] | /**
* @param {string} s
* @param {string} sub
* @param {character[][]} mappings
* @return {boolean}
*/
var matchReplacement = function(s, sub, mappings) {
}; | You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times:
Replace a character oldi of sub with newi.
Each character in sub cannot be replaced more than once.
Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. Otherwise, return false.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: s = "fool3e7bar", sub = "leet", mappings = [["e","3"],["t","7"],["t","8"]]
Output: true
Explanation: Replace the first 'e' in sub with '3' and 't' in sub with '7'.
Now sub = "l3e7" is a substring of s, so we return true.
Example 2:
Input: s = "fooleetbar", sub = "f00l", mappings = [["o","0"]]
Output: false
Explanation: The string "f00l" is not a substring of s and no replacements can be made.
Note that we cannot replace '0' with 'o'.
Example 3:
Input: s = "Fool33tbaR", sub = "leetd", mappings = [["e","3"],["t","7"],["t","8"],["d","b"],["p","b"]]
Output: true
Explanation: Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'.
Now sub = "l33tb" is a substring of s, so we return true.
Constraints:
1 <= sub.length <= s.length <= 5000
0 <= mappings.length <= 1000
mappings[i].length == 2
oldi != newi
s and sub consist of uppercase and lowercase English letters and digits.
oldi and newi are either uppercase or lowercase English letters or digits.
| Hard | [
"array",
"hash-table",
"string",
"string-matching"
] | null | [] |
2,302 | count-subarrays-with-score-less-than-k | [
"If we add an element to a list of elements, how will the score change?",
"How can we use this to determine the number of subarrays with score less than k in a given range?",
"How can we use “Two Pointers” to generalize the solution, and thus count all possible subarrays?"
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var countSubarrays = function(nums, k) {
}; | The score of an array is defined as the product of its sum and its length.
For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75.
Given a positive integer array nums and an integer k, return the number of non-empty subarrays of nums whose score is strictly less than k.
A subarray is a contiguous sequence of elements within an array.
Example 1:
Input: nums = [2,1,4,3,5], k = 10
Output: 6
Explanation:
The 6 subarrays having scores less than 10 are:
- [2] with score 2 * 1 = 2.
- [1] with score 1 * 1 = 1.
- [4] with score 4 * 1 = 4.
- [3] with score 3 * 1 = 3.
- [5] with score 5 * 1 = 5.
- [2,1] with score (2 + 1) * 2 = 6.
Note that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10.
Example 2:
Input: nums = [1,1,1], k = 5
Output: 5
Explanation:
Every subarray except [1,1,1] has a score less than 5.
[1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5.
Thus, there are 5 subarrays having scores less than 5.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= k <= 1015
| Hard | [
"array",
"binary-search",
"sliding-window",
"prefix-sum"
] | [
"const countSubarrays = function(nums, k) {\n let sum = 0\n let res = 0\n for(let i = 0, j = 0, n = nums.length; i < n; i++) {\n sum += nums[i]\n while(sum * (i - j + 1) >= k) sum -= nums[j++]\n res += i - j + 1\n }\n \n return res\n};"
] |
|
2,303 | calculate-amount-paid-in-taxes | [
"As you iterate through the tax brackets, keep track of the previous tax bracket’s upper bound in a variable called prev. If there is no previous tax bracket, use 0 instead.",
"The amount of money in the ith tax bracket is min(income, upperi) - prev."
] | /**
* @param {number[][]} brackets
* @param {number} income
* @return {number}
*/
var calculateTax = function(brackets, income) {
}; | You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti] means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti. The brackets are sorted by upper bound (i.e. upperi-1 < upperi for 0 < i < brackets.length).
Tax is calculated as follows:
The first upper0 dollars earned are taxed at a rate of percent0.
The next upper1 - upper0 dollars earned are taxed at a rate of percent1.
The next upper2 - upper1 dollars earned are taxed at a rate of percent2.
And so on.
You are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: brackets = [[3,50],[7,10],[12,25]], income = 10
Output: 2.65000
Explanation:
Based on your income, you have 3 dollars in the 1st tax bracket, 4 dollars in the 2nd tax bracket, and 3 dollars in the 3rd tax bracket.
The tax rate for the three tax brackets is 50%, 10%, and 25%, respectively.
In total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.
Example 2:
Input: brackets = [[1,0],[4,25],[5,50]], income = 2
Output: 0.25000
Explanation:
Based on your income, you have 1 dollar in the 1st tax bracket and 1 dollar in the 2nd tax bracket.
The tax rate for the two tax brackets is 0% and 25%, respectively.
In total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.
Example 3:
Input: brackets = [[2,50]], income = 0
Output: 0.00000
Explanation:
You have no income to tax, so you have to pay a total of $0 in taxes.
Constraints:
1 <= brackets.length <= 100
1 <= upperi <= 1000
0 <= percenti <= 100
0 <= income <= 1000
upperi is sorted in ascending order.
All the values of upperi are unique.
The upper bound of the last tax bracket is greater than or equal to income.
| Easy | [
"array",
"simulation"
] | [
"var calculateTax = function(brackets, income) {\n let res = 0\n const arr = brackets\n let first = Math.min(income, arr[0][0])\n res = first * arr[0][1] / 100\n let remain = income - first\n for(let i = 1; i < arr.length; i++) {\n if(remain === 0) break\n const [cur, r] = arr[i]\n const gap = cur - arr[i - 1][0]\n const real = Math.min(gap, remain)\n res += real * r / 100\n remain -= real\n }\n \n return res\n};"
] |
|
2,304 | minimum-path-cost-in-a-grid | [
"What is the optimal cost to get to each of the cells in the second row? What about the third row?",
"Use dynamic programming to compute the optimal cost to get to each cell."
] | /**
* @param {number[][]} grid
* @param {number[][]} moveCost
* @return {number}
*/
var minPathCost = function(grid, moveCost) {
}; | You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x < m - 1, you can move to any of the cells (x + 1, 0), (x + 1, 1), ..., (x + 1, n - 1). Note that it is not possible to move from cells in the last row.
Each possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n, where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j of the next row. The cost of moving from cells in the last row of grid can be ignored.
The cost of a path in grid is the sum of all values of cells visited plus the sum of costs of all the moves made. Return the minimum cost of a path that starts from any cell in the first row and ends at any cell in the last row.
Example 1:
Input: grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]
Output: 17
Explanation: The path with the minimum possible cost is the path 5 -> 0 -> 1.
- The sum of the values of cells visited is 5 + 0 + 1 = 6.
- The cost of moving from 5 to 0 is 3.
- The cost of moving from 0 to 1 is 8.
So the total cost of the path is 6 + 3 + 8 = 17.
Example 2:
Input: grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]
Output: 6
Explanation: The path with the minimum possible cost is the path 2 -> 3.
- The sum of the values of cells visited is 2 + 3 = 5.
- The cost of moving from 2 to 3 is 1.
So the total cost of this path is 5 + 1 = 6.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 50
grid consists of distinct integers from 0 to m * n - 1.
moveCost.length == m * n
moveCost[i].length == n
1 <= moveCost[i][j] <= 100
| Medium | [
"array",
"dynamic-programming",
"matrix"
] | [
"var minPathCost = function(grid, moveCost) {\n const m = grid.length, n = grid[0].length\n const memo = Array.from({ length: 2 }, () => Array(n))\n for(let i = 0; i < n; i++) {\n memo[0][i] = grid[0][i]\n }\n let cur = 0\n for(let i = 0; i < m - 1; i++) {\n const nxt = cur ^ 1\n for(let t = 0; t < n; t++) {\n memo[nxt][t] = Infinity\n }\n for(let j = 0; j < n; j++) {\n const v = grid[i][j]\n for(let k = 0; k < n; k++) {\n const cost = moveCost[v][k]\n memo[nxt][k] = Math.min(memo[nxt][k], memo[cur][j] + grid[i + 1][k] + cost)\n }\n }\n cur ^= 1\n }\n \n return Math.min(...memo[cur])\n};"
] |
|
2,305 | fair-distribution-of-cookies | [
"We have to give each bag to one of the children. How can we enumerate all of the possibilities?",
"Use recursion and keep track of the current number of cookies each child has. Once all the bags have been distributed, find the child with the most cookies."
] | /**
* @param {number[]} cookies
* @param {number} k
* @return {number}
*/
var distributeCookies = function(cookies, k) {
}; | You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.
The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution.
Return the minimum unfairness of all distributions.
Example 1:
Input: cookies = [8,15,10,20,8], k = 2
Output: 31
Explanation: One optimal distribution is [8,15,8] and [10,20]
- The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.
- The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies.
The unfairness of the distribution is max(31,30) = 31.
It can be shown that there is no distribution with an unfairness less than 31.
Example 2:
Input: cookies = [6,1,3,2,2,4,1,2], k = 3
Output: 7
Explanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2]
- The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies.
- The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies.
- The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies.
The unfairness of the distribution is max(7,7,7) = 7.
It can be shown that there is no distribution with an unfairness less than 7.
Constraints:
2 <= cookies.length <= 8
1 <= cookies[i] <= 105
2 <= k <= cookies.length
| Medium | [
"array",
"dynamic-programming",
"backtracking",
"bit-manipulation",
"bitmask"
] | [
"const distributeCookies = function(cookies, k) {\n const n = cookies.length\n let res = Infinity\n const arr = Array(n).fill(0)\n\n bt(0)\n return res\n \n function bt(idx) {\n if(idx === n) {\n res = Math.min(res, Math.max(...arr))\n return\n }\n const cur = cookies[idx]\n const visited = new Set()\n for(let i = 0; i < k; i++) {\n const e = arr[i]\n if(visited.has(arr[i])) continue\n if(cur + e >= res) continue\n visited.add(arr[i])\n arr[i] += cur\n bt(idx + 1)\n arr[i] -= cur\n if(arr[i] === 0) break\n }\n }\n};"
] |
|
2,306 | naming-a-company | [
"How can we divide the ideas into groups to make it easier to find valid pairs?",
"Group ideas that share the same suffix (all characters except the first) together and notice that a pair of ideas from the same group is invalid. What about pairs of ideas from different groups?",
"The first letter of the idea in the first group must not be the first letter of an idea in the second group and vice versa.",
"We can efficiently count the valid pairings for an idea if we already know how many ideas starting with a letter x are within a group that does not contain any ideas with starting letter y for all letters x and y."
] | /**
* @param {string[]} ideas
* @return {number}
*/
var distinctNames = function(ideas) {
}; | You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
Choose 2 distinct names from ideas, call them ideaA and ideaB.
Swap the first letters of ideaA and ideaB with each other.
If both of the new names are not found in the original ideas, then the name ideaA ideaB (the concatenation of ideaA and ideaB, separated by a space) is a valid company name.
Otherwise, it is not a valid name.
Return the number of distinct valid names for the company.
Example 1:
Input: ideas = ["coffee","donuts","time","toffee"]
Output: 6
Explanation: The following selections are valid:
- ("coffee", "donuts"): The company name created is "doffee conuts".
- ("donuts", "coffee"): The company name created is "conuts doffee".
- ("donuts", "time"): The company name created is "tonuts dime".
- ("donuts", "toffee"): The company name created is "tonuts doffee".
- ("time", "donuts"): The company name created is "dime tonuts".
- ("toffee", "donuts"): The company name created is "doffee tonuts".
Therefore, there are a total of 6 distinct company names.
The following are some examples of invalid selections:
- ("coffee", "time"): The name "toffee" formed after swapping already exists in the original array.
- ("time", "toffee"): Both names are still the same after swapping and exist in the original array.
- ("coffee", "toffee"): Both names formed after swapping already exist in the original array.
Example 2:
Input: ideas = ["lack","back"]
Output: 0
Explanation: There are no valid selections. Therefore, 0 is returned.
Constraints:
2 <= ideas.length <= 5 * 104
1 <= ideas[i].length <= 10
ideas[i] consists of lowercase English letters.
All the strings in ideas are unique.
| Hard | [
"array",
"hash-table",
"string",
"bit-manipulation",
"enumeration"
] | [
"const distinctNames = function (ideas) {\n let smap = Array.from({ length: 26 }, (_) => new Set()),\n ans = 0\n for (let i = 0; i < ideas.length; i++) {\n let word = ideas[i]\n smap[word.charCodeAt(0) - 97].add(word.slice(1))\n }\n for (let i = 0; i < 25; i++) {\n let a = smap[i]\n for (let j = i + 1; j < 26; j++) {\n let b = smap[j],\n count = 0\n for (let w of a) if (b.has(w)) count++\n ans += (a.size - count) * (b.size - count) * 2\n }\n }\n return ans\n}"
] |
|
2,309 | greatest-english-letter-in-upper-and-lower-case | [
"Consider iterating through the string and storing each unique character that occurs in a set.",
"From Z to A, check whether both the uppercase and lowercase version occur in the set."
] | /**
* @param {string} s
* @return {string}
*/
var greatestLetter = function(s) {
}; | Given a string of English letters s, return the greatest English letter which occurs as both a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such letter exists, return an empty string.
An English letter b is greater than another letter a if b appears after a in the English alphabet.
Example 1:
Input: s = "lEeTcOdE"
Output: "E"
Explanation:
The letter 'E' is the only letter to appear in both lower and upper case.
Example 2:
Input: s = "arRAzFif"
Output: "R"
Explanation:
The letter 'R' is the greatest letter to appear in both lower and upper case.
Note that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.
Example 3:
Input: s = "AbCdEfGhIjK"
Output: ""
Explanation:
There is no letter that appears in both lower and upper case.
Constraints:
1 <= s.length <= 1000
s consists of lowercase and uppercase English letters.
| Easy | [
"hash-table",
"string",
"enumeration"
] | null | [] |
2,310 | sum-of-numbers-with-units-digit-k | [
"Try solving this recursively.",
"Create a method that takes an integer x as a parameter. This method returns the minimum possible size of a set where each number has units digit k and the sum of the numbers in the set is x."
] | /**
* @param {number} num
* @param {number} k
* @return {number}
*/
var minimumNumbers = function(num, k) {
}; | Given two integers num and k, consider a set of positive integers with the following properties:
The units digit of each integer is k.
The sum of the integers is num.
Return the minimum possible size of such a set, or -1 if no such set exists.
Note:
The set can contain multiple instances of the same integer, and the sum of an empty set is considered 0.
The units digit of a number is the rightmost digit of the number.
Example 1:
Input: num = 58, k = 9
Output: 2
Explanation:
One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9.
Another valid set is [19,39].
It can be shown that 2 is the minimum possible size of a valid set.
Example 2:
Input: num = 37, k = 2
Output: -1
Explanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.
Example 3:
Input: num = 0, k = 7
Output: 0
Explanation: The sum of an empty set is considered 0.
Constraints:
0 <= num <= 3000
0 <= k <= 9
| Medium | [
"math",
"dynamic-programming",
"greedy",
"enumeration"
] | null | [] |
2,311 | longest-binary-subsequence-less-than-or-equal-to-k | [
"Choosing a subsequence from the string is equivalent to deleting all the other digits.",
"If you were to remove a digit, which one should you remove to reduce the value of the string?"
] | /**
* @param {string} s
* @param {number} k
* @return {number}
*/
var longestSubsequence = function(s, k) {
}; | You are given a binary string s and a positive integer k.
Return the length of the longest subsequence of s that makes up a binary number less than or equal to k.
Note:
The subsequence can contain leading zeroes.
The empty string is considered to be equal to 0.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Example 1:
Input: s = "1001010", k = 5
Output: 5
Explanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is "00010", as this number is equal to 2 in decimal.
Note that "00100" and "00101" are also possible, which are equal to 4 and 5 in decimal, respectively.
The length of this subsequence is 5, so 5 is returned.
Example 2:
Input: s = "00101001", k = 1
Output: 6
Explanation: "000001" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.
The length of this subsequence is 6, so 6 is returned.
Constraints:
1 <= s.length <= 1000
s[i] is either '0' or '1'.
1 <= k <= 109
| Medium | [
"string",
"dynamic-programming",
"greedy",
"memoization"
] | [
"const longestSubsequence = function(s, k) {\n let val = 0, pow = 1, oneNum = 0\n for(let i = s.length - 1; i >= 0 && val + pow <= k; i--) {\n if(s[i] === '1') {\n oneNum++\n val += pow\n }\n pow <<= 1\n }\n return cnt(s, '0') + oneNum\n function cnt(s, t) {\n let res = 0\n for(const e of s) {\n if(e === '0') res++\n }\n return res\n }\n};"
] |
|
2,312 | selling-pieces-of-wood | [
"Note down the different actions that can be done on a piece of wood with dimensions m x n. What do you notice?",
"If possible, we could sell the m x n piece. We could also cut the piece vertically creating two pieces of size m x n1 and m x n2 where n1 + n2 = n, or horizontally creating two pieces of size m1 x n and m2 x n where m1 + m2 = m.",
"Notice that cutting a piece breaks the problem down into smaller subproblems, and selling the piece when available is also a case that terminates the process. Thus, we can use DP to efficiently solve this."
] | /**
* @param {number} m
* @param {number} n
* @param {number[][]} prices
* @return {number}
*/
var sellingWood = function(m, n, prices) {
}; | You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars.
To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width.
Return the maximum money you can earn after cutting an m x n piece of wood.
Note that you can cut the piece of wood as many times as you want.
Example 1:
Input: m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]]
Output: 19
Explanation: The diagram above shows a possible scenario. It consists of:
- 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14.
- 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3.
- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.
This obtains a total of 14 + 3 + 2 = 19 money earned.
It can be shown that 19 is the maximum amount of money that can be earned.
Example 2:
Input: m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]]
Output: 32
Explanation: The diagram above shows a possible scenario. It consists of:
- 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30.
- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.
This obtains a total of 30 + 2 = 32 money earned.
It can be shown that 32 is the maximum amount of money that can be earned.
Notice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.
Constraints:
1 <= m, n <= 200
1 <= prices.length <= 2 * 104
prices[i].length == 3
1 <= hi <= m
1 <= wi <= n
1 <= pricei <= 106
All the shapes of wood (hi, wi) are pairwise distinct.
| Hard | [
"array",
"dynamic-programming",
"memoization"
] | [
"const sellingWood = function(m, n, prices) {\n const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n for(const [h, w, p] of prices) {\n dp[h][w] = p\n }\n\n for (let i = 1; i <= m; ++i) {\n for (let j = 1; j <= n; ++j) {\n for (let k = 1; k <= i / 2; ++k) {\n dp[i][j] = Math.max(dp[i][j], dp[k][j] + dp[i - k][j]);\n }\n for (let k = 1; k <= j / 2; ++k) {\n dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[i][j - k]);\n }\n }\n }\n return dp[m][n];\n};",
"const sellingWood = function(m, n, prices) {\n const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n \n for(const [h, w, p] of prices) dp[h][w] = p\n for(let i = 1; i <= m; i++) {\n for(let j = 1; j <= n; j++) {\n for(let k = 1; k <= i / 2; k++) {\n dp[i][j] = Math.max(dp[i][j], dp[k][j] + dp[i - k][j])\n }\n \n for(let k = 1; k <= j / 2; k++) {\n dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[i][j - k])\n }\n }\n }\n \n return dp[m][n]\n};"
] |
|
2,315 | count-asterisks | [
"Iterate through each character, while maintaining whether we are currently between a pair of ‘|’ or not.",
"If we are not in between a pair of ‘|’ and there is a ‘*’, increment the answer by 1."
] | /**
* @param {string} s
* @return {number}
*/
var countAsterisks = function(s) {
}; | You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair, and so forth.
Return the number of '*' in s, excluding the '*' between each pair of '|'.
Note that each '|' will belong to exactly one pair.
Example 1:
Input: s = "l|*e*et|c**o|*de|"
Output: 2
Explanation: The considered characters are underlined: "l|*e*et|c**o|*de|".
The characters between the first and second '|' are excluded from the answer.
Also, the characters between the third and fourth '|' are excluded from the answer.
There are 2 asterisks considered. Therefore, we return 2.
Example 2:
Input: s = "iamprogrammer"
Output: 0
Explanation: In this example, there are no asterisks in s. Therefore, we return 0.
Example 3:
Input: s = "yo|uar|e**|b|e***au|tifu|l"
Output: 5
Explanation: The considered characters are underlined: "yo|uar|e**|b|e***au|tifu|l". There are 5 asterisks considered. Therefore, we return 5.
Constraints:
1 <= s.length <= 1000
s consists of lowercase English letters, vertical bars '|', and asterisks '*'.
s contains an even number of vertical bars '|'.
| Easy | [
"string"
] | null | [] |
2,316 | count-unreachable-pairs-of-nodes-in-an-undirected-graph | [
"Find the connected components of the graph. To find connected components, you can use Union Find (Disjoint Sets), BFS, or DFS.",
"For a node u, the number of nodes that are unreachable from u is the number of nodes that are not in the same connected component as u.",
"The number of unreachable nodes from node u will be the same for the number of nodes that are unreachable from node v if nodes u and v belong to the same connected component."
] | /**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/
var countPairs = function(n, edges) {
}; | You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.
Return the number of pairs of different nodes that are unreachable from each other.
Example 1:
Input: n = 3, edges = [[0,1],[0,2],[1,2]]
Output: 0
Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.
Example 2:
Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]
Output: 14
Explanation: There are 14 pairs of nodes that are unreachable from each other:
[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].
Therefore, we return 14.
Constraints:
1 <= n <= 105
0 <= edges.length <= 2 * 105
edges[i].length == 2
0 <= ai, bi < n
ai != bi
There are no repeated edges.
| Medium | [
"depth-first-search",
"breadth-first-search",
"union-find",
"graph"
] | null | [] |
2,317 | maximum-xor-after-operations | [
"Consider what it means to be able to choose any x for the operation and which integers could be obtained from a given nums[i].",
"The given operation can unset any bit in nums[i].",
"The nth bit of the XOR of all the elements is 1 if the nth bit is 1 for an odd number of elements. When can we ensure it is odd?",
"Try to set every bit of the result to 1 if possible."
] | /**
* @param {number[]} nums
* @return {number}
*/
var maximumXOR = function(nums) {
}; | You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x).
Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation.
Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times.
Example 1:
Input: nums = [3,2,4,6]
Output: 7
Explanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2.
Now, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7.
It can be shown that 7 is the maximum possible bitwise XOR.
Note that other operations may be used to achieve a bitwise XOR of 7.
Example 2:
Input: nums = [1,2,3,9,2]
Output: 11
Explanation: Apply the operation zero times.
The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11.
It can be shown that 11 is the maximum possible bitwise XOR.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 108
| Medium | [
"array",
"math",
"bit-manipulation"
] | [
"const maximumXOR = function(nums) {\n let res = 0\n for(const e of nums) res |= e\n \n return res\n};"
] |
|
2,318 | number-of-distinct-roll-sequences | [
"Can you think of a DP solution?",
"Consider a state that remembers the last 1 or 2 rolls.",
"Do you need to consider the last 3 rolls?"
] | /**
* @param {number} n
* @return {number}
*/
var distinctSequences = function(n) {
}; | You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied:
The greatest common divisor of any adjacent values in the sequence is equal to 1.
There is at least a gap of 2 rolls between equal valued rolls. More formally, if the value of the ith roll is equal to the value of the jth roll, then abs(i - j) > 2.
Return the total number of distinct sequences possible. Since the answer may be very large, return it modulo 109 + 7.
Two sequences are considered distinct if at least one element is different.
Example 1:
Input: n = 4
Output: 184
Explanation: Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.
Some invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6).
(1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed).
(1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3.
There are a total of 184 distinct sequences possible, so we return 184.
Example 2:
Input: n = 2
Output: 22
Explanation: Some of the possible sequences are (1, 2), (2, 1), (3, 2).
Some invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.
There are a total of 22 distinct sequences possible, so we return 22.
Constraints:
1 <= n <= 104
| Hard | [
"dynamic-programming",
"memoization"
] | [
"const distinctSequences = function(n) {\n const hash = {\n 1: [2,3,4,5,6],\n 2: [1,3,5],\n 3: [1,2,4,5],\n 4: [1,3,5],\n 5: [1,2,3,4,6],\n 6: [1,5],\n }\n \n const memo = kdArr(0, [7,7,n+1])\n const mod = 1e9 + 7\n let res = 0\n for(let i = 1; i <= 6; i++) {\n res = (res + dfs(i, 0, n - 1)) % mod\n }\n \n \n return res\n \n function dfs(s,i,j) {\n if(j === 0) return 1\n if(memo[s][i][j] !== 0) return memo[s][i][j]\n let res = 0\n for(let e of hash[s]) {\n if(e !== i) {\n res = (res + dfs(e, s, j - 1)) % mod\n }\n }\n memo[s][i][j] = res\n return res\n }\n \n function kdArr(defaultVal, arr) {\n if(arr.length === 1) return Array(arr[0]).fill(defaultVal)\n \n const res = []\n for(let i = 0, len = arr[0]; i < len; i++) {\n res.push(kdArr(defaultVal, arr.slice(1)))\n }\n \n return res\n }\n};",
"const dp = MultidimensionalArray(0, 1e4 + 1, 7, 7)\nconst distinctSequences = function (n, p = 0, pp = 0) {\n const mod = 1e9 + 7\n if (n === 0) return 1\n if (dp[n][p][pp] === 0) {\n for (let d = 1; d < 7; d++) {\n if (d !== p && d !== pp && (p === 0 || gcd(d, p) === 1)) {\n dp[n][p][pp] = (dp[n][p][pp] + distinctSequences(n - 1, d, p)) % mod\n }\n }\n }\n\n return dp[n][p][pp]\n}\n\nfunction gcd(a, b) {\n return b === 0 ? a : gcd(b, a % b)\n}\n\nfunction MultidimensionalArray(defaultValue, ...args) {\n if (args.length === 1) {\n return Array(args[0]).fill(defaultValue)\n }\n const res = []\n\n for (let i = 0, n = args[0]; i < n; i++) {\n res.push(MultidimensionalArray(defaultValue, ...args.slice(1)))\n }\n\n return res\n}"
] |
|
2,319 | check-if-matrix-is-x-matrix | [
"Assuming a 0-indexed matrix, for a given cell on row i and column j, it is in a diagonal if and only if i == j or i == n - 1 - j.",
"We can then iterate through the elements in the matrix to check if all the elements in the diagonals are non-zero and all other elements are zero."
] | /**
* @param {number[][]} grid
* @return {boolean}
*/
var checkXMatrix = function(grid) {
}; | A square matrix is said to be an X-Matrix if both of the following conditions hold:
All the elements in the diagonals of the matrix are non-zero.
All other elements are 0.
Given a 2D integer array grid of size n x n representing a square matrix, return true if grid is an X-Matrix. Otherwise, return false.
Example 1:
Input: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]
Output: true
Explanation: Refer to the diagram above.
An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.
Thus, grid is an X-Matrix.
Example 2:
Input: grid = [[5,7,0],[0,3,1],[0,5,0]]
Output: false
Explanation: Refer to the diagram above.
An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.
Thus, grid is not an X-Matrix.
Constraints:
n == grid.length == grid[i].length
3 <= n <= 100
0 <= grid[i][j] <= 105
| Easy | [
"array",
"matrix"
] | [
"var checkXMatrix = function(grid) {\n const n = grid.length\n const onDiag = (i, j) => {\n return i === j || j === n - 1 - i\n }\n for(let i = 0; i < n; i++) {\n for(let j = 0;j < n; j++) {\n const valid = onDiag(i, j)\n if(valid) {\n if(grid[i][j] === 0) return false\n }else {\n if(grid[i][j] !== 0) return false\n }\n }\n }\n \n return true\n};"
] |
|
2,320 | count-number-of-ways-to-place-houses | [
"Try coming up with a DP solution for one side of the street.",
"The DP for one side of the street will bear resemblance to the Fibonacci sequence.",
"The number of different arrangements on both side of the street is the same."
] | /**
* @param {number} n
* @return {number}
*/
var countHousePlacements = function(n) {
}; | There is a street with n * 2 plots, where there are n plots on each side of the street. The plots on each side are numbered from 1 to n. On each plot, a house can be placed.
Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street. Since the answer may be very large, return it modulo 109 + 7.
Note that if a house is placed on the ith plot on one side of the street, a house can also be placed on the ith plot on the other side of the street.
Example 1:
Input: n = 1
Output: 4
Explanation:
Possible arrangements:
1. All plots are empty.
2. A house is placed on one side of the street.
3. A house is placed on the other side of the street.
4. Two houses are placed, one on each side of the street.
Example 2:
Input: n = 2
Output: 9
Explanation: The 9 possible arrangements are shown in the diagram above.
Constraints:
1 <= n <= 104
| Medium | [
"dynamic-programming"
] | [
"const countHousePlacements = function(n) {\n const mod = BigInt(1e9 + 7)\n let house = 1n, space = 1n, total = 2n\n for(let i = 2; i <= n; i++) {\n house = space\n space = total\n total = (house + space) % mod\n }\n \n return total * total % mod\n};",
"var countHousePlacements = function(n) {\n const mod = 1e9 + 7\n let f0 = 1;\n let f1 = 1;\n for (let i = 1; i < n; i++) {\n let nf0 = (f0 + f1) % mod;\n let nf1 = f0;\n f0 = nf0;\n f1 = nf1;\n }\n let m = (f0 + f1) % mod;\n return BigInt(m) * BigInt(m) % BigInt(mod)\n};"
] |
|
2,321 | maximum-score-of-spliced-array | [
"Think on Dynamic Programming.",
"First assume you will be taking the array a and choose some subarray from b",
"Suppose the DP is DP(pos, state). pos is the current position you are in. state is one of {0,1,2}, where 0 means taking the array a, 1 means we are taking the subarray b, and 2 means we are again taking the array a. We need to handle the transitions carefully."
] | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var maximumsSplicedArray = function(nums1, nums2) {
}; | You are given two 0-indexed integer arrays nums1 and nums2, both of length n.
You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right].
For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and right = 2, nums1 becomes [1,12,13,4,5] and nums2 becomes [11,2,3,14,15].
You may choose to apply the mentioned operation once or not do anything.
The score of the arrays is the maximum of sum(nums1) and sum(nums2), where sum(arr) is the sum of all the elements in the array arr.
Return the maximum possible score.
A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).
Example 1:
Input: nums1 = [60,60,60], nums2 = [10,90,10]
Output: 210
Explanation: Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10].
The score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.
Example 2:
Input: nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]
Output: 220
Explanation: Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30].
The score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.
Example 3:
Input: nums1 = [7,11,13], nums2 = [1,1,1]
Output: 31
Explanation: We choose not to swap any subarray.
The score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.
Constraints:
n == nums1.length == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 104
| Hard | [
"array",
"dynamic-programming"
] | [
"var maximumsSplicedArray = function(nums1, nums2) {\n let n = nums1.length;\n let arr = new Array(n).fill(0);\n let s1 = 0, s2 = 0;\n for (let i = 0; i < n; i++) {\n s1 += nums1[i];\n s2 += nums2[i];\n }\n for (let i = 0; i < n; i++) {\n arr[i] = nums1[i] - nums2[i];\n }\n let sum = 0;\n let min1 = 0;\n let max1 = 0;\n for (let i = 0; i < n; i++) {\n sum += arr[i];\n max1 = Math.max(sum - min1, max1);\n min1 = Math.min(min1, sum);\n }\n sum = 0;\n let min2 = 0;\n let max2 = 0;\n for (let i = 0; i < n; i++) {\n sum += arr[i];\n min2 = Math.min(sum - max2, min2);\n max2 = Math.max(max2, sum);\n }\n return Math.max(s2 + max1, s1 - min2);\n};",
"const maximumsSplicedArray = function (nums1, nums2) {\n let sum1 = 0,\n sum2 = 0,\n max1 = 0,\n max2 = 0,\n ac1 = 0,\n ac2 = 0\n sum1 = nums1.reduce((ac, e) => ac + e, 0)\n sum2 = nums2.reduce((ac, e) => ac + e, 0)\n const { max } = Math\n let res = max(sum1, sum2)\n for (let i = 0, n = nums1.length; i < n; i++) {\n ac1 += nums1[i] - nums2[i]\n ac2 += nums2[i] - nums1[i] \n max1 = max(max1, ac1)\n max2 = max(max2, ac2)\n if(ac1 < 0) ac1 = 0\n if(ac2 < 0) ac2 = 0\n }\n res = max(res, sum1 + max2, sum2 + max1)\n\n return res\n}"
] |
|
2,322 | minimum-score-after-removals-on-a-tree | [
"Consider iterating over the first edge to remove, and then doing some precalculations on the 2 resulting connected components.",
"Will calculating the XOR of each subtree help?"
] | /**
* @param {number[]} nums
* @param {number[][]} edges
* @return {number}
*/
var minimumScore = function(nums, edges) {
}; | There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the ith node. You are also given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Remove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined:
Get the XOR of all the values of the nodes for each of the three components respectively.
The difference between the largest XOR value and the smallest XOR value is the score of the pair.
For example, say the three components have the node values: [4,5,7], [1,9], and [3,3,3]. The three XOR values are 4 ^ 5 ^ 7 = 6, 1 ^ 9 = 8, and 3 ^ 3 ^ 3 = 3. The largest XOR value is 8 and the smallest XOR value is 3. The score is then 8 - 3 = 5.
Return the minimum score of any possible pair of edge removals on the given tree.
Example 1:
Input: nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]]
Output: 9
Explanation: The diagram above shows a way to make a pair of removals.
- The 1st component has nodes [1,3,4] with values [5,4,11]. Its XOR value is 5 ^ 4 ^ 11 = 10.
- The 2nd component has node [0] with value [1]. Its XOR value is 1 = 1.
- The 3rd component has node [2] with value [5]. Its XOR value is 5 = 5.
The score is the difference between the largest and smallest XOR value which is 10 - 1 = 9.
It can be shown that no other pair of removals will obtain a smaller score than 9.
Example 2:
Input: nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]]
Output: 0
Explanation: The diagram above shows a way to make a pair of removals.
- The 1st component has nodes [3,4] with values [4,4]. Its XOR value is 4 ^ 4 = 0.
- The 2nd component has nodes [1,0] with values [5,5]. Its XOR value is 5 ^ 5 = 0.
- The 3rd component has nodes [2,5] with values [2,2]. Its XOR value is 2 ^ 2 = 0.
The score is the difference between the largest and smallest XOR value which is 0 - 0 = 0.
We cannot obtain a smaller score than 0.
Constraints:
n == nums.length
3 <= n <= 1000
1 <= nums[i] <= 108
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree.
| Hard | [
"array",
"bit-manipulation",
"tree",
"depth-first-search"
] | [
"const minimumScore = function (nums, edges) {\n const n = nums.length, m = edges.length\n const graph = {}\n const children = {}\n const xor = nums.slice(0)\n const degree = Array(n).fill(0)\n\n for(const [p, q] of edges) {\n if(graph[p] == null) graph[p] = []\n if(graph[q] == null) graph[q] = []\n graph[p].push(q)\n graph[q].push(p)\n degree[p]++\n degree[q]++\n }\n\n let val = 0\n const seen = new Set()\n const queue = []\n for(let i = 0; i < n; i++) {\n val ^= nums[i]\n if(degree[i] === 1) {\n queue.push(i)\n seen.add(i)\n }\n }\n\n while(queue.length) {\n const cur = queue.shift()\n for(const nxt of (graph[cur] || [])) {\n if(!seen.has(nxt)) {\n if(children[nxt] == null) children[nxt] = new Set()\n children[nxt].add(cur)\n for(const e of (children[cur] || [])) {\n children[nxt].add(e)\n }\n xor[nxt] ^= xor[cur]\n }\n degree[nxt]--\n if(degree[nxt] === 1) {\n seen.add(nxt)\n queue.push(nxt)\n }\n }\n }\n\n let res = Infinity\n\n for(let i = 0; i < m - 1; i++) {\n for(let j = i + 1; j < m; j++) {\n let [a, b] = edges[i]\n // Let a, c be the lower break points\n if(children[a]?.has(b)) {\n ;[a, b] = [b, a]\n }\n let [c, d] = edges[j]\n if(children[c]?.has(d)) {\n ;[c, d] = [d, c]\n } \n let cur\n if(children[a]?.has(c)) {\n cur = [xor[c], xor[a] ^ xor[c], val ^ xor[a]] \n } else if(children[c]?.has(a)) {\n cur = [xor[a], xor[c] ^ xor[a], val ^ xor[c]]\n } else {\n cur = [xor[a], xor[c], val ^ xor[a] ^ xor[c]]\n }\n res = Math.min(res, Math.max(...cur) - Math.min(...cur))\n }\n }\n\n return res\n}",
"var minimumScore = function (nums, edges) {\n let n = nums.length,\n ans = Infinity\n let visited = Array(n).fill(0)\n let pc = []\n let adj = Array.from({ length: n }, () => [])\n let child_xor = Array(n).fill(0)\n let childs = Array.from({ length: n }, () => Array(n).fill(false))\n const { min, max } = Math\n let par = Array(n).fill(0)\n\n // Creating an adjacency matrix\n for (const edge of edges)\n adj[edge[0]].push(edge[1]), adj[edge[1]].push(edge[0])\n\n dfs(0)\n\n // console.log(childs)\n // console.log(pc)\n for (let i = 0; i < pc.length; i++)\n for (let j = i + 1; j < pc.length; j++) {\n // removing an edge i and j\n let a = pc[i][1],\n b = pc[j][1] // node that will come below when you delete an edge i and j\n let xa = child_xor[a],\n xb = child_xor[b],\n xc = child_xor[0]\n // console.log(a,b)\n if (childs[a][b]) (xc ^= xa), (xa ^= xb)\n else (xc ^= xa), (xc ^= xb)\n\n ans = min(max(xa, max(xb, xc)) - min(xa, min(xb, xc)), ans)\n }\n\n return ans\n\n function dfs(i) {\n let ans = nums[i]\n visited[i] = true\n\n for (let p of par) childs[p][i] = true // Defining this node as the child of all its parents\n\n par.push(i)\n\n for (let child of adj[i] || [])\n if (!visited[child]) {\n pc.push([i, child])\n ans ^= dfs(child) // Recurcively calculating xors\n }\n\n par.pop()\n\n return (child_xor[i] = ans)\n }\n}"
] |
|
2,325 | decode-the-message | [
"Iterate through the characters in the key to construct a mapping to the English alphabet.",
"Make sure to check that the current character is not already in the mapping (only the first appearance is considered).",
"Map the characters in the message according to the constructed mapping."
] | /**
* @param {string} key
* @param {string} message
* @return {string}
*/
var decodeMessage = function(key, message) {
}; | You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows:
Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table.
Align the substitution table with the regular English alphabet.
Each letter in message is then substituted using the table.
Spaces ' ' are transformed to themselves.
For example, given key = "happy boy" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b', 'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f').
Return the decoded message.
Example 1:
Input: key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv"
Output: "this is a secret"
Explanation: The diagram above shows the substitution table.
It is obtained by taking the first appearance of each letter in "the quick brown fox jumps over the lazy dog".
Example 2:
Input: key = "eljuxhpwnyrdgtqkviszcfmabo", message = "zwx hnfx lqantp mnoeius ycgk vcnjrdb"
Output: "the five boxing wizards jump quickly"
Explanation: The diagram above shows the substitution table.
It is obtained by taking the first appearance of each letter in "eljuxhpwnyrdgtqkviszcfmabo".
Constraints:
26 <= key.length <= 2000
key consists of lowercase English letters and ' '.
key contains every letter in the English alphabet ('a' to 'z') at least once.
1 <= message.length <= 2000
message consists of lowercase English letters and ' '.
| Easy | [
"hash-table",
"string"
] | [
"var decodeMessage = function(key, message) {\n const set = new Set()\n for(const ch of key) {\n if(ch !== ' ') set.add(ch)\n if(set.size === 26) break\n }\n const arr = Array.from(set).map((e, i) => [e, i])\n const hash = {}\n for(const [e, i] of arr) {\n hash[e] = i\n }\n // console.log(arr)\n const a = 'a'.charCodeAt(0)\n let res = ''\n for(const ch of message) {\n if(ch === ' ') {\n res += ' '\n continue\n }\n const idx = hash[ch]\n const tmp = String.fromCharCode(a + idx)\n res += tmp\n }\n \n return res\n};"
] |
|
2,326 | spiral-matrix-iv | [
"First, generate an m x n matrix filled with -1s.",
"Navigate within the matrix at (i, j) with the help of a direction vector ⟨di, dj⟩. At (i, j), you need to decide if you can keep going in the current direction.",
"If you cannot keep going, rotate the direction vector clockwise by 90 degrees."
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {number} m
* @param {number} n
* @param {ListNode} head
* @return {number[][]}
*/
var spiralMatrix = function(m, n, head) {
}; | You are given two integers m and n, which represent the dimensions of a matrix.
You are also given the head of a linked list of integers.
Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1.
Return the generated matrix.
Example 1:
Input: m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]
Output: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]
Explanation: The diagram above shows how the values are printed in the matrix.
Note that the remaining spaces in the matrix are filled with -1.
Example 2:
Input: m = 1, n = 4, head = [0,1,2]
Output: [[0,1,2,-1]]
Explanation: The diagram above shows how the values are printed from left to right in the matrix.
The last space in the matrix is set to -1.
Constraints:
1 <= m, n <= 105
1 <= m * n <= 105
The number of nodes in the list is in the range [1, m * n].
0 <= Node.val <= 1000
| Medium | [
"array",
"linked-list",
"matrix",
"simulation"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const spiralMatrix = function (m, n, head) {\n const mat = Array.from({ length: m }, () => Array(n).fill(-1));\n let cur = head;\n const dirs = [\n [0, 1],\n [1, 0],\n [0, -1],\n [-1, 0],\n ];\n let i = 0,\n j = 0,\n left = 0,\n right = n - 1,\n top = 0,\n bottom = m - 1,\n idx = 0;\n while (cur) {\n mat[i][j] = cur.val;\n if (idx === 0 && j === right) {\n idx = (idx + 1) % 4;\n right--;\n } else if (idx === 1 && i === bottom) {\n idx = (idx + 1) % 4;\n bottom--;\n } else if (idx === 2 && j === left) {\n idx = (idx + 1) % 4;\n left++;\n } else if (idx === 3 && i === top + 1) {\n idx = (idx + 1) % 4;\n top++;\n }\n i += dirs[idx][0];\n j += dirs[idx][1];\n cur = cur.next;\n }\n\n return mat;\n};"
] |
2,327 | number-of-people-aware-of-a-secret | [
"Let dp[i][j] be the number of people who have known the secret for exactly j + 1 days, at day i.",
"If j > 0, dp[i][j] = dp[i – 1][j – 1].",
"dp[i][0] = sum(dp[i – 1][j]) for j in [delay – 1, forget – 2]."
] | /**
* @param {number} n
* @param {number} delay
* @param {number} forget
* @return {number}
*/
var peopleAwareOfSecret = function(n, delay, forget) {
}; | On day 1, one person discovers a secret.
You are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards.
Given an integer n, return the number of people who know the secret at the end of day n. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: n = 6, delay = 2, forget = 4
Output: 5
Explanation:
Day 1: Suppose the first person is named A. (1 person)
Day 2: A is the only person who knows the secret. (1 person)
Day 3: A shares the secret with a new person, B. (2 people)
Day 4: A shares the secret with a new person, C. (3 people)
Day 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)
Day 6: B shares the secret with E, and C shares the secret with F. (5 people)
Example 2:
Input: n = 4, delay = 1, forget = 3
Output: 6
Explanation:
Day 1: The first person is named A. (1 person)
Day 2: A shares the secret with B. (2 people)
Day 3: A and B share the secret with 2 new people, C and D. (4 people)
Day 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)
Constraints:
2 <= n <= 1000
1 <= delay < forget <= n
| Medium | [
"dynamic-programming",
"queue",
"simulation"
] | [
"const peopleAwareOfSecret = function(n, delay, forget) {\n const dp = Array(n + 1).fill(0)\n const mod = 1e9 + 7\n \n dp[1] = 1\n for(let i = 1; i <= n; i++) {\n for(let j = i + delay; j < i + forget; j++) {\n if(j > n) break\n dp[j] += dp[i]\n dp[j] %= mod\n }\n }\n\n let res = 0\n for(let i = n - forget + 1; i <= n; i++) {\n res = (dp[i] + res) % mod\n }\n \n return res\n};",
"const peopleAwareOfSecret = function(n, delay, forget) {\n let cnt = new Array(n+1).fill(0);\n cnt[1] = 1;\n let i = 1;\n let MOD = 1_000_000_007;\n while (i+delay <= n) {\n for (let j = i+delay; j <= Math.min(n, i+forget-1); j++) {\n cnt[j] = (cnt[j]+cnt[i])%MOD;\n }\n i++;\n }\n let res = 0;\n for (let j = n; j > n-forget; j--) {\n res = (res + cnt[j])%MOD;\n }\n return res;\n};",
" const peopleAwareOfSecret = function(n, delay, forget) {\n const mod = 1e9 + 7\n const dp = Array(n + 1).fill(0)\n const { max } = Math\n dp[1] = 1\n let share = 0\n for(let i = 2; i <= n; i++) {\n share = (share + dp[max(0, i - delay)] - dp[max(i - forget, 0)] + mod) % mod\n dp[i] = share\n }\n let res = 0\n for(let i = n - forget + 1; i <= n; i++) {\n res = (res + dp[i]) % mod\n }\n return res\n};"
] |
|
2,328 | number-of-increasing-paths-in-a-grid | [
"How can you calculate the number of increasing paths that start from a cell (i, j)? Think about dynamic programming.",
"Define f(i, j) as the number of increasing paths starting from cell (i, j). Try to find how f(i, j) is related to each of f(i, j+1), f(i, j-1), f(i+1, j) and f(i-1, j)."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var countPaths = function(grid) {
}; | You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions.
Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7.
Two paths are considered different if they do not have exactly the same sequence of visited cells.
Example 1:
Input: grid = [[1,1],[3,4]]
Output: 8
Explanation: The strictly increasing paths are:
- Paths with length 1: [1], [1], [3], [4].
- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].
- Paths with length 3: [1 -> 3 -> 4].
The total number of paths is 4 + 3 + 1 = 8.
Example 2:
Input: grid = [[1],[2]]
Output: 3
Explanation: The strictly increasing paths are:
- Paths with length 1: [1], [2].
- Paths with length 2: [1 -> 2].
The total number of paths is 2 + 1 = 3.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
1 <= grid[i][j] <= 105
| Hard | [
"array",
"dynamic-programming",
"depth-first-search",
"breadth-first-search",
"graph",
"topological-sort",
"memoization",
"matrix"
] | [
"const countPaths = function (grid) {\n const mod = 1e9 + 7\n const m = grid.length, n = grid[0].length\n let res = 0\n const dirs = [[1,0], [-1,0], [0, 1], [0, -1]]\n const memo = 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 res = (res + dfs(i, j)) % mod\n }\n } \n return res\n \n function dfs(i, j) {\n let res = 1\n if(memo[i][j] !== 0) return memo[i][j]\n for(const [dx, dy] of dirs) {\n const nx = i + dx, ny = j + dy\n if(nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] > grid[i][j]) {\n res = (res + dfs(nx, ny)) % mod\n }\n }\n \n memo[i][j] = res\n \n return res\n }\n}",
"var countPaths = function (grid) {\n const MOD = 1e9 + 7\n let res = 0\n const M = grid.length,\n N = grid[0].length\n\n const dp = Array.from({ length: M }, () => Array(N))\n\n for (let r = 0; r < M; r++) {\n for (let c = 0; c < N; c++) {\n res = (res + dfs(r, c)) % MOD\n }\n }\n return res\n\n function dfs(r, c) {\n if (dp[r][c] != null) {\n return dp[r][c]\n }\n let res = 1\n\n for (const dir of [\n [-1, 0],\n [0, -1],\n [1, 0],\n [0, 1],\n ]) {\n const nr = r + dir[0],\n nc = c + dir[1]\n if (\n nr < 0 ||\n nr >= M ||\n nc < 0 ||\n nc >= N ||\n grid[nr][nc] <= grid[r][c]\n ) {\n continue\n }\n res = (res + dfs(nr, nc)) % MOD\n }\n dp[r][c] = res\n return res\n }\n}"
] |
|
2,331 | evaluate-boolean-binary-tree | [
"Traverse the tree using depth-first search in post-order.",
"Can you use recursion to solve this easily?"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var evaluateTree = function(root) {
}; | You are given the root of a full binary tree with the following properties:
Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True.
Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND.
The evaluation of a node is as follows:
If the node is a leaf node, the evaluation is the value of the node, i.e. True or False.
Otherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations.
Return the boolean result of evaluating the root node.
A full binary tree is a binary tree where each node has either 0 or 2 children.
A leaf node is a node that has zero children.
Example 1:
Input: root = [2,1,3,null,null,0,1]
Output: true
Explanation: The above diagram illustrates the evaluation process.
The AND node evaluates to False AND True = False.
The OR node evaluates to True OR False = True.
The root node evaluates to True, so we return true.
Example 2:
Input: root = [0]
Output: false
Explanation: The root node is a leaf node and it evaluates to false, so we return false.
Constraints:
The number of nodes in the tree is in the range [1, 1000].
0 <= Node.val <= 3
Every node has either 0 or 2 children.
Leaf nodes have a value of 0 or 1.
Non-leaf nodes have a value of 2 or 3.
| Easy | [
"tree",
"depth-first-search",
"binary-tree"
] | null | [] |
2,332 | the-latest-time-to-catch-a-bus | [
"Sort the buses and passengers arrays.",
"Use 2 pointers to traverse buses and passengers with a simulation of passengers getting on a particular bus."
] | /**
* @param {number[]} buses
* @param {number[]} passengers
* @param {number} capacity
* @return {number}
*/
var latestTimeCatchTheBus = function(buses, passengers, capacity) {
}; | You are given a 0-indexed integer array buses of length n, where buses[i] represents the departure time of the ith bus. You are also given a 0-indexed integer array passengers of length m, where passengers[j] represents the arrival time of the jth passenger. All bus departure times are unique. All passenger arrival times are unique.
You are given an integer capacity, which represents the maximum number of passengers that can get on each bus.
When a passenger arrives, they will wait in line for the next available bus. You can get on a bus that departs at x minutes if you arrive at y minutes where y <= x, and the bus is not full. Passengers with the earliest arrival times get on the bus first.
More formally when a bus arrives, either:
If capacity or fewer passengers are waiting for a bus, they will all get on the bus, or
The capacity passengers with the earliest arrival times will get on the bus.
Return the latest time you may arrive at the bus station to catch a bus. You cannot arrive at the same time as another passenger.
Note: The arrays buses and passengers are not necessarily sorted.
Example 1:
Input: buses = [10,20], passengers = [2,17,18,19], capacity = 2
Output: 16
Explanation: Suppose you arrive at time 16.
At time 10, the first bus departs with the 0th passenger.
At time 20, the second bus departs with you and the 1st passenger.
Note that you may not arrive at the same time as another passenger, which is why you must arrive before the 1st passenger to catch the bus.
Example 2:
Input: buses = [20,30,10], passengers = [19,13,26,4,25,11,21], capacity = 2
Output: 20
Explanation: Suppose you arrive at time 20.
At time 10, the first bus departs with the 3rd passenger.
At time 20, the second bus departs with the 5th and 1st passengers.
At time 30, the third bus departs with the 0th passenger and you.
Notice if you had arrived any later, then the 6th passenger would have taken your seat on the third bus.
Constraints:
n == buses.length
m == passengers.length
1 <= n, m, capacity <= 105
2 <= buses[i], passengers[i] <= 109
Each element in buses is unique.
Each element in passengers is unique.
| Medium | [
"array",
"two-pointers",
"binary-search",
"sorting"
] | [
"const latestTimeCatchTheBus = function(buses, passengers, capacity) {\n buses.sort((b1, b2) => b1 - b2)\n passengers.sort((p1, p2) => p1 - p2)\n \n const passengersSet = new Set(passengers)\n \n let j = 0\n let lastBus = []\n for (let i = 0; i < buses.length; i++) {\n let k = j\n let currentBus = []\n while (k - j < capacity && passengers[k] <= buses[i]) {\n currentBus.push(passengers[k])\n k++\n }\n lastBus = currentBus\n j = k\n }\n \n let lastArrival\n if (lastBus.length == capacity) {\n lastArrival = lastBus[capacity - 1]\n while (passengersSet.has(lastArrival)) {\n lastArrival--\n }\n } else {\n lastArrival = buses[buses.length - 1]\n \n while (passengersSet.has(lastArrival)) {\n lastArrival--\n }\n }\n \n \n return lastArrival\n};"
] |
|
2,333 | minimum-sum-of-squared-difference | [
"There is no difference between the purpose of k1 and k2. Adding +1 to one element in nums1 is same as performing -1 to one element in nums2, and vice versa.",
"Reduce the sum of squared difference greedily. One operation of k should use the index that has the current maximum difference.",
"Binary search the maximum difference for the final result."
] | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number} k1
* @param {number} k2
* @return {number}
*/
var minSumSquareDiff = function(nums1, nums2, k1, k2) {
}; | You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n.
The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i])2 for each 0 <= i < n.
You are also given two positive integers k1 and k2. You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times.
Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times.
Note: You are allowed to modify the array elements to become negative integers.
Example 1:
Input: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0
Output: 579
Explanation: The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0.
The sum of square difference will be: (1 - 2)2 + (2 - 10)2 + (3 - 20)2 + (4 - 19)2 = 579.
Example 2:
Input: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1
Output: 43
Explanation: One way to obtain the minimum sum of square difference is:
- Increase nums1[0] once.
- Increase nums2[2] once.
The minimum of the sum of square difference will be:
(2 - 5)2 + (4 - 8)2 + (10 - 7)2 + (12 - 9)2 = 43.
Note that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.
Constraints:
n == nums1.length == nums2.length
1 <= n <= 105
0 <= nums1[i], nums2[i] <= 105
0 <= k1, k2 <= 109
| Medium | [
"array",
"math",
"sorting",
"heap-priority-queue"
] | [
"const minSumSquareDiff = function (nums1, nums2, k1, k2) {\n const n = nums1.length\n const diff = Array(n).fill(0)\n for (let i = 0; i < n; ++i) {\n diff[i] = Math.abs(nums1[i] - nums2[i])\n }\n const M = Math.max(...diff)\n const bucket = Array(M + 1).fill(0)\n for (let i = 0; i < n; i++) {\n bucket[diff[i]]++\n }\n let k = k1 + k2\n for (let i = M; i > 0 && k; i--) {\n if (bucket[i] > 0) {\n const minus = Math.min(bucket[i], k)\n bucket[i] -= minus\n bucket[i - 1] += minus\n k -= minus\n }\n }\n let res = 0\n for (let i = M; i > 0; --i) {\n res += bucket[i] * i * i\n }\n return res\n}"
] |
|
2,334 | subarray-with-elements-greater-than-varying-threshold | [
"For all elements to be greater than the threshold/length, the minimum element in the subarray must be greater than the threshold/length.",
"For a given index, could you find the largest subarray such that the given index is the minimum element?",
"Could you use a monotonic stack to get the next and previous smallest element for every index?"
] | /**
* @param {number[]} nums
* @param {number} threshold
* @return {number}
*/
var validSubarraySize = function(nums, threshold) {
}; | You are given an integer array nums and an integer threshold.
Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k.
Return the size of any such subarray. If there is no such subarray, return -1.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,3,4,3,1], threshold = 6
Output: 3
Explanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2.
Note that this is the only valid subarray.
Example 2:
Input: nums = [6,5,6,5,8], threshold = 7
Output: 1
Explanation: The subarray [8] has a size of 1, and 8 > 7 / 1 = 7. So 1 is returned.
Note that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5.
Similarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions.
Therefore, 2, 3, 4, or 5 may also be returned.
Constraints:
1 <= nums.length <= 105
1 <= nums[i], threshold <= 109
| Hard | [
"array",
"stack",
"union-find",
"monotonic-stack"
] | [
"const validSubarraySize = function (nums, threshold) {\n const n = nums.length\n\n let stk = []\n // used for storing next and previous smaller elements\n const nextS = Array(n).fill(-1)\n const prevS = Array(n).fill(-1)\n\n // firstly, let's find out the next smaller elements\n for (let i = 0; i < n; i++) {\n while (stk.length && nums[i] < nums[back(stk)]) {\n nextS[back(stk)] = i\n stk.pop()\n }\n stk.push(i)\n }\n\n stk = []\n\n // find out the previous smaller elements for each index\n for (let i = n - 1; i >= 0; i--) {\n while (stk.length && nums[i] < nums[back(stk)]) {\n prevS[back(stk)] = i\n stk.pop()\n }\n stk.push(i)\n }\n\n for (let i = 0; i < n; i++) {\n // left boundary\n const left = prevS[i]\n // right boundary\n const right = nextS[i] == -1 ? n : nextS[i]\n // length of subarray formed with nums[i] as minimum\n const len = right - left - 1\n\n if (nums[i] > threshold / len) return len\n }\n\n return -1\n\n function back(arr) {\n return arr[arr.length - 1]\n }\n}"
] |
|
2,335 | minimum-amount-of-time-to-fill-cups | [
"To minimize the amount of time needed, you want to fill up as many cups as possible in each second. This means that you want to maximize the number of seconds where you are filling up two cups.",
"You always want to fill up the two types of water with the most unfilled cups."
] | /**
* @param {number[]} amount
* @return {number}
*/
var fillCups = function(amount) {
}; | You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water.
You are given a 0-indexed integer array amount of length 3 where amount[0], amount[1], and amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups.
Example 1:
Input: amount = [1,4,2]
Output: 4
Explanation: One way to fill up the cups is:
Second 1: Fill up a cold cup and a warm cup.
Second 2: Fill up a warm cup and a hot cup.
Second 3: Fill up a warm cup and a hot cup.
Second 4: Fill up a warm cup.
It can be proven that 4 is the minimum number of seconds needed.
Example 2:
Input: amount = [5,4,4]
Output: 7
Explanation: One way to fill up the cups is:
Second 1: Fill up a cold cup, and a hot cup.
Second 2: Fill up a cold cup, and a warm cup.
Second 3: Fill up a cold cup, and a warm cup.
Second 4: Fill up a warm cup, and a hot cup.
Second 5: Fill up a cold cup, and a hot cup.
Second 6: Fill up a cold cup, and a warm cup.
Second 7: Fill up a hot cup.
Example 3:
Input: amount = [5,0,0]
Output: 5
Explanation: Every second, we fill up a cold cup.
Constraints:
amount.length == 3
0 <= amount[i] <= 100
| Easy | [
"array",
"greedy",
"sorting",
"heap-priority-queue"
] | [
"const fillCups = function(amount) {\n amount.sort((a, b) => a- b)\n let res = 0;\n while (amount[2] !== 0) {\n res++;\n amount[2]--;\n if (amount[1] > 0) {\n amount[1]--;\n }\n amount.sort((a, b) => a- b)\n }\n return res; \n};"
] |
|
2,336 | smallest-number-in-infinite-set | [
"Based on the constraints, what is the maximum element that can possibly be popped?",
"Maintain whether elements are in or not in the set. How many elements do we consider?"
] |
var SmallestInfiniteSet = function() {
};
/**
* @return {number}
*/
SmallestInfiniteSet.prototype.popSmallest = function() {
};
/**
* @param {number} num
* @return {void}
*/
SmallestInfiniteSet.prototype.addBack = function(num) {
};
/**
* Your SmallestInfiniteSet object will be instantiated and called as such:
* var obj = new SmallestInfiniteSet()
* var param_1 = obj.popSmallest()
* obj.addBack(num)
*/ | You have a set which contains all positive integers [1, 2, 3, 4, 5, ...].
Implement the SmallestInfiniteSet class:
SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.
int popSmallest() Removes and returns the smallest integer contained in the infinite set.
void addBack(int num) Adds a positive integer num back into the infinite set, if it is not already in the infinite set.
Example 1:
Input
["SmallestInfiniteSet", "addBack", "popSmallest", "popSmallest", "popSmallest", "addBack", "popSmallest", "popSmallest", "popSmallest"]
[[], [2], [], [], [], [1], [], [], []]
Output
[null, null, 1, 2, 3, null, 1, 4, 5]
Explanation
SmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();
smallestInfiniteSet.addBack(2); // 2 is already in the set, so no change is made.
smallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.
smallestInfiniteSet.addBack(1); // 1 is added back to the set.
smallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and
// is the smallest number, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.
Constraints:
1 <= num <= 1000
At most 1000 calls will be made in total to popSmallest and addBack.
| Medium | [
"hash-table",
"design",
"heap-priority-queue"
] | [
"const SmallestInfiniteSet = function() {\n this.nums = new Set(Array.from({ length: 1001 }, (e, i) => i + 1))\n this.tmp = new Set()\n};\n\n\nSmallestInfiniteSet.prototype.popSmallest = function() {\n const min = Math.min(...this.nums)\n this.nums.delete(min)\n this.tmp.add(min)\n return min\n};\n\n\nSmallestInfiniteSet.prototype.addBack = function(num) {\n if(this.tmp.has(num)) {\n this.tmp.delete(num)\n this.nums.add(num)\n } \n};"
] |
|
2,337 | move-pieces-to-obtain-a-string | [
"After some sequence of moves, can the order of the pieces change?",
"Try to match each piece in s with a piece in e."
] | /**
* @param {string} start
* @param {string} target
* @return {boolean}
*/
var canChange = function(start, target) {
}; | You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where:
The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there is a blank space directly to its right.
The character '_' represents a blank space that can be occupied by any of the 'L' or 'R' pieces.
Return true if it is possible to obtain the string target by moving the pieces of the string start any number of times. Otherwise, return false.
Example 1:
Input: start = "_L__R__R_", target = "L______RR"
Output: true
Explanation: We can obtain the string target from start by doing the following moves:
- Move the first piece one step to the left, start becomes equal to "L___R__R_".
- Move the last piece one step to the right, start becomes equal to "L___R___R".
- Move the second piece three steps to the right, start becomes equal to "L______RR".
Since it is possible to get the string target from start, we return true.
Example 2:
Input: start = "R_L_", target = "__LR"
Output: false
Explanation: The 'R' piece in the string start can move one step to the right to obtain "_RL_".
After that, no pieces can move anymore, so it is impossible to obtain the string target from start.
Example 3:
Input: start = "_R", target = "R_"
Output: false
Explanation: The piece in the string start can move only to the right, so it is impossible to obtain the string target from start.
Constraints:
n == start.length == target.length
1 <= n <= 105
start and target consist of the characters 'L', 'R', and '_'.
| Medium | [
"two-pointers",
"string"
] | [
"const canChange = function(start, target) {\n const n=target.length;\n let i=0,j=0;\n while(i<=n && j<=n){\n\n while(i<n && target[i]==='_') i++;\n while(j<n && start[j]==='_') j++;\n\n if(i===n || j===n){\n return i===n && j===n;\n }\n\n if(target[i]!==start[j]) return false;\n\n if(target[i]==='L'){\n if(j<i) return false;\n }\n else{\n if(i<j) return false;\n }\n\n i++;\n j++;\n }\n return true;\n};"
] |
|
2,338 | count-the-number-of-ideal-arrays | [
"Notice that an ideal array is non-decreasing.",
"Consider an alternative problem: where an ideal array must also be strictly increasing. Can you use DP to solve it?",
"Will combinatorics help to get an answer from the alternative problem to the actual problem?"
] | /**
* @param {number} n
* @param {number} maxValue
* @return {number}
*/
var idealArrays = function(n, maxValue) {
}; | You are given two integers n and maxValue, which are used to describe an ideal array.
A 0-indexed integer array arr of length n is considered ideal if the following conditions hold:
Every arr[i] is a value from 1 to maxValue, for 0 <= i < n.
Every arr[i] is divisible by arr[i - 1], for 0 < i < n.
Return the number of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: n = 2, maxValue = 5
Output: 10
Explanation: The following are the possible ideal arrays:
- Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5]
- Arrays starting with the value 2 (2 arrays): [2,2], [2,4]
- Arrays starting with the value 3 (1 array): [3,3]
- Arrays starting with the value 4 (1 array): [4,4]
- Arrays starting with the value 5 (1 array): [5,5]
There are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.
Example 2:
Input: n = 5, maxValue = 3
Output: 11
Explanation: The following are the possible ideal arrays:
- Arrays starting with the value 1 (9 arrays):
- With no other distinct values (1 array): [1,1,1,1,1]
- With 2nd distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]
- With 2nd distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3]
- Arrays starting with the value 2 (1 array): [2,2,2,2,2]
- Arrays starting with the value 3 (1 array): [3,3,3,3,3]
There are a total of 9 + 1 + 1 = 11 distinct ideal arrays.
Constraints:
2 <= n <= 104
1 <= maxValue <= 104
| Hard | [
"math",
"dynamic-programming",
"combinatorics",
"number-theory"
] | [
"const ll = BigInt, mod = ll(1e9 + 7), N = 1e4 + 15;\n\nconst hcomb = (p, q) => p == 0 && q == 0 ? 1 : comb(p + q - 1, q);\nconst comb_init = () => {\n fact[0] = ifact[0] = inv[1] = 1n; // factorial, inverse factorial\n for (let i = 2; i < N; i++) inv[i] = (mod - mod / ll(i)) * inv[mod % ll(i)] % mod;\n for (let i = 1; i < N; i++) {\n fact[i] = fact[i - 1] * ll(i) % mod;\n ifact[i] = ifact[i - 1] * inv[i] % mod;\n }\n};\n\n// combination mod pick k from n\nconst comb = (n, k) => {\n if (n < k || k < 0) return 0;\n return fact[n] * ifact[k] % mod * ifact[n - k] % mod;\n};\n\n\nconst number_factor = (n) => {\n let m = new Map();\n for (let i = 2; i * i <= n; i++) {\n while (n % i == 0) {\n n /= i;\n m.set(i, m.get(i) + 1 || 1);\n }\n }\n if (n > 1) m.set(n, m.get(n) + 1 || 1);\n return m;\n};\n\nlet fact, ifact, inv;\nconst idealArrays = (n, maxValue) => {\n fact = Array(N).fill(0), ifact = Array(N).fill(0), inv = Array(N).fill(0);\n comb_init();\n let res = 0n;\n for (let x = 1; x <= maxValue; x++) {\n let perm = 1n, m = number_factor(x);\n for (const [x, occ] of m) {\n perm = perm * hcomb(n, occ) % mod;\n }\n res += perm;\n }\n return res % mod;\n};"
] |
|
2,341 | maximum-number-of-pairs-in-array | [
"What do we need to know to find how many pairs we can make? We need to know the frequency of each integer.",
"When will there be a leftover number? When the frequency of an integer is an odd number."
] | /**
* @param {number[]} nums
* @return {number[]}
*/
var numberOfPairs = function(nums) {
}; | You are given a 0-indexed integer array nums. In one operation, you may do the following:
Choose two integers in nums that are equal.
Remove both integers from nums, forming a pair.
The operation is done on nums as many times as possible.
Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible.
Example 1:
Input: nums = [1,3,2,1,3,2,2]
Output: [3,1]
Explanation:
Form a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2].
Form a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2].
Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2].
No more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.
Example 2:
Input: nums = [1,1]
Output: [1,0]
Explanation: Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [].
No more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.
Example 3:
Input: nums = [0]
Output: [0,1]
Explanation: No pairs can be formed, and there is 1 number leftover in nums.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
| Easy | [
"array",
"hash-table",
"counting"
] | [
"var numberOfPairs = function(nums) {\n const n = nums.length\n let res = 0\n const hash = {}\n for(const e of nums) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n if(hash[e] === 2) {\n res++\n hash[e] = 0\n }\n }\n \n return [res, n - res * 2]\n};"
] |
|
2,342 | max-sum-of-a-pair-with-equal-sum-of-digits | [
"What is the largest possible sum of digits a number can have?",
"Group the array elements by the sum of their digits, and find the largest two elements of each group."
] | /**
* @param {number[]} nums
* @return {number}
*/
var maximumSum = function(nums) {
}; | You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j].
Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions.
Example 1:
Input: nums = [18,43,36,13,7]
Output: 54
Explanation: The pairs (i, j) that satisfy the conditions are:
- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.
- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.
So the maximum sum that we can obtain is 54.
Example 2:
Input: nums = [10,12,19,14]
Output: -1
Explanation: There are no two numbers that satisfy the conditions, so we return -1.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
| Medium | [
"array",
"hash-table",
"sorting",
"heap-priority-queue"
] | [
"const maximumSum = function(nums) {\n const map = new Map()\n for(const e of nums) {\n const k = dSum(e)\n add(map, k, e)\n }\n // console.log(map)\n let res = -1\n for(const [k, v] of map) {\n if(v.length === 2) {\n res = Math.max(res, v[0] + v[1])\n }\n }\n \n return res\n \n \n function add(map, k, v) {\n if(!map.has(k)) {\n map.set(k, [v])\n } else {\n if(map.get(k).length === 1) {\n map.get(k).push(v)\n } else {\n const arr = map.get(k)\n arr.push(v)\n arr.sort((a, b) => b - a)\n arr.splice(2, 1)\n }\n }\n }\n \n function dSum(num) {\n let res = 0\n \n let cur = num\n while(cur) {\n res += cur % 10\n cur = ~~(cur / 10)\n }\n \n return res\n }\n};"
] |
|
2,343 | query-kth-smallest-trimmed-number | [
"Run a simulation to follow the requirement of each query."
] | /**
* @param {string[]} nums
* @param {number[][]} queries
* @return {number[]}
*/
var smallestTrimmedNumbers = function(nums, queries) {
}; | You are given a 0-indexed array of strings nums, where each string is of equal length and consists of only digits.
You are also given a 0-indexed 2D integer array queries where queries[i] = [ki, trimi]. For each queries[i], you need to:
Trim each number in nums to its rightmost trimi digits.
Determine the index of the kith smallest trimmed number in nums. If two trimmed numbers are equal, the number with the lower index is considered to be smaller.
Reset each number in nums to its original length.
Return an array answer of the same length as queries, where answer[i] is the answer to the ith query.
Note:
To trim to the rightmost x digits means to keep removing the leftmost digit, until only x digits remain.
Strings in nums may contain leading zeros.
Example 1:
Input: nums = ["102","473","251","814"], queries = [[1,1],[2,3],[4,2],[1,2]]
Output: [2,2,1,0]
Explanation:
1. After trimming to the last digit, nums = ["2","3","1","4"]. The smallest number is 1 at index 2.
2. Trimmed to the last 3 digits, nums is unchanged. The 2nd smallest number is 251 at index 2.
3. Trimmed to the last 2 digits, nums = ["02","73","51","14"]. The 4th smallest number is 73.
4. Trimmed to the last 2 digits, the smallest number is 2 at index 0.
Note that the trimmed number "02" is evaluated as 2.
Example 2:
Input: nums = ["24","37","96","04"], queries = [[2,1],[2,2]]
Output: [3,0]
Explanation:
1. Trimmed to the last digit, nums = ["4","7","6","4"]. The 2nd smallest number is 4 at index 3.
There are two occurrences of 4, but the one at index 0 is considered smaller than the one at index 3.
2. Trimmed to the last 2 digits, nums is unchanged. The 2nd smallest number is 24.
Constraints:
1 <= nums.length <= 100
1 <= nums[i].length <= 100
nums[i] consists of only digits.
All nums[i].length are equal.
1 <= queries.length <= 100
queries[i].length == 2
1 <= ki <= nums.length
1 <= trimi <= nums[i].length
Follow up: Could you use the Radix Sort Algorithm to solve this problem? What will be the complexity of that solution?
| Medium | [
"array",
"string",
"divide-and-conquer",
"sorting",
"heap-priority-queue",
"radix-sort",
"quickselect"
] | [
"const smallestTrimmedNumbers = function(nums, queries) {\n const m = nums.length, n = queries.length, len = nums[0].length\n const res = []\n \n for(const [k, trim] of queries) {\n const tmp = nums.map(e => e.slice(trim>len?0:len - trim))\n // console.log(trim, tmp)\n const clone = tmp.slice().map((e,i) => ({v:e,i}))\n clone.sort((a, b) => {\n a = BigInt(a.v)\n b = BigInt(b.v)\n if(a > b) {\n return 1;\n } else if (a < b){\n return -1;\n } else {\n return 0;\n }\n })\n // console.log(clone)\n const el = clone[k - 1]\n // const idx = tmp.lastIndexOf(el)\n res.push(el.i)\n }\n \n return res\n};"
] |
|
2,344 | minimum-deletions-to-make-array-divisible | [
"How can we find an integer x that divides all the elements of numsDivide?",
"Will finding GCD (Greatest Common Divisor) help here?"
] | /**
* @param {number[]} nums
* @param {number[]} numsDivide
* @return {number}
*/
var minOperations = function(nums, numsDivide) {
}; | You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums.
Return the minimum number of deletions such that the smallest element in nums divides all the elements of numsDivide. If this is not possible, return -1.
Note that an integer x divides y if y % x == 0.
Example 1:
Input: nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15]
Output: 2
Explanation:
The smallest element in [2,3,2,4,3] is 2, which does not divide all the elements of numsDivide.
We use 2 deletions to delete the elements in nums that are equal to 2 which makes nums = [3,4,3].
The smallest element in [3,4,3] is 3, which divides all the elements of numsDivide.
It can be shown that 2 is the minimum number of deletions needed.
Example 2:
Input: nums = [4,3,6], numsDivide = [8,2,6,10]
Output: -1
Explanation:
We want the smallest element in nums to divide all the elements of numsDivide.
There is no way to delete elements from nums to allow this.
Constraints:
1 <= nums.length, numsDivide.length <= 105
1 <= nums[i], numsDivide[i] <= 109
| Hard | [
"array",
"math",
"sorting",
"heap-priority-queue",
"number-theory"
] | [
"const minOperations = function (nums, numsDivide) {\n nums.sort((a, b) => a - b)\n let gcdVal = numsDivide[0]\n\n for(let i = 1, n = numsDivide.length; i < n; i++) {\n gcdVal = gcd(gcdVal, numsDivide[i])\n }\n\n for(let i = 0, n = nums.length; i < n && nums[i] <= gcdVal; i++) {\n if(gcdVal % nums[i] === 0) return i\n }\n\n return -1\n\n\n function gcd(a,b) {\n return b === 0 ? a : gcd(b, a % b)\n }\n}",
"var minOperations = function(nums, numsDivide) {\n let div = numsDivide[0], min = Infinity\n for(let i = 1, n = numsDivide.length; i < n; i++) {\n div = Math.min(div, gcd(numsDivide[i], div))\n min = Math.min(min, numsDivide[i])\n }\n // console.log(div)\n\n nums.sort((a, b) => a - b)\n if(div === 1 && nums[0] !== 1) return -1\n let res = 0\n for(const e of nums) {\n if(e > min) break\n if(div % e === 0) {\n return res\n }\n if(e % div !== 0) res++\n else {\n return res\n }\n }\n \n return -1\n \n function gcd(a, b) {\n return b === 0 ? a : gcd(b, a % b)\n }\n};"
] |
|
2,347 | best-poker-hand | [
"Sequentially check the conditions 1 through 4, and return the outcome corresponding to the first met condition."
] | /**
* @param {number[]} ranks
* @param {character[]} suits
* @return {string}
*/
var bestHand = function(ranks, suits) {
}; | You are given an integer array ranks and a character array suits. You have 5 cards where the ith card has a rank of ranks[i] and a suit of suits[i].
The following are the types of poker hands you can make from best to worst:
"Flush": Five cards of the same suit.
"Three of a Kind": Three cards of the same rank.
"Pair": Two cards of the same rank.
"High Card": Any single card.
Return a string representing the best type of poker hand you can make with the given cards.
Note that the return values are case-sensitive.
Example 1:
Input: ranks = [13,2,3,1,9], suits = ["a","a","a","a","a"]
Output: "Flush"
Explanation: The hand with all the cards consists of 5 cards with the same suit, so we have a "Flush".
Example 2:
Input: ranks = [4,4,2,4,4], suits = ["d","a","a","b","c"]
Output: "Three of a Kind"
Explanation: The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a "Three of a Kind".
Note that we could also make a "Pair" hand but "Three of a Kind" is a better hand.
Also note that other cards could be used to make the "Three of a Kind" hand.
Example 3:
Input: ranks = [10,10,2,12,9], suits = ["a","b","c","a","d"]
Output: "Pair"
Explanation: The hand with the first and second card consists of 2 cards with the same rank, so we have a "Pair".
Note that we cannot make a "Flush" or a "Three of a Kind".
Constraints:
ranks.length == suits.length == 5
1 <= ranks[i] <= 13
'a' <= suits[i] <= 'd'
No two cards have the same rank and suit.
| Easy | [
"array",
"hash-table",
"counting"
] | [
"const bestHand = function(ranks, suits) {\n let isFlush = false\n const freq = {}\n for(const e of suits) {\n if(freq[e] == null) freq[e] = 0\n freq[e]++\n if(freq[e] >= 5) return 'Flush'\n }\n const rankHash = {}\n for(const e of ranks) {\n if(rankHash[e] == null) rankHash[e] = 0\n rankHash[e]++\n if(rankHash[e] >= 3) return 'Three of a Kind'\n }\n const rankKeys = Object.keys(rankHash)\n for(const k of rankKeys) {\n if(rankHash[k] >= 2) return 'Pair'\n }\n return 'High Card'\n};"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.