QID
int64 1
2.85k
| titleSlug
stringlengths 3
77
| Hints
list | Code
stringlengths 80
1.34k
| Body
stringlengths 190
4.55k
| Difficulty
stringclasses 3
values | Topics
list | Definitions
stringclasses 14
values | Solutions
list |
---|---|---|---|---|---|---|---|---|
2,348 |
number-of-zero-filled-subarrays
|
[
"For each zero, you can calculate the number of zero-filled subarrays that end on that index, which is the number of consecutive zeros behind the current element + 1.",
"Maintain the number of consecutive zeros behind the current element, count the number of zero-filled subarrays that end on each index, sum it up to get the answer."
] |
/**
* @param {number[]} nums
* @return {number}
*/
var zeroFilledSubarray = function(nums) {
};
|
Given an integer array nums, return the number of subarrays filled with 0.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,3,0,0,2,0,0,4]
Output: 6
Explanation:
There are 4 occurrences of [0] as a subarray.
There are 2 occurrences of [0,0] as a subarray.
There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.
Example 2:
Input: nums = [0,0,0,2,0,0]
Output: 9
Explanation:
There are 5 occurrences of [0] as a subarray.
There are 3 occurrences of [0,0] as a subarray.
There is 1 occurrence of [0,0,0] as a subarray.
There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.
Example 3:
Input: nums = [2,10,2019]
Output: 0
Explanation: There is no subarray filled with 0. Therefore, we return 0.
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
|
Medium
|
[
"array",
"math"
] |
[
"const zeroFilledSubarray = function(nums) {\n let res = 0\n let idx = -1\n const n = nums.length\n for(let i = 0; i < n; i++) {\n const e = nums[i]\n if(e !== 0) {\n const len = (i - 1) - idx\n res += helper(len)\n idx = i\n } else {\n continue\n }\n }\n if(idx !== n - 1) {\n res += helper(n - 1 - idx)\n }\n \n \n return res\n \n function helper(n) {\n let res = 0\n for(let i = 1; i <= n; i++) {\n res += i\n }\n \n return res\n }\n};"
] |
|
2,349 |
design-a-number-container-system
|
[
"Use a hash table to efficiently map each number to all of its indices in the container and to map each index to their current number.",
"In addition, you can use ordered set to store all of the indices for each number to solve the find method. Do not forget to update the ordered set according to the change method."
] |
var NumberContainers = function() {
};
/**
* @param {number} index
* @param {number} number
* @return {void}
*/
NumberContainers.prototype.change = function(index, number) {
};
/**
* @param {number} number
* @return {number}
*/
NumberContainers.prototype.find = function(number) {
};
/**
* Your NumberContainers object will be instantiated and called as such:
* var obj = new NumberContainers()
* obj.change(index,number)
* var param_2 = obj.find(number)
*/
|
Design a number container system that can do the following:
Insert or Replace a number at the given index in the system.
Return the smallest index for the given number in the system.
Implement the NumberContainers class:
NumberContainers() Initializes the number container system.
void change(int index, int number) Fills the container at index with the number. If there is already a number at that index, replace it.
int find(int number) Returns the smallest index for the given number, or -1 if there is no index that is filled by number in the system.
Example 1:
Input
["NumberContainers", "find", "change", "change", "change", "change", "find", "change", "find"]
[[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]]
Output
[null, -1, null, null, null, null, 1, null, 2]
Explanation
NumberContainers nc = new NumberContainers();
nc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.
nc.change(2, 10); // Your container at index 2 will be filled with number 10.
nc.change(1, 10); // Your container at index 1 will be filled with number 10.
nc.change(3, 10); // Your container at index 3 will be filled with number 10.
nc.change(5, 10); // Your container at index 5 will be filled with number 10.
nc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.
nc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20.
nc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.
Constraints:
1 <= index, number <= 109
At most 105 calls will be made in total to change and find.
|
Medium
|
[
"hash-table",
"design",
"heap-priority-queue",
"ordered-set"
] | null |
[] |
2,350 |
shortest-impossible-sequence-of-rolls
|
[
"How can you find the minimum index such that all sequences of length 1 can be formed from the start until that index?",
"Starting from the previous minimum index, what is the next index such that all sequences of length 2 can be formed?",
"Can you extend the idea to sequences of length 3 and more?"
] |
/**
* @param {number[]} rolls
* @param {number} k
* @return {number}
*/
var shortestSequence = function(rolls, k) {
};
|
You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i].
Return the length of the shortest sequence of rolls that cannot be taken from rolls.
A sequence of rolls of length len is the result of rolling a k sided dice len times.
Note that the sequence taken does not have to be consecutive as long as it is in order.
Example 1:
Input: rolls = [4,2,1,2,3,3,2,4,1], k = 4
Output: 3
Explanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.
Every sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.
The sequence [1, 4, 2] cannot be taken from rolls, so we return 3.
Note that there are other sequences that cannot be taken from rolls.
Example 2:
Input: rolls = [1,1,2,2], k = 2
Output: 2
Explanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls.
The sequence [2, 1] cannot be taken from rolls, so we return 2.
Note that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.
Example 3:
Input: rolls = [1,1,3,2,2,2,3,3], k = 4
Output: 1
Explanation: The sequence [4] cannot be taken from rolls, so we return 1.
Note that there are other sequences that cannot be taken from rolls but [4] is the shortest.
Constraints:
n == rolls.length
1 <= n <= 105
1 <= rolls[i] <= k <= 105
|
Hard
|
[
"array",
"hash-table",
"greedy"
] |
[
"const shortestSequence = function (rolls, k) {\n let res = 1\n let set = new Set()\n\n for (let i of rolls) {\n set.add(i)\n if (set.size === k) {\n res++\n set = new Set()\n }\n }\n return res\n}"
] |
|
2,351 |
first-letter-to-appear-twice
|
[
"Iterate through the string from left to right. Keep track of the elements you have already seen in a set.",
"If the current element is already in the set, return that element."
] |
/**
* @param {string} s
* @return {character}
*/
var repeatedCharacter = function(s) {
};
|
Given a string s consisting of lowercase English letters, return the first letter to appear twice.
Note:
A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.
s will contain at least one letter that appears twice.
Example 1:
Input: s = "abccbaacz"
Output: "c"
Explanation:
The letter 'a' appears on the indexes 0, 5 and 6.
The letter 'b' appears on the indexes 1 and 4.
The letter 'c' appears on the indexes 2, 3 and 7.
The letter 'z' appears on the index 8.
The letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.
Example 2:
Input: s = "abcdd"
Output: "d"
Explanation:
The only letter that appears twice is 'd' so we return 'd'.
Constraints:
2 <= s.length <= 100
s consists of lowercase English letters.
s has at least one repeated letter.
|
Easy
|
[
"hash-table",
"string",
"counting"
] |
[
"var repeatedCharacter = function(s) {\n const set = new Set()\n \n for(const e of s) {\n if(set.has(e)) return e\n else set.add(e)\n }\n};"
] |
|
2,352 |
equal-row-and-column-pairs
|
[
"We can use nested loops to compare every row against every column.",
"Another loop is necessary to compare the row and column element by element.",
"It is also possible to hash the arrays and compare the hashed values instead."
] |
/**
* @param {number[][]} grid
* @return {number}
*/
var equalPairs = function(grid) {
};
|
Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) such that row ri and column cj are equal.
A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
Example 1:
Input: grid = [[3,2,1],[1,7,6],[2,7,7]]
Output: 1
Explanation: There is 1 equal row and column pair:
- (Row 2, Column 1): [2,7,7]
Example 2:
Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
Output: 3
Explanation: There are 3 equal row and column pairs:
- (Row 0, Column 0): [3,1,2,2]
- (Row 2, Column 2): [2,4,2,2]
- (Row 3, Column 2): [2,4,2,2]
Constraints:
n == grid.length == grid[i].length
1 <= n <= 200
1 <= grid[i][j] <= 105
|
Medium
|
[
"array",
"hash-table",
"matrix",
"simulation"
] |
[
"var equalPairs = function(grid) {\n let res = 0\n \n const n = grid.length\n for(let i = 0; i <n; i++) {\n for(let j = 0; j < n;j++){\n let tmp = true\n for(let k = 0; k < n; k++) {\n if(grid[i][k] !== grid[k][j]) {\n tmp = false\n break\n }\n }\n if(tmp) res++\n }\n }\n \n return res\n};"
] |
|
2,353 |
design-a-food-rating-system
|
[
"The key to solving this problem is to properly store the data using the right data structures.",
"Firstly, a hash table is needed to efficiently map each food item to its cuisine and current rating.",
"In addition, another hash table is needed to map cuisines to foods within each cuisine stored in an ordered set according to their ratings."
] |
/**
* @param {string[]} foods
* @param {string[]} cuisines
* @param {number[]} ratings
*/
var FoodRatings = function(foods, cuisines, ratings) {
};
/**
* @param {string} food
* @param {number} newRating
* @return {void}
*/
FoodRatings.prototype.changeRating = function(food, newRating) {
};
/**
* @param {string} cuisine
* @return {string}
*/
FoodRatings.prototype.highestRated = function(cuisine) {
};
/**
* Your FoodRatings object will be instantiated and called as such:
* var obj = new FoodRatings(foods, cuisines, ratings)
* obj.changeRating(food,newRating)
* var param_2 = obj.highestRated(cuisine)
*/
|
Design a food rating system that can do the following:
Modify the rating of a food item listed in the system.
Return the highest-rated food item for a type of cuisine in the system.
Implement the FoodRatings class:
FoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food items are described by foods, cuisines and ratings, all of which have a length of n.
foods[i] is the name of the ith food,
cuisines[i] is the type of cuisine of the ith food, and
ratings[i] is the initial rating of the ith food.
void changeRating(String food, int newRating) Changes the rating of the food item with the name food.
String highestRated(String cuisine) Returns the name of the food item that has the highest rating for the given type of cuisine. If there is a tie, return the item with the lexicographically smaller name.
Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.
Example 1:
Input
["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"]
[[["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]], ["korean"], ["japanese"], ["sushi", 16], ["japanese"], ["ramen", 16], ["japanese"]]
Output
[null, "kimchi", "ramen", null, "sushi", null, "ramen"]
Explanation
FoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]);
foodRatings.highestRated("korean"); // return "kimchi"
// "kimchi" is the highest rated korean food with a rating of 9.
foodRatings.highestRated("japanese"); // return "ramen"
// "ramen" is the highest rated japanese food with a rating of 14.
foodRatings.changeRating("sushi", 16); // "sushi" now has a rating of 16.
foodRatings.highestRated("japanese"); // return "sushi"
// "sushi" is the highest rated japanese food with a rating of 16.
foodRatings.changeRating("ramen", 16); // "ramen" now has a rating of 16.
foodRatings.highestRated("japanese"); // return "ramen"
// Both "sushi" and "ramen" have a rating of 16.
// However, "ramen" is lexicographically smaller than "sushi".
Constraints:
1 <= n <= 2 * 104
n == foods.length == cuisines.length == ratings.length
1 <= foods[i].length, cuisines[i].length <= 10
foods[i], cuisines[i] consist of lowercase English letters.
1 <= ratings[i] <= 108
All the strings in foods are distinct.
food will be the name of a food item in the system across all calls to changeRating.
cuisine will be a type of cuisine of at least one food item in the system across all calls to highestRated.
At most 2 * 104 calls in total will be made to changeRating and highestRated.
|
Medium
|
[
"hash-table",
"design",
"heap-priority-queue",
"ordered-set"
] |
[
"var FoodRatings = function(foods, cuisines, ratings) {\n let n = foods.length, cm = new Map(), fm = new Map(); // cm: cuisine map {cuisine: pq}, fm: food map {food: [cuisine, rating]}\n for (let i = 0; i < n; i++) {\n fm.set(foods[i], [cuisines[i], ratings[i]]);\n if (!cm.has(cuisines[i])) {\n let pq = new MaxPriorityQueue({\n compare: (x, y) => {\n if (x[0] != y[0]) return y[0] - x[0]; // first priority: high rate comes first\n return x[1].localeCompare(y[1]); // second priority: lexical smaller comes first\n }\n });\n cm.set(cuisines[i], pq);\n }\n cm.get(cuisines[i]).enqueue([ratings[i], foods[i]])\n }\n return { changeRating, highestRated }\n function changeRating(food, newRating) {\n let cur = fm.get(food), cuisine = cur[0];\n cur[1] = newRating;\n fm.set(food, cur);\n cm.get(cuisine).enqueue([newRating, food]);\n }\n function highestRated(cuisine) {\n let pq = cm.get(cuisine);\n while (fm.get(pq.front()[1])[1] != pq.front()[0]) pq.dequeue(); // lazy remove\n return pq.front()[1];\n }\n};"
] |
|
2,354 |
number-of-excellent-pairs
|
[
"Can you find a different way to describe the second condition?",
"The sum of the number of set bits in (num1 OR num2) and (num1 AND num2) is equal to the sum of the number of set bits in num1 and num2."
] |
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var countExcellentPairs = function(nums, k) {
};
|
You are given a 0-indexed positive integer array nums and a positive integer k.
A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied:
Both the numbers num1 and num2 exist in the array nums.
The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k, where OR is the bitwise OR operation and AND is the bitwise AND operation.
Return the number of distinct excellent pairs.
Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example, (1, 2) and (2, 1) are distinct.
Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: 5
Explanation: The excellent pairs are the following:
- (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3.
- (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.
- (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.
So the number of excellent pairs is 5.
Example 2:
Input: nums = [5,1,1], k = 10
Output: 0
Explanation: There are no excellent pairs for this array.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= 60
|
Hard
|
[
"array",
"hash-table",
"binary-search",
"bit-manipulation"
] |
[
"const countExcellentPairs = function(nums, k) {\n const cnt = Array(31).fill(0), set = new Set(nums)\n for(const e of set) {\n cnt[setBits(e)]++\n }\n let res = 0\n \n for(let i = 1; i < 31; i++) {\n for(let j = 1; j < 31; j++) {\n if(i + j >= k) res += cnt[i] * cnt[j]\n }\n }\n\n return res\n \n function setBits(num) {\n let res = 0\n while(num) {\n res += num % 2\n num = num >> 1\n }\n return res\n }\n};",
"const countExcellentPairs = function(nums, k) {\n const arr = [], set = new Set(nums)\n for(const e of set) {\n arr.push(setBits(e))\n }\n\n arr.sort((a, b) => a - b)\n let res = 0\n for(let i = 0, n = arr.length; i < n; i++) {\n const idx = bs(arr, k - arr[i])\n res += n - idx\n }\n return res\n \n \n function bs(arr, target) {\n let l = 0, r = arr.length\n \n while(l < r) {\n const mid = (l + r) >> 1\n if(arr[mid] < target) l = mid + 1\n else r = mid\n }\n \n return l\n }\n function setBits(num) {\n let res = 0\n while(num) {\n res += num % 2\n num = num >> 1\n }\n return res\n }\n};"
] |
|
2,357 |
make-array-zero-by-subtracting-equal-amounts
|
[
"It is always best to set x as the smallest non-zero element in nums.",
"Elements with the same value will always take the same number of operations to become 0. Contrarily, elements with different values will always take a different number of operations to become 0.",
"The answer is the number of unique non-zero numbers in nums."
] |
/**
* @param {number[]} nums
* @return {number}
*/
var minimumOperations = function(nums) {
};
|
You are given a non-negative integer array nums. In one operation, you must:
Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.
Subtract x from every positive element in nums.
Return the minimum number of operations to make every element in nums equal to 0.
Example 1:
Input: nums = [1,5,0,3,5]
Output: 3
Explanation:
In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].
In the second operation, choose x = 2. Now, nums = [0,2,0,0,2].
In the third operation, choose x = 2. Now, nums = [0,0,0,0,0].
Example 2:
Input: nums = [0]
Output: 0
Explanation: Each element in nums is already 0 so no operations are needed.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
|
Easy
|
[
"array",
"hash-table",
"greedy",
"sorting",
"heap-priority-queue",
"simulation"
] |
[
"const minimumOperations = function(nums) {\n \n let res = 0\n \n while(!allZero(nums)) {\n const sub = minNonZero(nums)\n nums = nums.map(e => e - sub)\n \n res++\n }\n \n return res\n \n function minNonZero(arr) {\n let res = 0\n const f = arr.filter(e => e > 0)\n \n \n return Math.min(...f)\n }\n \n function allZero(arr) {\n for(const e of arr) {\n if(e > 0) return false\n }\n return true\n }\n};"
] |
|
2,358 |
maximum-number-of-groups-entering-a-competition
|
[
"Would it be easier to place the students into valid groups after sorting them based on their grades in ascending order?",
"Notice that, after sorting, we can separate them into groups of sizes 1, 2, 3, and so on.",
"If the last group is invalid, we can merge it with the previous group.",
"This creates the maximum number of groups because we always greedily form the smallest possible group."
] |
/**
* @param {number[]} grades
* @return {number}
*/
var maximumGroups = function(grades) {
};
|
You are given a positive integer array grades which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions:
The sum of the grades of students in the ith group is less than the sum of the grades of students in the (i + 1)th group, for all groups (except the last).
The total number of students in the ith group is less than the total number of students in the (i + 1)th group, for all groups (except the last).
Return the maximum number of groups that can be formed.
Example 1:
Input: grades = [10,6,12,7,3,5]
Output: 3
Explanation: The following is a possible way to form 3 groups of students:
- 1st group has the students with grades = [12]. Sum of grades: 12. Student count: 1
- 2nd group has the students with grades = [6,7]. Sum of grades: 6 + 7 = 13. Student count: 2
- 3rd group has the students with grades = [10,3,5]. Sum of grades: 10 + 3 + 5 = 18. Student count: 3
It can be shown that it is not possible to form more than 3 groups.
Example 2:
Input: grades = [8,8]
Output: 1
Explanation: We can only form 1 group, since forming 2 groups would lead to an equal number of students in both groups.
Constraints:
1 <= grades.length <= 105
1 <= grades[i] <= 105
|
Medium
|
[
"array",
"math",
"binary-search",
"greedy"
] |
[
"const maximumGroups = function(grades) {\n grades.sort((a, b) => a - b)\n let res = 0\n let pre = 0, preNum = 0, cur = 0, curNum = 0\n const n = grades.length\n for(let i = 0; i < n; i++) {\n cur += grades[i]\n curNum++\n if(cur > pre && curNum > preNum) {\n res++\n pre = cur\n preNum = curNum\n cur = 0\n curNum = 0\n }\n }\n \n \n return res\n};"
] |
|
2,359 |
find-closest-node-to-given-two-nodes
|
[
"How can you find the shortest distance from one node to all nodes in the graph?",
"Use BFS to find the shortest distance from both node1 and node2 to all nodes in the graph. Then iterate over all nodes, and find the node with the minimum max distance."
] |
/**
* @param {number[]} edges
* @param {number} node1
* @param {number} node2
* @return {number}
*/
var closestMeetingNode = function(edges, node1, node2) {
};
|
You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.
The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then edges[i] == -1.
You are also given two integers node1 and node2.
Return the index of the node that can be reached from both node1 and node2, such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1.
Note that edges may contain cycles.
Example 1:
Input: edges = [2,2,3,-1], node1 = 0, node2 = 1
Output: 2
Explanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1.
The maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2.
Example 2:
Input: edges = [1,2,-1], node1 = 0, node2 = 2
Output: 2
Explanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0.
The maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.
Constraints:
n == edges.length
2 <= n <= 105
-1 <= edges[i] < n
edges[i] != i
0 <= node1, node2 < n
|
Medium
|
[
"depth-first-search",
"graph"
] |
[
"const closestMeetingNode = function(edges, node1, node2) {\n const graph = {}\n const n = edges.length\n for(let i = 0; i < n; i++) {\n const e = edges[i]\n if(graph[i] == null) graph[i] = new Set()\n if(e !== -1) graph[i].add(e)\n }\n \n const dis1 = bfs(node1), dis2 = bfs(node2)\n // console.log(dis1, dis2)\n let min = Infinity, res= -1\n \n for(let i = 0; i < n; i++) {\n const disa = dis1[i], disb = dis2[i]\n if(disa !== Infinity && disb !== Infinity) {\n const tmp = Math.min(min, Math.max(disa, disb))\n if(tmp < min) {\n res = i\n min = tmp\n }\n }\n \n }\n \n return res\n \n function bfs(node) {\n const dis1 = Array(n).fill(Infinity)\n dis1[node] = 0\n const visited = new Set()\n visited.add(node)\n let q = [node], dis = 0\n\n while(q.length) {\n const size = q.length\n const nxt = []\n dis++\n for(let i = 0; i < size; i++) {\n const cur = q[i]\n const tmp = graph[cur]\n if(tmp) {\n for(const e of tmp) {\n if(visited.has(e)) continue\n nxt.push(e)\n visited.add(e)\n dis1[e] = dis\n }\n }\n }\n q = nxt\n }\n return dis1\n }\n \n};"
] |
|
2,360 |
longest-cycle-in-a-graph
|
[
"How many cycles can each node at most be part of?",
"Each node can be part of at most one cycle. Start from each node and find the cycle that it is part of if there is any. Save the already visited nodes to not repeat visiting the same cycle multiple times."
] |
/**
* @param {number[]} edges
* @return {number}
*/
var longestCycle = function(edges) {
};
|
You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.
The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.
Return the length of the longest cycle in the graph. If no cycle exists, return -1.
A cycle is a path that starts and ends at the same node.
Example 1:
Input: edges = [3,3,4,2,3]
Output: 3
Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.
The length of this cycle is 3, so 3 is returned.
Example 2:
Input: edges = [2,-1,3,1]
Output: -1
Explanation: There are no cycles in this graph.
Constraints:
n == edges.length
2 <= n <= 105
-1 <= edges[i] < n
edges[i] != i
|
Hard
|
[
"depth-first-search",
"graph",
"topological-sort"
] |
[
"const longestCycle = function(edges) {\n const n = edges.length, colors = Array(n).fill(0), dis = Array(n).fill(0)\n let res = -1\n \n for(let i = 0; i < n; i++) {\n if(colors[i] === 0) {\n res = Math.max(res, dfs(i, 0))\n }\n }\n \n return res\n \n function dfs(u, d) {\n let ans = -1\n dis[u] = d\n colors[u] = 1\n \n if(edges[u] !== -1) {\n if(colors[edges[u]] == 1) {\n return dis[u] - dis[edges[u]] + 1\n } else if(colors[edges[u]] === 0) {\n ans = Math.max(ans, dfs(edges[u], d + 1)) \n }\n }\n \n colors[u] = 2\n return ans\n }\n};"
] |
|
2,363 |
merge-similar-items
|
[
"Map the weights using the corresponding values as keys.",
"Make sure your output is sorted in ascending order by value."
] |
/**
* @param {number[][]} items1
* @param {number[][]} items2
* @return {number[][]}
*/
var mergeSimilarItems = function(items1, items2) {
};
|
You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties:
items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item.
The value of each item in items is unique.
Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of weights of all items with value valuei.
Note: ret should be returned in ascending order by value.
Example 1:
Input: items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]
Output: [[1,6],[3,9],[4,5]]
Explanation:
The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 5, total weight = 1 + 5 = 6.
The item with value = 3 occurs in items1 with weight = 8 and in items2 with weight = 1, total weight = 8 + 1 = 9.
The item with value = 4 occurs in items1 with weight = 5, total weight = 5.
Therefore, we return [[1,6],[3,9],[4,5]].
Example 2:
Input: items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]]
Output: [[1,4],[2,4],[3,4]]
Explanation:
The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 3, total weight = 1 + 3 = 4.
The item with value = 2 occurs in items1 with weight = 3 and in items2 with weight = 1, total weight = 3 + 1 = 4.
The item with value = 3 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4.
Therefore, we return [[1,4],[2,4],[3,4]].
Example 3:
Input: items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]]
Output: [[1,7],[2,4],[7,1]]
Explanation:
The item with value = 1 occurs in items1 with weight = 3 and in items2 with weight = 4, total weight = 3 + 4 = 7.
The item with value = 2 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4.
The item with value = 7 occurs in items2 with weight = 1, total weight = 1.
Therefore, we return [[1,7],[2,4],[7,1]].
Constraints:
1 <= items1.length, items2.length <= 1000
items1[i].length == items2[i].length == 2
1 <= valuei, weighti <= 1000
Each valuei in items1 is unique.
Each valuei in items2 is unique.
|
Easy
|
[
"array",
"hash-table",
"sorting",
"ordered-set"
] | null |
[] |
2,364 |
count-number-of-bad-pairs
|
[
"Would it be easier to count the number of pairs that are not bad pairs?",
"Notice that (j - i != nums[j] - nums[i]) is the same as (nums[i] - i != nums[j] - j).",
"Keep a counter of nums[i] - i. To be efficient, use a HashMap."
] |
/**
* @param {number[]} nums
* @return {number}
*/
var countBadPairs = function(nums) {
};
|
You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i].
Return the total number of bad pairs in nums.
Example 1:
Input: nums = [4,1,3,3]
Output: 5
Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.
The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.
The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.
The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.
The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.
There are a total of 5 bad pairs, so we return 5.
Example 2:
Input: nums = [1,2,3,4,5]
Output: 0
Explanation: There are no bad pairs.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
|
Medium
|
[
"array",
"hash-table"
] | null |
[] |
2,365 |
task-scheduler-ii
|
[
"Try taking breaks as late as possible, such that tasks are still spaced appropriately.",
"Whenever considering whether to complete the next task, if it is not the first task of its type, check how many days ago the previous task was completed and add an appropriate number of breaks."
] |
/**
* @param {number[]} tasks
* @param {number} space
* @return {number}
*/
var taskSchedulerII = function(tasks, space) {
};
|
You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the ith task.
You are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed.
Each day, until all tasks have been completed, you must either:
Complete the next task from tasks, or
Take a break.
Return the minimum number of days needed to complete all tasks.
Example 1:
Input: tasks = [1,2,1,2,3,1], space = 3
Output: 9
Explanation:
One way to complete all tasks in 9 days is as follows:
Day 1: Complete the 0th task.
Day 2: Complete the 1st task.
Day 3: Take a break.
Day 4: Take a break.
Day 5: Complete the 2nd task.
Day 6: Complete the 3rd task.
Day 7: Take a break.
Day 8: Complete the 4th task.
Day 9: Complete the 5th task.
It can be shown that the tasks cannot be completed in less than 9 days.
Example 2:
Input: tasks = [5,8,8,5], space = 2
Output: 6
Explanation:
One way to complete all tasks in 6 days is as follows:
Day 1: Complete the 0th task.
Day 2: Complete the 1st task.
Day 3: Take a break.
Day 4: Take a break.
Day 5: Complete the 2nd task.
Day 6: Complete the 3rd task.
It can be shown that the tasks cannot be completed in less than 6 days.
Constraints:
1 <= tasks.length <= 105
1 <= tasks[i] <= 109
1 <= space <= tasks.length
|
Medium
|
[
"array",
"hash-table",
"simulation"
] |
[
"const taskSchedulerII = function(tasks, space) {\n const last = new Map();;\n let res = 0;\n for (const a of tasks)\n if (last.has(a)) {\n res = Math.max(res, last.get(a) + space) + 1\n last.set(a, res);\n } else {\n res++\n last.set(a, res);\n } \n return res;\n};"
] |
|
2,366 |
minimum-replacements-to-sort-the-array
|
[
"It is optimal to never make an operation to the last element of the array.",
"You can iterate from the second last element to the first. If the current value is greater than the previous bound, we want to break it into pieces so that the smaller one is as large as possible but not larger than the previous one."
] |
/**
* @param {number[]} nums
* @return {number}
*/
var minimumReplacement = function(nums) {
};
|
You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it.
For example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7].
Return the minimum number of operations to make an array that is sorted in non-decreasing order.
Example 1:
Input: nums = [3,9,3]
Output: 2
Explanation: Here are the steps to sort the array in non-decreasing order:
- From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3]
- From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3]
There are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.
Example 2:
Input: nums = [1,2,3,4,5]
Output: 0
Explanation: The array is already in non-decreasing order. Therefore, we return 0.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
|
Hard
|
[
"array",
"math",
"greedy"
] |
[
"const minimumReplacement = function(nums) {\n const n = nums.length\n let prev = nums[n - 1];;\n let ans = 0;\n for(let i = n - 2; i >= 0; i--){\n let noOfTime = ~~(nums[i] / prev); \n if((nums[i]) % prev != 0){\n noOfTime++;\n prev = ~~(nums[i] / noOfTime);\n } \n ans += noOfTime - 1;\n }\n return ans;\n};"
] |
|
2,367 |
number-of-arithmetic-triplets
|
[
"Are the constraints small enough for brute force?",
"We can use three loops, each iterating through the array to go through every possible triplet. Be sure to not count duplicates."
] |
/**
* @param {number[]} nums
* @param {number} diff
* @return {number}
*/
var arithmeticTriplets = function(nums, diff) {
};
|
You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met:
i < j < k,
nums[j] - nums[i] == diff, and
nums[k] - nums[j] == diff.
Return the number of unique arithmetic triplets.
Example 1:
Input: nums = [0,1,4,6,7,10], diff = 3
Output: 2
Explanation:
(1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3.
(2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3.
Example 2:
Input: nums = [4,5,6,7,8,9], diff = 2
Output: 2
Explanation:
(0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2.
(1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2.
Constraints:
3 <= nums.length <= 200
0 <= nums[i] <= 200
1 <= diff <= 50
nums is strictly increasing.
|
Easy
|
[
"array",
"hash-table",
"two-pointers",
"enumeration"
] |
[
"var arithmeticTriplets = function(nums, diff) {\n let res = 0\n const n = nums.length\n for(let i = 0;i < n - 2; i++) {\n for(let j = i + 1; j < n - 1; j++) {\n for(let k = j + 1; k < n; k++) {\n if(nums[j] - nums[i] === diff && nums[k] - nums[j] === diff) {\n res++\n }\n }\n }\n }\n return res\n};"
] |
|
2,368 |
reachable-nodes-with-restrictions
|
[
"Can we find all the reachable nodes in a single traversal?",
"Traverse the graph from node 0 while avoiding the nodes in restricted and do not revisit nodes that have been visited.",
"Keep count of how many nodes are visited in total."
] |
/**
* @param {number} n
* @param {number[][]} edges
* @param {number[]} restricted
* @return {number}
*/
var reachableNodes = function(n, edges, restricted) {
};
|
There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
You are 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. You are also given an integer array restricted which represents restricted nodes.
Return the maximum number of nodes you can reach from node 0 without visiting a restricted node.
Note that node 0 will not be a restricted node.
Example 1:
Input: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]
Output: 4
Explanation: The diagram above shows the tree.
We have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.
Example 2:
Input: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]
Output: 3
Explanation: The diagram above shows the tree.
We have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.
Constraints:
2 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree.
1 <= restricted.length < n
1 <= restricted[i] < n
All the values of restricted are unique.
|
Medium
|
[
"array",
"hash-table",
"tree",
"depth-first-search",
"breadth-first-search",
"graph"
] |
[
"const reachableNodes = function(n, edges, restricted) {\n const graph = {}\n for(const [u, v] of edges) {\n if(graph[u] == null) graph[u] = new Set()\n if(graph[v] == null) graph[v] = new Set()\n graph[u].add(v)\n graph[v].add(u)\n }\n const forbid = new Set(restricted)\n const visited = new Set()\n let res = 0\n let q = []\n if(!forbid.has(0)) q.push(0)\n visited.add(0)\n while(q.length) {\n const size = q.length\n const tmp = []\n for(let i = 0; i < size; i++) {\n const cur = q[i]\n res++\n for(const e of (graph[cur] || [])) {\n if(!forbid.has(e) && !visited.has(e)) {\n tmp.push(e)\n visited.add(e)\n }\n }\n \n }\n \n q = tmp\n }\n \n \n return res\n};"
] |
|
2,369 |
check-if-there-is-a-valid-partition-for-the-array
|
[
"How can you reduce the problem to checking if there is a valid partition for a smaller array?",
"Use dynamic programming to reduce the problem until you have an empty array."
] |
/**
* @param {number[]} nums
* @return {boolean}
*/
var validPartition = function(nums) {
};
|
You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.
We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:
The subarray consists of exactly 2, equal elements. For example, the subarray [2,2] is good.
The subarray consists of exactly 3, equal elements. For example, the subarray [4,4,4] is good.
The subarray consists of exactly 3 consecutive increasing elements, that is, the difference between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray [1,3,5] is not.
Return true if the array has at least one valid partition. Otherwise, return false.
Example 1:
Input: nums = [4,4,4,5,6]
Output: true
Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6].
This partition is valid, so we return true.
Example 2:
Input: nums = [1,1,1,2]
Output: false
Explanation: There is no valid partition for this array.
Constraints:
2 <= nums.length <= 105
1 <= nums[i] <= 106
|
Medium
|
[
"array",
"dynamic-programming"
] |
[
"var validPartition = function(nums) {\n const n = nums.length\n const memo = {}\n function dfs(i, cur) {\n // console.log(i,cur)\n if(i === n) {\n if(chk1(cur) || chk2(cur) || chk3(cur) || cur.length === 0) return true\n return false\n }\n const k = `${i}_${cur.join(',')}`\n if(memo[k] != null) return memo[k]\n let res\n if(cur.length === 0) {\n cur.push(nums[i])\n res = dfs(i + 1, cur)\n } else if(cur.length === 1) {\n cur.push(nums[i])\n res = dfs(i + 1, cur)\n } else if(cur.length === 2) {\n let r1 = false\n if(chk1(cur)) {\n r1 = dfs(i + 1, [nums[i]])\n }\n cur.push(nums[i])\n let r2 = dfs(i + 1, cur)\n res = r1 || r2\n } else if(cur.length === 3) {\n if(chk2(cur) || chk3(cur)) {\n res = dfs(i + 1, [nums[i]])\n }else res = false\n }\n memo[k] = res\n return res\n }\n \n return dfs(0, [])\n \n function chk1(arr) {\n return arr.length === 2 && arr[0] === arr[1]\n }\n function chk2(arr) {\n return arr.length === 3 && arr[0] === arr[1] && arr[2] === arr[1]\n }\n function chk3(arr) {\n return arr.length === 3 && arr[1] - arr[0] === 1 && arr[2] - arr[1] === 1\n }\n};"
] |
|
2,370 |
longest-ideal-subsequence
|
[
"How can you calculate the longest ideal subsequence that ends at a specific index i?",
"Can you calculate it for all positions i? How can you use previously calculated answers to calculate the answer for the next position?"
] |
/**
* @param {string} s
* @param {number} k
* @return {number}
*/
var longestIdealString = function(s, k) {
};
|
You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied:
t is a subsequence of the string s.
The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k.
Return the length of the longest ideal string.
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.
Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.
Example 1:
Input: s = "acfgbd", k = 2
Output: 4
Explanation: The longest ideal string is "acbd". The length of this string is 4, so 4 is returned.
Note that "acfgbd" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.
Example 2:
Input: s = "abcd", k = 3
Output: 4
Explanation: The longest ideal string is "abcd". The length of this string is 4, so 4 is returned.
Constraints:
1 <= s.length <= 105
0 <= k <= 25
s consists of lowercase English letters.
|
Medium
|
[
"hash-table",
"string",
"dynamic-programming"
] |
[
"const longestIdealString = function(s, k) {\n const n = s.length, a = 'a'.charCodeAt(0)\n const dp = Array(26).fill(0)\n let res = 0\n \n for(let i = 0; i < n; i++) {\n const cur = s[i], curCode = cur.charCodeAt(0)\n const tmp = helper(curCode - a) + 1\n dp[curCode - a] = tmp\n res = Math.max(res, tmp)\n }\n // console.log(dp)\n return res\n \n function helper(end) {\n let res = 0\n for(let i = Math.max(0, end - k), e = Math.min(25, end + k); i <= e; i++) {\n if(dp[i] > res) res = dp[i]\n }\n \n return res\n }\n};",
"const longestIdealString = function(s, k) {\n const n = s.length\n const arr = [], a = 'a'.charCodeAt(0)\n for(const ch of s) {\n arr.push(ch.charCodeAt(0) - a)\n }\n const dp = Array(26).fill(0)\n for(const e of arr) {\n dp[e] = 1 + Math.max(...dp.slice(Math.max(0, e - k), e + k + 1))\n }\n return Math.max(...dp)\n};"
] |
|
2,373 |
largest-local-values-in-a-matrix
|
[
"Use nested loops to run through all possible 3 x 3 windows in the matrix.",
"For each 3 x 3 window, iterate through the values to get the maximum value within the window."
] |
/**
* @param {number[][]} grid
* @return {number[][]}
*/
var largestLocal = function(grid) {
};
|
You are given an n x n integer matrix grid.
Generate an integer matrix maxLocal of size (n - 2) x (n - 2) such that:
maxLocal[i][j] is equal to the largest value of the 3 x 3 matrix in grid centered around row i + 1 and column j + 1.
In other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid.
Return the generated matrix.
Example 1:
Input: grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]
Output: [[9,9],[8,6]]
Explanation: The diagram above shows the original matrix and the generated matrix.
Notice that each value in the generated matrix corresponds to the largest value of a contiguous 3 x 3 matrix in grid.
Example 2:
Input: grid = [[1,1,1,1,1],[1,1,1,1,1],[1,1,2,1,1],[1,1,1,1,1],[1,1,1,1,1]]
Output: [[2,2,2],[2,2,2],[2,2,2]]
Explanation: Notice that the 2 is contained within every contiguous 3 x 3 matrix in grid.
Constraints:
n == grid.length == grid[i].length
3 <= n <= 100
1 <= grid[i][j] <= 100
|
Easy
|
[
"array",
"matrix"
] |
[
"var largestLocal = function(grid) {\n const n = grid.length\n const res = Array.from({ length: n - 2 }, () => Array(n - 2).fill(0))\n \n for(let i = 0; i < n - 2; i++) {\n for(let j = 0; j < n - 2; j++) {\n res[i][j] = helper(i, j)\n }\n }\n \n return res\n \n function helper(i, j) {\n let res = 0\n for(let ii = i; ii < 3 + i; ii++) {\n for(let jj = j; jj < 3 + j; jj++) {\n if(grid[ii][jj] > res) {\n res = grid[ii][jj]\n }\n }\n }\n \n return res\n }\n};"
] |
|
2,374 |
node-with-highest-edge-score
|
[
"Create an array arr where arr[i] is the edge score for node i.",
"How does the edge score for node edges[i] change? It increases by i.",
"The edge score may not fit within a standard 32-bit integer."
] |
/**
* @param {number[]} edges
* @return {number}
*/
var edgeScore = function(edges) {
};
|
You are given a directed graph with n nodes labeled from 0 to n - 1, where each node has exactly one outgoing edge.
The graph is represented by a given 0-indexed integer array edges of length n, where edges[i] indicates that there is a directed edge from node i to node edges[i].
The edge score of a node i is defined as the sum of the labels of all the nodes that have an edge pointing to i.
Return the node with the highest edge score. If multiple nodes have the same edge score, return the node with the smallest index.
Example 1:
Input: edges = [1,0,0,0,0,7,7,5]
Output: 7
Explanation:
- The nodes 1, 2, 3 and 4 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 + 3 + 4 = 10.
- The node 0 has an edge pointing to node 1. The edge score of node 1 is 0.
- The node 7 has an edge pointing to node 5. The edge score of node 5 is 7.
- The nodes 5 and 6 have an edge pointing to node 7. The edge score of node 7 is 5 + 6 = 11.
Node 7 has the highest edge score so return 7.
Example 2:
Input: edges = [2,0,0,2]
Output: 0
Explanation:
- The nodes 1 and 2 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 = 3.
- The nodes 0 and 3 have an edge pointing to node 2. The edge score of node 2 is 0 + 3 = 3.
Nodes 0 and 2 both have an edge score of 3. Since node 0 has a smaller index, we return 0.
Constraints:
n == edges.length
2 <= n <= 105
0 <= edges[i] < n
edges[i] != i
|
Medium
|
[
"hash-table",
"graph"
] |
[
"var edgeScore = function(edges) {\n const n = edges.length\n const score = Array(n).fill(0)\n for(let i = 0; i < n; i++) {\n const from = i, to = edges[i]\n score[to] += from\n }\n const max = Math.max(...score)\n for(let i = 0; i < n; i++) {\n const e = score[i]\n if(e === max) return i\n }\n};"
] |
|
2,375 |
construct-smallest-number-from-di-string
|
[
"With the constraints, could we generate every possible string?",
"Yes we can. Now we just need to check if the string meets all the conditions."
] |
/**
* @param {string} pattern
* @return {string}
*/
var smallestNumber = function(pattern) {
};
|
You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing.
A 0-indexed string num of length n + 1 is created using the following conditions:
num consists of the digits '1' to '9', where each digit is used at most once.
If pattern[i] == 'I', then num[i] < num[i + 1].
If pattern[i] == 'D', then num[i] > num[i + 1].
Return the lexicographically smallest possible string num that meets the conditions.
Example 1:
Input: pattern = "IIIDIDDD"
Output: "123549876"
Explanation:
At indices 0, 1, 2, and 4 we must have that num[i] < num[i+1].
At indices 3, 5, 6, and 7 we must have that num[i] > num[i+1].
Some possible values of num are "245639871", "135749862", and "123849765".
It can be proven that "123549876" is the smallest possible num that meets the conditions.
Note that "123414321" is not possible because the digit '1' is used more than once.
Example 2:
Input: pattern = "DDD"
Output: "4321"
Explanation:
Some possible values of num are "9876", "7321", and "8742".
It can be proven that "4321" is the smallest possible num that meets the conditions.
Constraints:
1 <= pattern.length <= 8
pattern consists of only the letters 'I' and 'D'.
|
Medium
|
[
"string",
"backtracking",
"stack",
"greedy"
] |
[
"var smallestNumber = function(pattern) {\n const n = pattern.length\n let res = ''\n dfs('', new Set())\n \n return res\n \n function dfs(str, set) {\n if(str.length === n + 1) {\n if(valid(str)) {\n if(res === '') res = str\n else if(str < res) res = str\n } \n return\n }\n \n for(let i = 1; i <= 9; i++) {\n if(set.has(i)) continue\n set.add(i)\n dfs(str + i, set)\n set.delete(i)\n }\n \n }\n\n \n function valid(str) {\n for(let i = 0; i < n; i++) {\n if(pattern[i] === 'I' && str[i] >= str[i + 1]) return false\n if(pattern[i] === 'D' && str[i] <= str[i + 1]) return false\n }\n \n return true\n }\n};"
] |
|
2,376 |
count-special-integers
|
[
"Try to think of dynamic programming.",
"Use the idea of digit dynamic programming to build the numbers, in addition to a bitmask that will tell which digits you have used so far on the number that you are building."
] |
/**
* @param {number} n
* @return {number}
*/
var countSpecialNumbers = function(n) {
};
|
We call a positive integer special if all of its digits are distinct.
Given a positive integer n, return the number of special integers that belong to the interval [1, n].
Example 1:
Input: n = 20
Output: 19
Explanation: All the integers from 1 to 20, except 11, are special. Thus, there are 19 special integers.
Example 2:
Input: n = 5
Output: 5
Explanation: All the integers from 1 to 5 are special.
Example 3:
Input: n = 135
Output: 110
Explanation: There are 110 integers from 1 to 135 that are special.
Some of the integers that are not special are: 22, 114, and 131.
Constraints:
1 <= n <= 2 * 109
|
Hard
|
[
"math",
"dynamic-programming"
] |
[
"var countSpecialNumbers = function(n) {\n const L = [];\n for (let x = n + 1; x > 0; x = Math.floor(x / 10)) L.unshift(x % 10);\n\n // Count the number with digits < N\n let res = 0,\n limit = L.length;\n for (let i = 1; i < limit; ++i) res += 9 * A(9, i - 1);\n\n const seen = new Set();\n for (let i = 0; i < limit; ++i) {\n for (let j = i > 0 ? 0 : 1; j < L[i]; ++j)\n if (!seen.has(j)) res += A(9 - i, limit - i - 1);\n if (seen.has(L[i])) break;\n seen.add(L[i]);\n }\n return res; \n};\n\n\nfunction A(m, n) {\n return n === 0 ? 1 : A(m, n - 1) * (m - n + 1);\n}",
"const countSpecialNumbers = function (n) {\n const s = '' + n\n const dp = Array.from({ length: 11 }, () =>\n Array.from({ length: 2 }, () => Array(1024).fill(-1))\n )\n\n return helper(0, 1, 0, s)\n function helper(idx, tight = 1, mask = 0, digits) {\n if (idx == digits.length) return mask !== 0 ? 1 : 0\n\n if (dp[idx][tight][mask] != -1) return dp[idx][tight][mask]\n\n let k = tight ? +digits[idx] : 9\n let ans = 0\n\n for (let i = 0; i <= k; i++) {\n if (mask & (1 << i)) continue\n let newMask = mask == 0 && i == 0 ? mask : mask | (1 << i)\n\n let nextTight = tight && i == digits[idx] ? 1 : 0\n ans += helper(idx + 1, nextTight, newMask, digits)\n }\n\n return (dp[idx][tight][mask] = ans)\n }\n}"
] |
|
2,379 |
minimum-recolors-to-get-k-consecutive-black-blocks
|
[
"Iterate through all possible consecutive substrings of k characters.",
"Find the number of changes for each substring to make all blocks black, and return the minimum of these."
] |
/**
* @param {string} blocks
* @param {number} k
* @return {number}
*/
var minimumRecolors = function(blocks, k) {
};
|
You are given a 0-indexed string blocks of length n, where blocks[i] is either 'W' or 'B', representing the color of the ith block. The characters 'W' and 'B' denote the colors white and black, respectively.
You are also given an integer k, which is the desired number of consecutive black blocks.
In one operation, you can recolor a white block such that it becomes a black block.
Return the minimum number of operations needed such that there is at least one occurrence of k consecutive black blocks.
Example 1:
Input: blocks = "WBBWWBBWBW", k = 7
Output: 3
Explanation:
One way to achieve 7 consecutive black blocks is to recolor the 0th, 3rd, and 4th blocks
so that blocks = "BBBBBBBWBW".
It can be shown that there is no way to achieve 7 consecutive black blocks in less than 3 operations.
Therefore, we return 3.
Example 2:
Input: blocks = "WBWBBBW", k = 2
Output: 0
Explanation:
No changes need to be made, since 2 consecutive black blocks already exist.
Therefore, we return 0.
Constraints:
n == blocks.length
1 <= n <= 100
blocks[i] is either 'W' or 'B'.
1 <= k <= n
|
Easy
|
[
"string",
"sliding-window"
] | null |
[] |
2,380 |
time-needed-to-rearrange-a-binary-string
|
[
"Try replicating the steps from the problem statement.",
"Perform the replacements simultaneously, and return the number of times the process repeats."
] |
/**
* @param {string} s
* @return {number}
*/
var secondsToRemoveOccurrences = function(s) {
};
|
You are given a binary string s. In one second, all occurrences of "01" are simultaneously replaced with "10". This process repeats until no occurrences of "01" exist.
Return the number of seconds needed to complete this process.
Example 1:
Input: s = "0110101"
Output: 4
Explanation:
After one second, s becomes "1011010".
After another second, s becomes "1101100".
After the third second, s becomes "1110100".
After the fourth second, s becomes "1111000".
No occurrence of "01" exists any longer, and the process needed 4 seconds to complete,
so we return 4.
Example 2:
Input: s = "11100"
Output: 0
Explanation:
No occurrence of "01" exists in s, and the processes needed 0 seconds to complete,
so we return 0.
Constraints:
1 <= s.length <= 1000
s[i] is either '0' or '1'.
Follow up:
Can you solve this problem in O(n) time complexity?
|
Medium
|
[
"string",
"dynamic-programming",
"simulation"
] |
[
"const secondsToRemoveOccurrences = function(s) {\n let zeros = 0\n const n = s.length, { max } = Math\n let res = 0\n \n for(let i = 0; i < n; i++) {\n if(s[i] === '0') zeros++\n if(s[i] === '1' && zeros > 0) {\n res = max(res + 1, zeros)\n }\n }\n return res \n};",
"var secondsToRemoveOccurrences = function(s) {\n const n = s.length\n let zeros = 0, seconds = 0;\n for (let i = 0; i < n; ++i) {\n zeros += s.charAt(i) == '0' ? 1 : 0;\n if (s.charAt(i) == '1' && zeros > 0)\n seconds = Math.max(seconds + 1, zeros);\n }\n return seconds; \n};"
] |
|
2,381 |
shifting-letters-ii
|
[
"Instead of shifting every character in each shift, could you keep track of which characters are shifted and by how much across all shifts?",
"Try marking the start and ends of each shift, then perform a prefix sum of the shifts."
] |
/**
* @param {string} s
* @param {number[][]} shifts
* @return {string}
*/
var shiftingLetters = function(s, shifts) {
};
|
You are given a string s of lowercase English letters and a 2D integer array shifts where shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters backward if directioni = 0.
Shifting a character forward means replacing it with the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Similarly, shifting a character backward means replacing it with the previous letter in the alphabet (wrapping around so that 'a' becomes 'z').
Return the final string after all such shifts to s are applied.
Example 1:
Input: s = "abc", shifts = [[0,1,0],[1,2,1],[0,2,1]]
Output: "ace"
Explanation: Firstly, shift the characters from index 0 to index 1 backward. Now s = "zac".
Secondly, shift the characters from index 1 to index 2 forward. Now s = "zbd".
Finally, shift the characters from index 0 to index 2 forward. Now s = "ace".
Example 2:
Input: s = "dztz", shifts = [[0,0,0],[1,1,1]]
Output: "catz"
Explanation: Firstly, shift the characters from index 0 to index 0 backward. Now s = "cztz".
Finally, shift the characters from index 1 to index 1 forward. Now s = "catz".
Constraints:
1 <= s.length, shifts.length <= 5 * 104
shifts[i].length == 3
0 <= starti <= endi < s.length
0 <= directioni <= 1
s consists of lowercase English letters.
|
Medium
|
[
"array",
"string",
"prefix-sum"
] |
[
"const shiftingLetters = function(s, shifts) {\n const n = s.length\n const arr = Array(n + 1).fill(0)\n const a = 'a'.charCodeAt(0)\n const chToCode = ch => ch.charCodeAt(0)\n const codeToCh = code => String.fromCharCode(code)\n for(const [s, e, d] of shifts) {\n const delta = d === 1 ? 1 : -1\n arr[s] += delta\n arr[e + 1] -= delta\n }\n for(let i = 1; i < n + 1; i++) {\n arr[i] = arr[i - 1] + arr[i]\n }\n const codes = s.split('').map(e => chToCode(e))\n for(let i = 0; i < n; i++) {\n codes[i] += arr[i]\n codes[i] = a + (codes[i] - a + 26 * n) % 26\n }\n return codes.map(c => codeToCh(c)).join('')\n};"
] |
|
2,382 |
maximum-segment-sum-after-removals
|
[
"Use a sorted data structure to collect removal points and store the segments.",
"Use a heap or priority queue to store segment sums and their corresponding boundaries.",
"Make sure to remove invalid segments from the heap."
] |
/**
* @param {number[]} nums
* @param {number[]} removeQueries
* @return {number[]}
*/
var maximumSegmentSum = function(nums, removeQueries) {
};
|
You are given two 0-indexed integer arrays nums and removeQueries, both of length n. For the ith query, the element in nums at the index removeQueries[i] is removed, splitting nums into different segments.
A segment is a contiguous sequence of positive integers in nums. A segment sum is the sum of every element in a segment.
Return an integer array answer, of length n, where answer[i] is the maximum segment sum after applying the ith removal.
Note: The same index will not be removed more than once.
Example 1:
Input: nums = [1,2,5,6,1], removeQueries = [0,3,2,4,1]
Output: [14,7,2,2,0]
Explanation: Using 0 to indicate a removed element, the answer is as follows:
Query 1: Remove the 0th element, nums becomes [0,2,5,6,1] and the maximum segment sum is 14 for segment [2,5,6,1].
Query 2: Remove the 3rd element, nums becomes [0,2,5,0,1] and the maximum segment sum is 7 for segment [2,5].
Query 3: Remove the 2nd element, nums becomes [0,2,0,0,1] and the maximum segment sum is 2 for segment [2].
Query 4: Remove the 4th element, nums becomes [0,2,0,0,0] and the maximum segment sum is 2 for segment [2].
Query 5: Remove the 1st element, nums becomes [0,0,0,0,0] and the maximum segment sum is 0, since there are no segments.
Finally, we return [14,7,2,2,0].
Example 2:
Input: nums = [3,2,11,1], removeQueries = [3,2,1,0]
Output: [16,5,3,0]
Explanation: Using 0 to indicate a removed element, the answer is as follows:
Query 1: Remove the 3rd element, nums becomes [3,2,11,0] and the maximum segment sum is 16 for segment [3,2,11].
Query 2: Remove the 2nd element, nums becomes [3,2,0,0] and the maximum segment sum is 5 for segment [3,2].
Query 3: Remove the 1st element, nums becomes [3,0,0,0] and the maximum segment sum is 3 for segment [3].
Query 4: Remove the 0th element, nums becomes [0,0,0,0] and the maximum segment sum is 0, since there are no segments.
Finally, we return [16,5,3,0].
Constraints:
n == nums.length == removeQueries.length
1 <= n <= 105
1 <= nums[i] <= 109
0 <= removeQueries[i] < n
All the values of removeQueries are unique.
|
Hard
|
[
"array",
"union-find",
"prefix-sum",
"ordered-set"
] |
[
"const maximumSegmentSum = function(nums, removeQueries) {\n removeQueries.reverse()\n const rev = removeQueries\n const hash = {}\n const res = []\n let cur = 0\n for(const idx of rev) {\n hash[idx] = [nums[idx], 1]\n const [lv, ll] = (hash[idx - 1] || [0, 0])\n const [rv, rl] = (hash[idx + 1] || [0, 0])\n \n const val = nums[idx] + lv + rv\n hash[idx + rl] = [val, ll + rl + 1]\n hash[idx - ll] = [val, ll + rl + 1]\n \n cur = Math.max(cur, val)\n res.push(cur)\n }\n res.pop()\n res.reverse()\n res.push(0)\n \n return res\n};"
] |
|
2,383 |
minimum-hours-of-training-to-win-a-competition
|
[
"Find the minimum number of training hours needed for the energy and experience separately, and sum the results.",
"Try to increase the energy and experience until you find how much is enough to win the competition."
] |
/**
* @param {number} initialEnergy
* @param {number} initialExperience
* @param {number[]} energy
* @param {number[]} experience
* @return {number}
*/
var minNumberOfHours = function(initialEnergy, initialExperience, energy, experience) {
};
|
You are entering a competition, and are given two positive integers initialEnergy and initialExperience denoting your initial energy and initial experience respectively.
You are also given two 0-indexed integer arrays energy and experience, both of length n.
You will face n opponents in order. The energy and experience of the ith opponent is denoted by energy[i] and experience[i] respectively. When you face an opponent, you need to have both strictly greater experience and energy to defeat them and move to the next opponent if available.
Defeating the ith opponent increases your experience by experience[i], but decreases your energy by energy[i].
Before starting the competition, you can train for some number of hours. After each hour of training, you can either choose to increase your initial experience by one, or increase your initial energy by one.
Return the minimum number of training hours required to defeat all n opponents.
Example 1:
Input: initialEnergy = 5, initialExperience = 3, energy = [1,4,3,2], experience = [2,6,3,1]
Output: 8
Explanation: You can increase your energy to 11 after 6 hours of training, and your experience to 5 after 2 hours of training.
You face the opponents in the following order:
- You have more energy and experience than the 0th opponent so you win.
Your energy becomes 11 - 1 = 10, and your experience becomes 5 + 2 = 7.
- You have more energy and experience than the 1st opponent so you win.
Your energy becomes 10 - 4 = 6, and your experience becomes 7 + 6 = 13.
- You have more energy and experience than the 2nd opponent so you win.
Your energy becomes 6 - 3 = 3, and your experience becomes 13 + 3 = 16.
- You have more energy and experience than the 3rd opponent so you win.
Your energy becomes 3 - 2 = 1, and your experience becomes 16 + 1 = 17.
You did a total of 6 + 2 = 8 hours of training before the competition, so we return 8.
It can be proven that no smaller answer exists.
Example 2:
Input: initialEnergy = 2, initialExperience = 4, energy = [1], experience = [3]
Output: 0
Explanation: You do not need any additional energy or experience to win the competition, so we return 0.
Constraints:
n == energy.length == experience.length
1 <= n <= 100
1 <= initialEnergy, initialExperience, energy[i], experience[i] <= 100
|
Easy
|
[
"array",
"greedy"
] |
[
"const minNumberOfHours = function(initialEnergy, initialExperience, energy, experience) {\n\tlet hours = 0\n\n\tfor(let i = 0; i < energy.length; i++) {\n\t\tif (initialEnergy > energy[i]) {\n\t\t\tinitialEnergy -= energy[i]\n\t\t} else {\n\t\t\thours += energy[i] - initialEnergy + 1\n\t\t\tinitialEnergy = 1\n\t\t}\n\n\t\tif (initialExperience <= experience[i]) {\n\t\t\thours += experience[i] - initialExperience + 1\n\t\t\tinitialExperience += experience[i] - initialExperience + 1\n\t\t}\n\n\t\tinitialExperience += experience[i]\n\t}\n\treturn hours\n};"
] |
|
2,384 |
largest-palindromic-number
|
[
"In order to form a valid palindrome, other than the middle digit in an odd-length palindrome, every digit needs to exist on both sides.",
"A longer palindrome implies a larger valued palindrome. For palindromes of the same length, the larger digits should occur first.",
"We can count the occurrences of each digit and build the palindrome starting from the ends. Starting from the larger digits, if there are still at least 2 occurrences of a digit, we can place these digits on each side.",
"Make sure to consider the special case for the center digit (if any) and zeroes. There should not be leading zeroes."
] |
/**
* @param {string} num
* @return {string}
*/
var largestPalindromic = function(num) {
};
|
You are given a string num consisting of digits only.
Return the largest palindromic integer (in the form of a string) that can be formed using digits taken from num. It should not contain leading zeroes.
Notes:
You do not need to use all the digits of num, but you must use at least one digit.
The digits can be reordered.
Example 1:
Input: num = "444947137"
Output: "7449447"
Explanation:
Use the digits "4449477" from "444947137" to form the palindromic integer "7449447".
It can be shown that "7449447" is the largest palindromic integer that can be formed.
Example 2:
Input: num = "00009"
Output: "9"
Explanation:
It can be shown that "9" is the largest palindromic integer that can be formed.
Note that the integer returned should not contain leading zeroes.
Constraints:
1 <= num.length <= 105
num consists of digits.
|
Medium
|
[
"hash-table",
"string",
"greedy"
] |
[
"const largestPalindromic = function(num) {\n let cnt = new Array(10).fill(0);\n for (let i = 0; i < num.length; i++) {\n let c = +num[i];\n cnt[c]++;\n }\n\n let list = [];\n for (let i = 9; i >= 0; i--) {\n if (i == 0 && list.length == 0) {\n break;\n }\n while (cnt[i] >= 2) {\n list.push(i);\n cnt[i] -= 2;\n }\n }\n let sb = '';\n for (let n of list) {\n sb += n;\n }\n for (let i = 9; i >= 0; i--) {\n if (cnt[i] > 0) {\n sb += i;\n break;\n }\n }\n for (let i = list.length - 1; i >= 0; i--) {\n sb += list[i];\n }\n return sb;\n};"
] |
|
2,385 |
amount-of-time-for-binary-tree-to-be-infected
|
[
"Convert the tree to an undirected graph to make it easier to handle.",
"Use BFS starting at the start node to find the distance between each node and the start node. The answer is the maximum distance."
] |
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} start
* @return {number}
*/
var amountOfTime = function(root, start) {
};
|
You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start.
Each minute, a node becomes infected if:
The node is currently uninfected.
The node is adjacent to an infected node.
Return the number of minutes needed for the entire tree to be infected.
Example 1:
Input: root = [1,5,3,null,4,10,6,9,2], start = 3
Output: 4
Explanation: The following nodes are infected during:
- Minute 0: Node 3
- Minute 1: Nodes 1, 10 and 6
- Minute 2: Node 5
- Minute 3: Node 4
- Minute 4: Nodes 9 and 2
It takes 4 minutes for the whole tree to be infected so we return 4.
Example 2:
Input: root = [1], start = 1
Output: 0
Explanation: At minute 0, the only node in the tree is infected so we return 0.
Constraints:
The number of nodes in the tree is in the range [1, 105].
1 <= Node.val <= 105
Each node has a unique value.
A node with a value of start exists in the tree.
|
Medium
|
[
"tree",
"depth-first-search",
"breadth-first-search",
"binary-tree"
] |
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
|
[
"var amountOfTime = function(root, start) {\n const graph = new Map()\n dfs(root)\n \n // console.log(graph)\n const visited = new Set([start])\n let q = [start]\n let res = 0\n while(q.length) {\n const tmp = []\n const size = q.length\n // console.log(q)\n for(let i = 0; i < size; i++) {\n const cur = q[i]\n for(const nxt of (graph.get(cur) || [])) {\n if(visited.has(nxt)) continue\n tmp.push(nxt)\n visited.add(nxt)\n }\n }\n \n q = tmp\n res++\n }\n \n return res - 1\n \n function dfs(node) {\n if(node == null) return\n if(node.left) {\n if(!graph.has(node.left.val)) graph.set(node.left.val, new Set())\n if(!graph.has(node.val)) graph.set(node.val, new Set())\n graph.get(node.val).add(node.left.val)\n graph.get(node.left.val).add(node.val)\n dfs(node.left)\n }\n if(node.right) {\n if(!graph.has(node.right.val)) graph.set(node.right.val, new Set())\n if(!graph.has(node.val)) graph.set(node.val, new Set())\n graph.get(node.val).add(node.right.val)\n graph.get(node.right.val).add(node.val)\n dfs(node.right)\n }\n }\n};"
] |
2,386 |
find-the-k-sum-of-an-array
|
[
"Start from the largest sum possible, and keep finding the next largest sum until you reach the kth sum.",
"Starting from a sum, what are the two next largest sums that you can obtain from it?"
] |
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var kSum = function(nums, k) {
};
|
You are given an integer array nums and a positive integer k. You can choose any subsequence of the array and sum all of its elements together.
We define the K-Sum of the array as the kth largest subsequence sum that can be obtained (not necessarily distinct).
Return the K-Sum of the array.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Note that the empty subsequence is considered to have a sum of 0.
Example 1:
Input: nums = [2,4,-2], k = 5
Output: 2
Explanation: All the possible subsequence sums that we can obtain are the following sorted in decreasing order:
- 6, 4, 4, 2, 2, 0, 0, -2.
The 5-Sum of the array is 2.
Example 2:
Input: nums = [1,-2,3,4,-10,12], k = 16
Output: 10
Explanation: The 16-Sum of the array is 10.
Constraints:
n == nums.length
1 <= n <= 105
-109 <= nums[i] <= 109
1 <= k <= min(2000, 2n)
|
Hard
|
[
"array",
"sorting",
"heap-priority-queue"
] |
[
"var kSum = function(nums, k) {\n let sum = 0, n = nums.length, pq = new MaxPriorityQueue({ compare: (x, y) => y[0] - x[0] });\n for (let i = 0; i < n; i++) {\n if (nums[i] < 0) {\n nums[i] *= -1;\n } else {\n sum += nums[i];\n }\n }\n if (k == 1) return sum;\n nums.sort((x, y) => x - y);\n pq.enqueue([sum - nums[0], 0]);\n for (let i = 2; i < k; i++) {\n let [x, idx] = pq.dequeue();\n if (idx + 1 < n) {\n pq.enqueue([x + nums[idx] - nums[idx + 1], idx + 1]);\n pq.enqueue([x - nums[idx + 1], idx + 1]);\n }\n }\n return pq.front()[0];\n};",
"const kSum = function (nums, k) {\n let sum = 0,\n n = nums.length,\n pq = new PriorityQueue((x, y) => y[0] < x[0])\n for (let i = 0; i < n; i++) {\n if (nums[i] < 0) {\n nums[i] *= -1\n } else {\n sum += nums[i]\n }\n }\n if (k == 1) return sum\n nums.sort((x, y) => x - y)\n pq.push([sum - nums[0], 0])\n for (let i = 2; i < k; i++) {\n let [x, idx] = pq.pop()\n if (idx + 1 < n) {\n pq.push([x + nums[idx] - nums[idx + 1], idx + 1])\n pq.push([x - nums[idx + 1], idx + 1])\n }\n }\n return pq.peek()[0]\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,389 |
longest-subsequence-with-limited-sum
|
[
"Solve each query independently.",
"When solving a query, which elements of nums should you choose to make the subsequence as long as possible?",
"Choose the smallest elements in nums that add up to a sum less than the query."
] |
/**
* @param {number[]} nums
* @param {number[]} queries
* @return {number[]}
*/
var answerQueries = function(nums, queries) {
};
|
You are given an integer array nums of length n, and an integer array queries of length m.
Return an array answer of length m where answer[i] is the maximum size of a subsequence that you can take from nums such that the sum of its elements is less than or equal to queries[i].
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [4,5,2,1], queries = [3,10,21]
Output: [2,3,4]
Explanation: We answer the queries as follows:
- The subsequence [2,1] has a sum less than or equal to 3. It can be proven that 2 is the maximum size of such a subsequence, so answer[0] = 2.
- The subsequence [4,5,1] has a sum less than or equal to 10. It can be proven that 3 is the maximum size of such a subsequence, so answer[1] = 3.
- The subsequence [4,5,2,1] has a sum less than or equal to 21. It can be proven that 4 is the maximum size of such a subsequence, so answer[2] = 4.
Example 2:
Input: nums = [2,3,4,5], queries = [1]
Output: [0]
Explanation: The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.
Constraints:
n == nums.length
m == queries.length
1 <= n, m <= 1000
1 <= nums[i], queries[i] <= 106
|
Easy
|
[
"array",
"binary-search",
"greedy",
"sorting",
"prefix-sum"
] |
[
"var answerQueries = function(nums, queries) {\n const n = nums, m = queries.length\n const arr = Array(n).fill(0)\n nums.sort((a, b) => a - b)\n \n const res = []\n for(const e of queries) {\n let sum = 0, i = 0\n while(sum <= e) {\n sum += nums[i]\n i++\n }\n res.push(i===0? 0 :i - 1)\n }\n \n return res\n};"
] |
|
2,390 |
removing-stars-from-a-string
|
[
"What data structure could we use to efficiently perform these removals?",
"Use a stack to store the characters. Pop one character off the stack at each star. Otherwise, we push the character onto the stack."
] |
/**
* @param {string} s
* @return {string}
*/
var removeStars = function(s) {
};
|
You are given a string s, which contains stars *.
In one operation, you can:
Choose a star in s.
Remove the closest non-star character to its left, as well as remove the star itself.
Return the string after all stars have been removed.
Note:
The input will be generated such that the operation is always possible.
It can be shown that the resulting string will always be unique.
Example 1:
Input: s = "leet**cod*e"
Output: "lecoe"
Explanation: Performing the removals from left to right:
- The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e".
- The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e".
- The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe".
There are no more stars, so we return "lecoe".
Example 2:
Input: s = "erase*****"
Output: ""
Explanation: The entire string is removed, so we return an empty string.
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters and stars *.
The operation above can be performed on s.
|
Medium
|
[
"string",
"stack",
"simulation"
] |
[
"var removeStars = function(s) {\n const stk = []\n for(const e of s) {\n if(e !== '*') stk.push(e)\n else {\n stk.pop()\n }\n }\n return stk.join('')\n};"
] |
|
2,391 |
minimum-amount-of-time-to-collect-garbage
|
[
"Where can we save time? By not visiting all the houses.",
"For each type of garbage, find the house with the highest index that has at least 1 unit of this type of garbage."
] |
/**
* @param {string[]} garbage
* @param {number[]} travel
* @return {number}
*/
var garbageCollection = function(garbage, travel) {
};
|
You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1 minute.
You are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1.
There are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house.
Only one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything.
Return the minimum number of minutes needed to pick up all the garbage.
Example 1:
Input: garbage = ["G","P","GP","GG"], travel = [2,4,3]
Output: 21
Explanation:
The paper garbage truck:
1. Travels from house 0 to house 1
2. Collects the paper garbage at house 1
3. Travels from house 1 to house 2
4. Collects the paper garbage at house 2
Altogether, it takes 8 minutes to pick up all the paper garbage.
The glass garbage truck:
1. Collects the glass garbage at house 0
2. Travels from house 0 to house 1
3. Travels from house 1 to house 2
4. Collects the glass garbage at house 2
5. Travels from house 2 to house 3
6. Collects the glass garbage at house 3
Altogether, it takes 13 minutes to pick up all the glass garbage.
Since there is no metal garbage, we do not need to consider the metal garbage truck.
Therefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage.
Example 2:
Input: garbage = ["MMM","PGM","GP"], travel = [3,10]
Output: 37
Explanation:
The metal garbage truck takes 7 minutes to pick up all the metal garbage.
The paper garbage truck takes 15 minutes to pick up all the paper garbage.
The glass garbage truck takes 15 minutes to pick up all the glass garbage.
It takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage.
Constraints:
2 <= garbage.length <= 105
garbage[i] consists of only the letters 'M', 'P', and 'G'.
1 <= garbage[i].length <= 10
travel.length == garbage.length - 1
1 <= travel[i] <= 100
|
Medium
|
[
"array",
"string",
"prefix-sum"
] |
[
"const garbageCollection = function(garbage, travel) {\n let res1 = 0, res2 = 0, res3 = 0\n const n = garbage.length\n // P\n res1 = helper('P')\n res2 = helper('M')\n res3 = helper('G')\n return res1 + res2 + res3\n \n function helper(target) {\n const arr = []\n for(let i = 0; i < n; i++) {\n const str = garbage[i]\n for(const e of str) {\n if(e === target) arr.push(e)\n }\n if(i + 1 < n) arr.push(travel[i])\n }\n const idx = arr.indexOf(target)\n const lastIdx =arr.lastIndexOf(target)\n let tmp = 0\n // console.log(arr, idx, lastIdx)\n for(let i = 0; i >= 0 && i<=lastIdx; i++) {\n const e = arr[i]\n if(e === target) tmp += 1\n else tmp += e\n }\n return tmp\n }\n};"
] |
|
2,392 |
build-a-matrix-with-conditions
|
[
"Can you think of the problem in terms of graphs?",
"What algorithm allows you to find the order of nodes in a graph?"
] |
/**
* @param {number} k
* @param {number[][]} rowConditions
* @param {number[][]} colConditions
* @return {number[][]}
*/
var buildMatrix = function(k, rowConditions, colConditions) {
};
|
You are given a positive integer k. You are also given:
a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and
a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti].
The two arrays contain integers from 1 to k.
You have to build a k x k matrix that contains each of the numbers from 1 to k exactly once. The remaining cells should have the value 0.
The matrix should also satisfy the following conditions:
The number abovei should appear in a row that is strictly above the row at which the number belowi appears for all i from 0 to n - 1.
The number lefti should appear in a column that is strictly left of the column at which the number righti appears for all i from 0 to m - 1.
Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.
Example 1:
Input: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]]
Output: [[3,0,0],[0,0,1],[0,2,0]]
Explanation: The diagram above shows a valid example of a matrix that satisfies all the conditions.
The row conditions are the following:
- Number 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix.
- Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix.
The column conditions are the following:
- Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix.
- Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix.
Note that there may be multiple correct answers.
Example 2:
Input: k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]]
Output: []
Explanation: From the first two conditions, 3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied.
No matrix can satisfy all the conditions, so we return the empty matrix.
Constraints:
2 <= k <= 400
1 <= rowConditions.length, colConditions.length <= 104
rowConditions[i].length == colConditions[i].length == 2
1 <= abovei, belowi, lefti, righti <= k
abovei != belowi
lefti != righti
|
Hard
|
[
"array",
"graph",
"topological-sort",
"matrix"
] |
[
"const buildMatrix = function (k, rowConditions, colConditions) {\n const res = Array.from({ length: k }, () => Array(k).fill(0))\n\n const row = khansAlgo(rowConditions, k)\n if (row.length != k) return []\n\n const col = khansAlgo(colConditions, k)\n if (col.length != k) return []\n\n const idx = Array(k + 1).fill(0)\n for (let j = 0; j < col.length; j++) {\n idx[col[j]] = j\n }\n for (let i = 0; i < k; i++) {\n res[i][idx[row[i]]] = row[i]\n }\n return res\n\n function khansAlgo(r, k) {\n const indegree = Array(k + 1).fill(0)\n const adj = Array.from({ length: k + 1 }, () => Array())\n\n for (let x of r) {\n indegree[x[1]]++\n adj[x[0]].push(x[1])\n }\n const row = []\n const q = []\n for (let i = 1; i <= k; i++) {\n if (indegree[i] == 0) {\n q.push(i)\n }\n }\n while (q.length) {\n let t = q.pop()\n\n row.push(t)\n for (let x of adj[t] || []) {\n indegree[x]--\n if (indegree[x] == 0) {\n q.push(x)\n }\n }\n }\n return row\n }\n}",
"const initializeGraph = (n) => {\n let g = []\n for (let i = 0; i < n; i++) {\n g.push([])\n }\n return g\n}\nconst packDGInDegree = (g, edges, indegree) => {\n for (const [u, v] of edges) {\n g[u].unshift(v)\n indegree[v]++\n }\n}\nconst initialize2DArray = (n, m) => {\n let d = []\n for (let i = 0; i < n; i++) {\n let t = Array(m).fill(0)\n d.push(t)\n }\n return d\n}\n\nconst buildMatrix = (k, rowConditions, colConditions) => {\n let gr = make(k, rowConditions),\n gc = make(k, colConditions),\n d = initialize2DArray(k, 2),\n res = initialize2DArray(k, k)\n if (gr.length == 0 || gc.length == 0) return []\n for (let i = 0; i < k; i++) {\n d[gr[i] - 1][0] = i\n d[gc[i] - 1][1] = i\n }\n for (let i = 0; i < k; i++) {\n let [x, y] = d[i]\n res[x][y] = i + 1\n }\n return res\n}\n\nconst make = (n, edges) => {\n let g = initializeGraph(n + 1),\n deg = Array(n + 1).fill(0)\n packDGInDegree(g, edges, deg)\n return topologicalSort_start_1(g, deg)\n}\n\nconst topologicalSort_start_1 = (g, indegree) => {\n let res = [],\n q = [],\n n = g.length - 1\n for (let i = 1; i <= n; i++) {\n if (indegree[i] == 0) q.push(i)\n }\n while (q.length) {\n let cur = q.shift()\n res.push(cur)\n for (const child of g[cur]) {\n indegree[child]--\n if (indegree[child] == 0) q.push(child)\n }\n }\n for (let i = 1; i <= n; i++) {\n if (indegree[i] > 0) return []\n }\n return res\n}"
] |
|
2,395 |
find-subarrays-with-equal-sum
|
[
"Use a counter to keep track of the subarray sums.",
"Use a hashset to check if any two sums are equal."
] |
/**
* @param {number[]} nums
* @return {boolean}
*/
var findSubarrays = function(nums) {
};
|
Given a 0-indexed integer array nums, determine whether there exist two subarrays of length 2 with equal sum. Note that the two subarrays must begin at different indices.
Return true if these subarrays exist, and false otherwise.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [4,2,4]
Output: true
Explanation: The subarrays with elements [4,2] and [2,4] have the same sum of 6.
Example 2:
Input: nums = [1,2,3,4,5]
Output: false
Explanation: No two subarrays of size 2 have the same sum.
Example 3:
Input: nums = [0,0,0]
Output: true
Explanation: The subarrays [nums[0],nums[1]] and [nums[1],nums[2]] have the same sum of 0.
Note that even though the subarrays have the same content, the two subarrays are considered different because they are in different positions in the original array.
Constraints:
2 <= nums.length <= 1000
-109 <= nums[i] <= 109
|
Easy
|
[
"array",
"hash-table"
] | null |
[] |
2,396 |
strictly-palindromic-number
|
[
"Consider the representation of the given number in the base n - 2.",
"The number n in base (n - 2) is always 12, which is not palindromic."
] |
/**
* @param {number} n
* @return {boolean}
*/
var isStrictlyPalindromic = function(n) {
};
|
An integer n is strictly palindromic if, for every base b between 2 and n - 2 (inclusive), the string representation of the integer n in base b is palindromic.
Given an integer n, return true if n is strictly palindromic and false otherwise.
A string is palindromic if it reads the same forward and backward.
Example 1:
Input: n = 9
Output: false
Explanation: In base 2: 9 = 1001 (base 2), which is palindromic.
In base 3: 9 = 100 (base 3), which is not palindromic.
Therefore, 9 is not strictly palindromic so we return false.
Note that in bases 4, 5, 6, and 7, n = 9 is also not palindromic.
Example 2:
Input: n = 4
Output: false
Explanation: We only consider base 2: 4 = 100 (base 2), which is not palindromic.
Therefore, we return false.
Constraints:
4 <= n <= 105
|
Medium
|
[
"math",
"two-pointers",
"brainteaser"
] | null |
[] |
2,397 |
maximum-rows-covered-by-columns
|
[
"Try a brute-force approach.",
"Iterate through all possible sets of exactly <code>cols</code> columns.",
"For each valid set, check how many rows are covered, and return the maximum."
] |
/**
* @param {number[][]} matrix
* @param {number} numSelect
* @return {number}
*/
var maximumRows = function(matrix, numSelect) {
};
|
You are given a 0-indexed m x n binary matrix matrix and an integer numSelect, which denotes the number of distinct columns you must select from matrix.
Let us consider s = {c1, c2, ...., cnumSelect} as the set of columns selected by you. A row row is covered by s if:
For each cell matrix[row][col] (0 <= col <= n - 1) where matrix[row][col] == 1, col is present in s or,
No cell in row has a value of 1.
You need to choose numSelect columns such that the number of rows that are covered is maximized.
Return the maximum number of rows that can be covered by a set of numSelect columns.
Example 1:
Input: matrix = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]], numSelect = 2
Output: 3
Explanation: One possible way to cover 3 rows is shown in the diagram above.
We choose s = {0, 2}.
- Row 0 is covered because it has no occurrences of 1.
- Row 1 is covered because the columns with value 1, i.e. 0 and 2 are present in s.
- Row 2 is not covered because matrix[2][1] == 1 but 1 is not present in s.
- Row 3 is covered because matrix[2][2] == 1 and 2 is present in s.
Thus, we can cover three rows.
Note that s = {1, 2} will also cover 3 rows, but it can be shown that no more than three rows can be covered.
Example 2:
Input: matrix = [[1],[0]], numSelect = 1
Output: 2
Explanation: Selecting the only column will result in both rows being covered since the entire matrix is selected.
Therefore, we return 2.
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 12
matrix[i][j] is either 0 or 1.
1 <= numSelect <= n
|
Medium
|
[
"array",
"backtracking",
"bit-manipulation",
"matrix",
"enumeration"
] |
[
"const maximumRows = function(matrix, numSelect) {\n const m = matrix.length, n = matrix[0].length\n const limit = 1 << n\n \n let res = 0\n \n for(let mask = 1; mask < limit; mask++) {\n if(bitCnt(mask) > numSelect) continue\n let num = 0\n for(let i = 0; i < m; i++) {\n let mark = true\n for(let j = n - 1; j >= 0; j--) {\n if(matrix[i][j] === 1 && (mask & (1 << j)) === 0) {\n mark = false\n break\n }\n }\n if(mark) num++\n }\n res = Math.max(res, num)\n }\n \n return res\n \n function bitCnt(num) {\n let res = 0\n while(num) {\n num = num & (num - 1)\n res++\n }\n return res\n }\n};"
] |
|
2,398 |
maximum-number-of-robots-within-budget
|
[
"Use binary search to convert the problem into checking if we can find a specific number of consecutive robots within the budget.",
"Maintain a sliding window of the consecutive robots being considered.",
"Use either a map, deque, or heap to find the maximum charge times in the window efficiently."
] |
/**
* @param {number[]} chargeTimes
* @param {number[]} runningCosts
* @param {number} budget
* @return {number}
*/
var maximumRobots = function(chargeTimes, runningCosts, budget) {
};
|
You have n robots. You are given two 0-indexed integer arrays, chargeTimes and runningCosts, both of length n. The ith robot costs chargeTimes[i] units to charge and costs runningCosts[i] units to run. You are also given an integer budget.
The total cost of running k chosen robots is equal to max(chargeTimes) + k * sum(runningCosts), where max(chargeTimes) is the largest charge cost among the k robots and sum(runningCosts) is the sum of running costs among the k robots.
Return the maximum number of consecutive robots you can run such that the total cost does not exceed budget.
Example 1:
Input: chargeTimes = [3,6,1,3,4], runningCosts = [2,1,3,4,5], budget = 25
Output: 3
Explanation:
It is possible to run all individual and consecutive pairs of robots within budget.
To obtain answer 3, consider the first 3 robots. The total cost will be max(3,6,1) + 3 * sum(2,1,3) = 6 + 3 * 6 = 24 which is less than 25.
It can be shown that it is not possible to run more than 3 consecutive robots within budget, so we return 3.
Example 2:
Input: chargeTimes = [11,12,19], runningCosts = [10,8,7], budget = 19
Output: 0
Explanation: No robot can be run that does not exceed the budget, so we return 0.
Constraints:
chargeTimes.length == runningCosts.length == n
1 <= n <= 5 * 104
1 <= chargeTimes[i], runningCosts[i] <= 105
1 <= budget <= 1015
|
Hard
|
[
"array",
"binary-search",
"queue",
"sliding-window",
"heap-priority-queue",
"prefix-sum"
] |
[
"const maximumRobots = function(chargeTimes, runningCosts, budget) {\n const times = chargeTimes, costs = runningCosts\n let sum = 0, res = 0, j = 0\n const q = [], n = times.length\n for(let i = 0; i < n; i++) {\n sum += costs[i]\n while(q.length && times[q[q.length - 1]] <= times[i]) q.pop()\n q.push(i)\n \n if(q.length && times[q[0]] + (i - j + 1) * sum > budget) {\n if(q[0] === j) q.shift()\n sum -= costs[j]\n j++\n }\n res = Math.max(res, i - j + 1)\n }\n \n return res\n};"
] |
|
2,399 |
check-distances-between-same-letters
|
[
"Create an integer array of size 26 to keep track of the first occurrence of each letter.",
"The number of letters between indices i and j is j - i - 1."
] |
/**
* @param {string} s
* @param {number[]} distance
* @return {boolean}
*/
var checkDistances = function(s, distance) {
};
|
You are given a 0-indexed string s consisting of only lowercase English letters, where each letter in s appears exactly twice. You are also given a 0-indexed integer array distance of length 26.
Each letter in the alphabet is numbered from 0 to 25 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, ... , 'z' -> 25).
In a well-spaced string, the number of letters between the two occurrences of the ith letter is distance[i]. If the ith letter does not appear in s, then distance[i] can be ignored.
Return true if s is a well-spaced string, otherwise return false.
Example 1:
Input: s = "abaccb", distance = [1,3,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: true
Explanation:
- 'a' appears at indices 0 and 2 so it satisfies distance[0] = 1.
- 'b' appears at indices 1 and 5 so it satisfies distance[1] = 3.
- 'c' appears at indices 3 and 4 so it satisfies distance[2] = 0.
Note that distance[3] = 5, but since 'd' does not appear in s, it can be ignored.
Return true because s is a well-spaced string.
Example 2:
Input: s = "aa", distance = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: false
Explanation:
- 'a' appears at indices 0 and 1 so there are zero letters between them.
Because distance[0] = 1, s is not a well-spaced string.
Constraints:
2 <= s.length <= 52
s consists only of lowercase English letters.
Each letter appears in s exactly twice.
distance.length == 26
0 <= distance[i] <= 50
|
Easy
|
[
"array",
"hash-table",
"string"
] |
[
"var checkDistances = function(s, distance) {\n const hash = {}\n const a = 'a'.charCodeAt(0)\n const n = s.length\n for(let i = 0; i < n; i++) {\n if(hash[s[i]] == null) hash[s[i]] = []\n hash[s[i]].push(i)\n }\n const keys = Object.keys(hash)\n for(let i = 0; i < keys.length; i++) {\n const k = keys[i]\n const idx = k.charCodeAt(0) - a\n if(hash[k][1] - hash[k][0] !== distance[idx] + 1) return false\n }\n return true\n};"
] |
|
2,400 |
number-of-ways-to-reach-a-position-after-exactly-k-steps
|
[
"How many steps to the left and to the right do you need to make exactly?",
"Does the order of the steps matter?",
"Use combinatorics to find the number of ways to order the steps."
] |
/**
* @param {number} startPos
* @param {number} endPos
* @param {number} k
* @return {number}
*/
var numberOfWays = function(startPos, endPos, k) {
};
|
You are given two positive integers startPos and endPos. Initially, you are standing at position startPos on an infinite number line. With one step, you can move either one position to the left, or one position to the right.
Given a positive integer k, return the number of different ways to reach the position endPos starting from startPos, such that you perform exactly k steps. Since the answer may be very large, return it modulo 109 + 7.
Two ways are considered different if the order of the steps made is not exactly the same.
Note that the number line includes negative integers.
Example 1:
Input: startPos = 1, endPos = 2, k = 3
Output: 3
Explanation: We can reach position 2 from 1 in exactly 3 steps in three ways:
- 1 -> 2 -> 3 -> 2.
- 1 -> 2 -> 1 -> 2.
- 1 -> 0 -> 1 -> 2.
It can be proven that no other way is possible, so we return 3.
Example 2:
Input: startPos = 2, endPos = 5, k = 10
Output: 0
Explanation: It is impossible to reach position 5 from position 2 in exactly 10 steps.
Constraints:
1 <= startPos, endPos, k <= 1000
|
Medium
|
[
"math",
"dynamic-programming",
"combinatorics"
] |
[
"const dp = Array.from({ length: 1000 + 1 }, () => Array(1000 + 1).fill(0))\nconst mod = 1e9 + 7\n\nconst numberOfWays = function(startPos, endPos, k) {\n const { abs } = Math\n if (dp[1][1] == 0) {\n for (let k = 1; k <= 1000; ++k) {\n dp[k][k] = 1;\n for (let i = 0; i < k; ++i) {\n dp[k][i] = ((i === 0 ? dp[k - 1][1] : dp[k - 1][i - 1]) + dp[k - 1][i + 1]) % mod; \n }\n } \n }\n\n return dp[k][abs(startPos - endPos)];\n};",
"var numberOfWays = function(startPos, endPos, k) {\n const ll = BigInt, mod = ll(1e9 + 7), N = 1005;\n\n let fact, ifact, inv;\n const comb_init = () => {\n fact = Array(N).fill(0);\n ifact = Array(N).fill(0);\n inv = Array(N).fill(0);\n fact[0] = ifact[0] = inv[1] = 1n;\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 const 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 comb_init();\n let res = 0n;\n for (let i = 0; i <= k; i++) {\n let moveRight = i, moveLeft = k - i;\n if (startPos + moveRight - moveLeft == endPos) res += comb(k, i);\n }\n return res;\n \n};"
] |
|
2,401 |
longest-nice-subarray
|
[
"What is the maximum possible length of a nice subarray?",
"The length of the longest nice subarray cannot exceed 30. Why is that?"
] |
/**
* @param {number[]} nums
* @return {number}
*/
var longestNiceSubarray = function(nums) {
};
|
You are given an array nums consisting of positive integers.
We call a subarray of nums nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0.
Return the length of the longest nice subarray.
A subarray is a contiguous part of an array.
Note that subarrays of length 1 are always considered nice.
Example 1:
Input: nums = [1,3,8,48,10]
Output: 3
Explanation: The longest nice subarray is [3,8,48]. This subarray satisfies the conditions:
- 3 AND 8 = 0.
- 3 AND 48 = 0.
- 8 AND 48 = 0.
It can be proven that no longer nice subarray can be obtained, so we return 3.
Example 2:
Input: nums = [3,1,5,11,13]
Output: 1
Explanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
|
Medium
|
[
"array",
"bit-manipulation",
"sliding-window"
] |
[
"const longestNiceSubarray = function (nums) {\n let res = 1, i = 0, j = 0, mask = 0\n const n = nums.length\n for(i = 0; i < n; i++) {\n const cur = nums[i]\n while((cur & mask) !== 0) {\n mask ^= nums[j]\n j++\n }\n mask |= cur\n // console.log(i, j, mask, i - j +1)\n res = Math.max(res, i - j + 1)\n }\n \n return res\n}",
"var longestNiceSubarray = function(nums) {\n let max = 1;\n let stack = [];\n for(let i =0;i<nums.length;i++){\n if(nums[i]&nums[i+1]) continue;\n stack.push(nums[i])\n for(let j =i+1;j<nums.length;j++){\n let state = true;\n for(el of stack){\n if(el&nums[j]){\n state=false;\n break;\n }\n }\n if(state) {\n stack.push(nums[j]);\n max = Math.max(max,stack.length);\n }\n else{\n stack = []\n break;\n }\n }\n }\n return max;\n};"
] |
|
2,402 |
meeting-rooms-iii
|
[
"Sort meetings based on start times.",
"Use two min heaps, the first one keeps track of the numbers of all the rooms that are free. The second heap keeps track of the end times of all the meetings that are happening and the room that they are in.",
"Keep track of the number of times each room is used in an array.",
"With each meeting, check if there are any free rooms. If there are, then use the room with the smallest number. Otherwise, assign the meeting to the room whose meeting will end the soonest."
] |
/**
* @param {number} n
* @param {number[][]} meetings
* @return {number}
*/
var mostBooked = function(n, meetings) {
};
|
You are given an integer n. There are n rooms numbered from 0 to n - 1.
You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique.
Meetings are allocated to rooms in the following manner:
Each meeting will take place in the unused room with the lowest number.
If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting.
When a room becomes unused, meetings that have an earlier original start time should be given the room.
Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number.
A half-closed interval [a, b) is the interval between a and b including a and not including b.
Example 1:
Input: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]
Output: 0
Explanation:
- At time 0, both rooms are not being used. The first meeting starts in room 0.
- At time 1, only room 1 is not being used. The second meeting starts in room 1.
- At time 2, both rooms are being used. The third meeting is delayed.
- At time 3, both rooms are being used. The fourth meeting is delayed.
- At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10).
- At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11).
Both rooms 0 and 1 held 2 meetings, so we return 0.
Example 2:
Input: n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]]
Output: 1
Explanation:
- At time 1, all three rooms are not being used. The first meeting starts in room 0.
- At time 2, rooms 1 and 2 are not being used. The second meeting starts in room 1.
- At time 3, only room 2 is not being used. The third meeting starts in room 2.
- At time 4, all three rooms are being used. The fourth meeting is delayed.
- At time 5, the meeting in room 2 finishes. The fourth meeting starts in room 2 for the time period [5,10).
- At time 6, all three rooms are being used. The fifth meeting is delayed.
- At time 10, the meetings in rooms 1 and 2 finish. The fifth meeting starts in room 1 for the time period [10,12).
Room 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so we return 1.
Constraints:
1 <= n <= 100
1 <= meetings.length <= 105
meetings[i].length == 2
0 <= starti < endi <= 5 * 105
All the values of starti are unique.
|
Hard
|
[
"array",
"sorting",
"heap-priority-queue"
] |
[
"const mostBooked = function(n, meetings) {\n const rooms = Array(n).fill(0)\n const busy = new PQ((a, b) => a[1] === b[1] ? a[0] < b[0] : a[1] < b[1])\n const avail = new PQ((a, b) => a[0] < b[0])\n for(let i = 0; i < n; i++) {\n avail.push([i, 0])\n }\n meetings.sort((a, b) => a[0] - b[0])\n \n for(let i = 0, len = meetings.length; i < len; i++) {\n const [s, e] = meetings[i]\n while(!busy.isEmpty() && busy.peek()[1] <= s) {\n avail.push(busy.pop())\n }\n if(!avail.isEmpty()) {\n const r = avail.pop()\n r[1] = e\n rooms[r[0]]++\n busy.push(r)\n } else {\n const r = busy.pop()\n r[1] += e - s\n rooms[r[0]]++\n busy.push(r)\n }\n }\n let res = 0\n // console.log(meetings.length, rooms)\n const maxNum = Math.max(...rooms)\n for(let i = 0; i < n; i++) {\n if(rooms[i] === maxNum) {\n res = i\n break\n }\n }\n return res\n};\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}",
"var mostBooked = function(n, meetings) {\n const count = new Array(n).fill(0);\n const freeTime = new Array(n).fill(0);\n meetings.sort((a, b) => a[0] - b[0]);\n for(let i = 0 ; i < meetings.length ; i++){\n let minRoom = -1;\n let minTime = Number.MAX_SAFE_INTEGER;\n for(let j = 0 ; j < n ; j++){\n if(freeTime[j] <= meetings[i][0]){\n count[j]++;\n freeTime[j] = meetings[i][1];\n minRoom = -1;\n break;\n }\n if(freeTime[j] < minTime){\n minTime = freeTime[j];\n minRoom = j;\n }\n }\n if(minRoom !== -1){\n count[minRoom]++;\n freeTime[minRoom] += meetings[i][1] - meetings[i][0]; \n }\n }\n \n let ans = 0;\n let maxCount = count[0];\n for(let i = 1 ; i < n ; i++){\n if(count[i] > maxCount){ \n ans = i;\n maxCount = count[i];\n }\n }\n return ans; \n};"
] |
|
2,404 |
most-frequent-even-element
|
[
"Could you count the frequency of each even element in the array?",
"Would a hashmap help?"
] |
/**
* @param {number[]} nums
* @return {number}
*/
var mostFrequentEven = function(nums) {
};
|
Given an integer array nums, return the most frequent even element.
If there is a tie, return the smallest one. If there is no such element, return -1.
Example 1:
Input: nums = [0,1,2,2,4,4,1]
Output: 2
Explanation:
The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most.
We return the smallest one, which is 2.
Example 2:
Input: nums = [4,4,4,9,2,4]
Output: 4
Explanation: 4 is the even element appears the most.
Example 3:
Input: nums = [29,47,21,41,13,37,25,7]
Output: -1
Explanation: There is no even element.
Constraints:
1 <= nums.length <= 2000
0 <= nums[i] <= 105
|
Easy
|
[
"array",
"hash-table",
"counting"
] |
[
"var mostFrequentEven = function(nums) {\n const hash = {}\n for(const e of nums) {\n if(e % 2 === 0) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n }\n const entries = Object.entries(hash)\n if(entries.length === 0) return -1\n entries.sort((a, b) => b[1] - a[1])\n const v = entries[0][1]\n const keys = Object.keys(hash).map(e => +e).sort((a, b) => a - b)\n// console.log(hash)\n for(const k of keys) {\n if(hash[k] === v) return k\n }\n \n return -1\n};"
] |
|
2,405 |
optimal-partition-of-string
|
[
"Try to come up with a greedy approach.",
"From left to right, extend every substring in the partition as much as possible."
] |
/**
* @param {string} s
* @return {number}
*/
var partitionString = function(s) {
};
|
Given a string s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.
Return the minimum number of substrings in such a partition.
Note that each character should belong to exactly one substring in a partition.
Example 1:
Input: s = "abacaba"
Output: 4
Explanation:
Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
It can be shown that 4 is the minimum number of substrings needed.
Example 2:
Input: s = "ssssss"
Output: 6
Explanation:
The only valid partition is ("s","s","s","s","s","s").
Constraints:
1 <= s.length <= 105
s consists of only English lowercase letters.
|
Medium
|
[
"hash-table",
"string",
"greedy"
] |
[
"var partitionString = function(s) {\n let res = 0, n = s.length\n let i = 0, j = 0, num = 0\n const set = new Set()\n for(let i = 0; i < n; i++) {\n const ch = s[i]\n if(set.has(ch)) {\n res++\n num = 1\n set.clear()\n } else {\n\n }\n set.add(ch)\n }\n \n return res + 1\n};"
] |
|
2,406 |
divide-intervals-into-minimum-number-of-groups
|
[
"Can you find a different way to describe the question?",
"The minimum number of groups we need is equivalent to the maximum number of intervals that overlap at some point. How can you find that?"
] |
/**
* @param {number[][]} intervals
* @return {number}
*/
var minGroups = function(intervals) {
};
|
You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti].
You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other.
Return the minimum number of groups you need to make.
Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect.
Example 1:
Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]
Output: 3
Explanation: We can divide the intervals into the following groups:
- Group 1: [1, 5], [6, 8].
- Group 2: [2, 3], [5, 10].
- Group 3: [1, 10].
It can be proven that it is not possible to divide the intervals into fewer than 3 groups.
Example 2:
Input: intervals = [[1,3],[5,6],[8,10],[11,13]]
Output: 1
Explanation: None of the intervals overlap, so we can put all of them in one group.
Constraints:
1 <= intervals.length <= 105
intervals[i].length == 2
1 <= lefti <= righti <= 106
|
Medium
|
[
"array",
"two-pointers",
"greedy",
"sorting",
"heap-priority-queue",
"prefix-sum"
] |
[
"var minGroups = function(intervals) {\n const hash = {}\n for(let [s, e] of intervals) {\n e = e + 1\n hash[s] = (hash[s] || 0) + 1\n hash[e] = (hash[e] || 0) - 1\n }\n let res = 0, cur = 0\n const keys = Object.keys(hash).map(e => +e)\n keys.sort((a, b) => a - b)\n for(const k of keys) {\n cur += hash[k]\n res = Math.max(res, cur)\n }\n return res\n};",
"const minGroups = function(intervals) {\n const hash = {}\n for(const [s, e] of intervals) {\n if(hash[s] == null) hash[s] = 0\n if(hash[e + 1] == null) hash[e + 1] = 0\n hash[s]++\n hash[e + 1]--\n }\n const keys = Object.keys(hash)\n keys.sort((a, b) => a - b)\n const n = keys.length\n\n const arr = Array(n).fill(0)\n arr[0] = hash[keys[0]]\n let res = arr[0]\n for(let i = 1; i < n; i++) {\n arr[i] = hash[keys[i]] + arr[i - 1]\n res = Math.max(res, arr[i])\n }\n return res\n};"
] |
|
2,407 |
longest-increasing-subsequence-ii
|
[
"We can use dynamic programming. Let dp[i][val] be the answer using only the first i + 1 elements, and the last element in the subsequence is equal to val.",
"The only value that might change between dp[i - 1] and dp[i] are dp[i - 1][val] and dp[i][val].",
"Try using dp[i - 1] and the fact that the second last element in the subsequence has to fall within a range to calculate dp[i][val].",
"We can use a segment tree to find the maximum value in dp[i - 1] within a certain range."
] |
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var lengthOfLIS = function(nums, k) {
};
|
You are given an integer array nums and an integer k.
Find the longest subsequence of nums that meets the following requirements:
The subsequence is strictly increasing and
The difference between adjacent elements in the subsequence is at most k.
Return the length of the longest subsequence that meets the requirements.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [4,2,1,4,3,4,5,8,15], k = 3
Output: 5
Explanation:
The longest subsequence that meets the requirements is [1,3,4,5,8].
The subsequence has a length of 5, so we return 5.
Note that the subsequence [1,3,4,5,8,15] does not meet the requirements because 15 - 8 = 7 is larger than 3.
Example 2:
Input: nums = [7,4,5,1,8,12,4,7], k = 5
Output: 4
Explanation:
The longest subsequence that meets the requirements is [4,5,8,12].
The subsequence has a length of 4, so we return 4.
Example 3:
Input: nums = [1,5], k = 1
Output: 1
Explanation:
The longest subsequence that meets the requirements is [1].
The subsequence has a length of 1, so we return 1.
Constraints:
1 <= nums.length <= 105
1 <= nums[i], k <= 105
|
Hard
|
[
"array",
"divide-and-conquer",
"dynamic-programming",
"binary-indexed-tree",
"segment-tree",
"queue",
"monotonic-queue"
] |
[
"const lengthOfLIS = (nums, k) => {\n const a = nums\n let max = Math.max(...a), st = new SegmentTreeRMQ(max + 3), res = 0;\n for (const x of a) {\n let l = Math.max(x-k, 0), r = x;\n let min = st.minx(l, r), maxL = min == Number.MAX_SAFE_INTEGER ? 0 : -min;\n maxL++;\n res = Math.max(res, maxL);\n st.update(x, -maxL);\n }\n return res;\n};\n///////////////////////////////////////////// Template ///////////////////////////////////////////////////////////\n// using array format\nfunction SegmentTreeRMQ(n) {\n let h = Math.ceil(Math.log2(n)), len = 2 * 2 ** h, a = Array(len).fill(Number.MAX_SAFE_INTEGER);\n h = 2 ** h;\n return { update, minx, indexOf, tree }\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,409 |
count-days-spent-together
|
[
"For a given day, determine if Alice or Bob or both are in Rome.",
"Brute force all 365 days for both Alice and Bob."
] |
/**
* @param {string} arriveAlice
* @param {string} leaveAlice
* @param {string} arriveBob
* @param {string} leaveBob
* @return {number}
*/
var countDaysTogether = function(arriveAlice, leaveAlice, arriveBob, leaveBob) {
};
|
Alice and Bob are traveling to Rome for separate business meetings.
You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob. Alice will be in the city from the dates arriveAlice to leaveAlice (inclusive), while Bob will be in the city from the dates arriveBob to leaveBob (inclusive). Each will be a 5-character string in the format "MM-DD", corresponding to the month and day of the date.
Return the total number of days that Alice and Bob are in Rome together.
You can assume that all dates occur in the same calendar year, which is not a leap year. Note that the number of days per month can be represented as: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].
Example 1:
Input: arriveAlice = "08-15", leaveAlice = "08-18", arriveBob = "08-16", leaveBob = "08-19"
Output: 3
Explanation: Alice will be in Rome from August 15 to August 18. Bob will be in Rome from August 16 to August 19. They are both in Rome together on August 16th, 17th, and 18th, so the answer is 3.
Example 2:
Input: arriveAlice = "10-01", leaveAlice = "10-31", arriveBob = "11-01", leaveBob = "12-31"
Output: 0
Explanation: There is no day when Alice and Bob are in Rome together, so we return 0.
Constraints:
All dates are provided in the format "MM-DD".
Alice and Bob's arrival dates are earlier than or equal to their leaving dates.
The given dates are valid dates of a non-leap year.
|
Easy
|
[
"math",
"string"
] | null |
[] |
2,410 |
maximum-matching-of-players-with-trainers
|
[
"Sort both the arrays.",
"Construct the matching greedily."
] |
/**
* @param {number[]} players
* @param {number[]} trainers
* @return {number}
*/
var matchPlayersAndTrainers = function(players, trainers) {
};
|
You are given a 0-indexed integer array players, where players[i] represents the ability of the ith player. You are also given a 0-indexed integer array trainers, where trainers[j] represents the training capacity of the jth trainer.
The ith player can match with the jth trainer if the player's ability is less than or equal to the trainer's training capacity. Additionally, the ith player can be matched with at most one trainer, and the jth trainer can be matched with at most one player.
Return the maximum number of matchings between players and trainers that satisfy these conditions.
Example 1:
Input: players = [4,7,9], trainers = [8,2,5,8]
Output: 2
Explanation:
One of the ways we can form two matchings is as follows:
- players[0] can be matched with trainers[0] since 4 <= 8.
- players[1] can be matched with trainers[3] since 7 <= 8.
It can be proven that 2 is the maximum number of matchings that can be formed.
Example 2:
Input: players = [1,1,1], trainers = [10]
Output: 1
Explanation:
The trainer can be matched with any of the 3 players.
Each player can only be matched with one trainer, so the maximum answer is 1.
Constraints:
1 <= players.length, trainers.length <= 105
1 <= players[i], trainers[j] <= 109
|
Medium
|
[
"array",
"two-pointers",
"greedy",
"sorting"
] | null |
[] |
2,411 |
smallest-subarrays-with-maximum-bitwise-or
|
[
"Consider trying to solve the problem for each bit position separately.",
"For each bit position, find the position of the next number that has a 1 in that position, if any.",
"Take the maximum distance to such a number, including the current number.",
"Iterate backwards to achieve a linear complexity."
] |
/**
* @param {number[]} nums
* @return {number[]}
*/
var smallestSubarrays = function(nums) {
};
|
You are given a 0-indexed array nums of length n, consisting of non-negative integers. For each index i from 0 to n - 1, you must determine the size of the minimum sized non-empty subarray of nums starting at i (inclusive) that has the maximum possible bitwise OR.
In other words, let Bij be the bitwise OR of the subarray nums[i...j]. You need to find the smallest subarray starting at i, such that bitwise OR of this subarray is equal to max(Bik) where i <= k <= n - 1.
The bitwise OR of an array is the bitwise OR of all the numbers in it.
Return an integer array answer of size n where answer[i] is the length of the minimum sized subarray starting at i with maximum bitwise OR.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,0,2,1,3]
Output: [3,3,2,2,1]
Explanation:
The maximum possible bitwise OR starting at any index is 3.
- Starting at index 0, the shortest subarray that yields it is [1,0,2].
- Starting at index 1, the shortest subarray that yields the maximum bitwise OR is [0,2,1].
- Starting at index 2, the shortest subarray that yields the maximum bitwise OR is [2,1].
- Starting at index 3, the shortest subarray that yields the maximum bitwise OR is [1,3].
- Starting at index 4, the shortest subarray that yields the maximum bitwise OR is [3].
Therefore, we return [3,3,2,2,1].
Example 2:
Input: nums = [1,2]
Output: [2,1]
Explanation:
Starting at index 0, the shortest subarray that yields the maximum bitwise OR is of length 2.
Starting at index 1, the shortest subarray that yields the maximum bitwise OR is of length 1.
Therefore, we return [2,1].
Constraints:
n == nums.length
1 <= n <= 105
0 <= nums[i] <= 109
|
Medium
|
[
"array",
"binary-search",
"bit-manipulation",
"sliding-window"
] |
[
"const smallestSubarrays = function (nums) {\n const n = nums.length,\n last = Array(30).fill(0),\n res = []\n for (let i = n - 1; i >= 0; i--) {\n res[i] = 1\n for (let j = 0; j < 30; j++) {\n if ((nums[i] & (1 << j)) > 0) last[j] = i\n res[i] = Math.max(res[i], last[j] - i + 1)\n }\n }\n return res\n}"
] |
|
2,412 |
minimum-money-required-before-transactions
|
[
"Split transactions that have cashback greater or equal to cost apart from transactions that have cashback less than cost. You will always <strong>earn</strong> money in the first scenario.",
"For transactions that have cashback greater or equal to cost, sort them by cost in descending order.",
"For transactions that have cashback less than cost, sort them by cashback in ascending order."
] |
/**
* @param {number[][]} transactions
* @return {number}
*/
var minimumMoney = function(transactions) {
};
|
You are given a 0-indexed 2D integer array transactions, where transactions[i] = [costi, cashbacki].
The array describes transactions, where each transaction must be completed exactly once in some order. At any given moment, you have a certain amount of money. In order to complete transaction i, money >= costi must hold true. After performing a transaction, money becomes money - costi + cashbacki.
Return the minimum amount of money required before any transaction so that all of the transactions can be completed regardless of the order of the transactions.
Example 1:
Input: transactions = [[2,1],[5,0],[4,2]]
Output: 10
Explanation:
Starting with money = 10, the transactions can be performed in any order.
It can be shown that starting with money < 10 will fail to complete all transactions in some order.
Example 2:
Input: transactions = [[3,0],[0,3]]
Output: 3
Explanation:
- If transactions are in the order [[3,0],[0,3]], the minimum money required to complete the transactions is 3.
- If transactions are in the order [[0,3],[3,0]], the minimum money required to complete the transactions is 0.
Thus, starting with money = 3, the transactions can be performed in any order.
Constraints:
1 <= transactions.length <= 105
transactions[i].length == 2
0 <= costi, cashbacki <= 109
|
Hard
|
[
"array",
"greedy",
"sorting"
] |
[
"const minimumMoney = function(transactions) {\n let res = 0;\n let v = 0;\n for (const a of transactions) {\n v = Math.max(v, Math.min(a[0], a[1]));\n res += Math.max(a[0] - a[1], 0);\n }\n return res + v;\n};"
] |
|
2,413 |
smallest-even-multiple
|
[
"A guaranteed way to find a multiple of 2 and n is to multiply them together. When is this the answer, and when is there a smaller answer?",
"There is a smaller answer when n is even."
] |
/**
* @param {number} n
* @return {number}
*/
var smallestEvenMultiple = function(n) {
};
|
Given a positive integer n, return the smallest positive integer that is a multiple of both 2 and n.
Example 1:
Input: n = 5
Output: 10
Explanation: The smallest multiple of both 5 and 2 is 10.
Example 2:
Input: n = 6
Output: 6
Explanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple of itself.
Constraints:
1 <= n <= 150
|
Easy
|
[
"math",
"number-theory"
] |
[
"var smallestEvenMultiple = function(n) {\n return n % 2 === 0 ? n : 2 * n\n};"
] |
|
2,414 |
length-of-the-longest-alphabetical-continuous-substring
|
[
"What is the longest possible continuous substring?",
"The size of the longest possible continuous substring is at most 26, so we can just brute force the answer."
] |
/**
* @param {string} s
* @return {number}
*/
var longestContinuousSubstring = function(s) {
};
|
An alphabetical continuous string is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string "abcdefghijklmnopqrstuvwxyz".
For example, "abc" is an alphabetical continuous string, while "acb" and "za" are not.
Given a string s consisting of lowercase letters only, return the length of the longest alphabetical continuous substring.
Example 1:
Input: s = "abacaba"
Output: 2
Explanation: There are 4 distinct continuous substrings: "a", "b", "c" and "ab".
"ab" is the longest continuous substring.
Example 2:
Input: s = "abcde"
Output: 5
Explanation: "abcde" is the longest continuous substring.
Constraints:
1 <= s.length <= 105
s consists of only English lowercase letters.
|
Medium
|
[
"string"
] |
[
"var longestContinuousSubstring = function(s) {\n let res = 1\n let tmp = 1\n const n = s.length\n let pre = s[0]\n for(let i = 1;i < n; i++) {\n const ch = s[i]\n if(ch.charCodeAt(0) - pre.charCodeAt(0) === 1) {\n tmp++\n pre = ch\n res = Math.max(res, tmp)\n } else {\n pre = ch\n tmp = 1\n }\n }\n \n return res\n};"
] |
|
2,415 |
reverse-odd-levels-of-binary-tree
|
[
"Try to solve recursively for each level independently.",
"While performing a depth-first search, pass the left and right nodes (which should be paired) to the next level. If the current level is odd, then reverse their values, or else recursively move to the next level."
] |
/**
* 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 {TreeNode}
*/
var reverseOddLevels = function(root) {
};
|
Given the root of a perfect binary tree, reverse the node values at each odd level of the tree.
For example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should become [18,29,11,7,4,3,1,2].
Return the root of the reversed tree.
A binary tree is perfect if all parent nodes have two children and all leaves are on the same level.
The level of a node is the number of edges along the path between it and the root node.
Example 1:
Input: root = [2,3,5,8,13,21,34]
Output: [2,5,3,8,13,21,34]
Explanation:
The tree has only one odd level.
The nodes at level 1 are 3, 5 respectively, which are reversed and become 5, 3.
Example 2:
Input: root = [7,13,11]
Output: [7,11,13]
Explanation:
The nodes at level 1 are 13, 11, which are reversed and become 11, 13.
Example 3:
Input: root = [0,1,2,0,0,0,0,1,1,1,1,2,2,2,2]
Output: [0,2,1,0,0,0,0,2,2,2,2,1,1,1,1]
Explanation:
The odd levels have non-zero values.
The nodes at level 1 were 1, 2, and are 2, 1 after the reversal.
The nodes at level 3 were 1, 1, 1, 1, 2, 2, 2, 2, and are 2, 2, 2, 2, 1, 1, 1, 1 after the reversal.
Constraints:
The number of nodes in the tree is in the range [1, 214].
0 <= Node.val <= 105
root is a perfect binary tree.
|
Medium
|
[
"tree",
"depth-first-search",
"breadth-first-search",
"binary-tree"
] |
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
|
[
"var reverseOddLevels = function(root) {\n \n let q = [root]\n let level = 0\n \n while(q.length) {\n const nxt = []\n for(let i = 0; i < q.length; i++) {\n const cur = q[i]\n if(cur.left) nxt.push(cur.left)\n if(cur.right) nxt.push(cur.right)\n }\n if(level % 2 === 1) {\n const arr = q.map(e => e.val)\n arr.reverse()\n for(let i = 0; i < q.length; i++) {\n q[i].val = arr[i]\n }\n }\n \n level++\n q = nxt\n }\n \n // dfs(root, 0)\n return root\n\n};"
] |
2,416 |
sum-of-prefix-scores-of-strings
|
[
"What data structure will allow you to efficiently keep track of the score of each prefix?",
"Use a Trie. Insert all the words into it, and keep a counter at each node that will tell you how many times we have visited each prefix."
] |
/**
* @param {string[]} words
* @return {number[]}
*/
var sumPrefixScores = function(words) {
};
|
You are given an array words of size n consisting of non-empty strings.
We define the score of a string word as the number of strings words[i] such that word is a prefix of words[i].
For example, if words = ["a", "ab", "abc", "cab"], then the score of "ab" is 2, since "ab" is a prefix of both "ab" and "abc".
Return an array answer of size n where answer[i] is the sum of scores of every non-empty prefix of words[i].
Note that a string is considered as a prefix of itself.
Example 1:
Input: words = ["abc","ab","bc","b"]
Output: [5,4,3,2]
Explanation: The answer for each string is the following:
- "abc" has 3 prefixes: "a", "ab", and "abc".
- There are 2 strings with the prefix "a", 2 strings with the prefix "ab", and 1 string with the prefix "abc".
The total is answer[0] = 2 + 2 + 1 = 5.
- "ab" has 2 prefixes: "a" and "ab".
- There are 2 strings with the prefix "a", and 2 strings with the prefix "ab".
The total is answer[1] = 2 + 2 = 4.
- "bc" has 2 prefixes: "b" and "bc".
- There are 2 strings with the prefix "b", and 1 string with the prefix "bc".
The total is answer[2] = 2 + 1 = 3.
- "b" has 1 prefix: "b".
- There are 2 strings with the prefix "b".
The total is answer[3] = 2.
Example 2:
Input: words = ["abcd"]
Output: [4]
Explanation:
"abcd" has 4 prefixes: "a", "ab", "abc", and "abcd".
Each prefix has a score of one, so the total is answer[0] = 1 + 1 + 1 + 1 = 4.
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 1000
words[i] consists of lowercase English letters.
|
Hard
|
[
"array",
"string",
"trie",
"counting"
] |
[
"const sumPrefixScores = function(words) {\n let trie = new Trie();\n for (let word of words) {\n trie.add(word);\n } \n\n let n = words.length, res = Array(n);\n for (let i = 0; i < words.length; i++) {\n res[i] = trie.getScore(words[i]);\n }\n return res;\n};\n\nclass TrieNode {\n constructor() {\n this.children = {};\n this.count = 0; \n }\n}\n\nclass Trie {\n constructor() {\n this.root = new TrieNode();\n }\n add(word) {\n let node = this.root;\n for (let i = 0; i < word.length; i++) {\n node = node.children;\n let char = word[i];\n if (!node[char]) node[char] = new TrieNode();\n node = node[char];\n node.count++;\n }\n }\n getScore(word) {\n let node = this.root, score = 0;\n for (let i = 0; i < word.length; i++) {\n node = node.children;\n let char = word[i];\n if (!node[char]) return score;\n node = node[char];\n score += node.count;\n }\n return score;\n }\n};"
] |
|
2,418 |
sort-the-people
|
[
"Find the tallest person and swap with the first person, then find the second tallest person and swap with the second person, etc. Repeat until you fix all n people."
] |
/**
* @param {string[]} names
* @param {number[]} heights
* @return {string[]}
*/
var sortPeople = function(names, heights) {
};
|
You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.
For each index i, names[i] and heights[i] denote the name and height of the ith person.
Return names sorted in descending order by the people's heights.
Example 1:
Input: names = ["Mary","John","Emma"], heights = [180,165,170]
Output: ["Mary","Emma","John"]
Explanation: Mary is the tallest, followed by Emma and John.
Example 2:
Input: names = ["Alice","Bob","Bob"], heights = [155,185,150]
Output: ["Bob","Alice","Bob"]
Explanation: The first Bob is the tallest, followed by Alice and the second Bob.
Constraints:
n == names.length == heights.length
1 <= n <= 103
1 <= names[i].length <= 20
1 <= heights[i] <= 105
names[i] consists of lower and upper case English letters.
All the values of heights are distinct.
|
Easy
|
[
"array",
"hash-table",
"string",
"sorting"
] |
[
"var sortPeople = function(names, heights) {\n const n = names.length\n const arr = []\n for(let i = 0; i <n; i++) {\n arr.push([names[i], heights[i]])\n }\n \n arr.sort((a, b) => a[1] - b[1])\n arr.reverse()\n return arr.map(e => e[0])\n};"
] |
|
2,419 |
longest-subarray-with-maximum-bitwise-and
|
[
"Notice that the bitwise AND of two different numbers will always be strictly less than the maximum of those two numbers.",
"What does that tell us about the nature of the subarray that we should choose?"
] |
/**
* @param {number[]} nums
* @return {number}
*/
var longestSubarray = function(nums) {
};
|
You are given an integer array nums of size n.
Consider a non-empty subarray from nums that has the maximum possible bitwise AND.
In other words, let k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should be considered.
Return the length of the longest such subarray.
The bitwise AND of an array is the bitwise AND of all the numbers in it.
A subarray is a contiguous sequence of elements within an array.
Example 1:
Input: nums = [1,2,3,3,2,2]
Output: 2
Explanation:
The maximum possible bitwise AND of a subarray is 3.
The longest subarray with that value is [3,3], so we return 2.
Example 2:
Input: nums = [1,2,3,4]
Output: 1
Explanation:
The maximum possible bitwise AND of a subarray is 4.
The longest subarray with that value is [4], so we return 1.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106
|
Medium
|
[
"array",
"bit-manipulation",
"brainteaser"
] |
[
"const longestSubarray = function(nums) {\n const max = Math.max(...nums)\n const arr = []\n for(let i = 0; i < nums.length; i++) {\n if(nums[i] === max) arr.push(i)\n }\n let res = 1, cur = 1\n for(let i = 1; i < arr.length; i++) {\n if(arr[i] - arr[i - 1] === 1) cur++\n else {\n cur = 1\n }\n \n res = Math.max(res, cur)\n }\n \n return res\n};"
] |
|
2,420 |
find-all-good-indices
|
[
"Iterate over all indices i. How do you quickly check the two conditions?",
"Precompute for each index whether the conditions are satisfied on the left and the right of the index. You can do that with two iterations, from left to right and right to left."
] |
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var goodIndices = function(nums, k) {
};
|
You are given a 0-indexed integer array nums of size n and a positive integer k.
We call an index i in the range k <= i < n - k good if the following conditions are satisfied:
The k elements that are just before the index i are in non-increasing order.
The k elements that are just after the index i are in non-decreasing order.
Return an array of all good indices sorted in increasing order.
Example 1:
Input: nums = [2,1,1,1,3,4,1], k = 2
Output: [2,3]
Explanation: There are two good indices in the array:
- Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order.
- Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order.
Note that the index 4 is not good because [4,1] is not non-decreasing.
Example 2:
Input: nums = [2,1,1,2], k = 2
Output: []
Explanation: There are no good indices in this array.
Constraints:
n == nums.length
3 <= n <= 105
1 <= nums[i] <= 106
1 <= k <= n / 2
|
Medium
|
[
"array",
"dynamic-programming",
"prefix-sum"
] |
[
"const goodIndices = function(nums, k) {\n const n = nums.length\n const pre = Array(n).fill(1), post = Array(n).fill(1)\n \n let preV = nums[0], cnt = 1\n for(let i = 1; i < n; i++) {\n if(nums[i] <= preV) cnt++\n else {\n cnt = 1\n }\n pre[i] = cnt\n preV = nums[i]\n }\n\n preV = nums[n - 1], cnt = 1\n for(let i = n - 2; i >= 0; i--) {\n if(nums[i] <= preV) cnt++\n else {\n cnt = 1\n }\n post[i] = cnt\n preV = nums[i]\n }\n // console.log(pre, post)\n \n const res = []\n \n for(let i = 1; i < n; i++) {\n if(pre[i - 1] >= k && post[i + 1] >= k) res.push(i)\n }\n \n return res\n};"
] |
|
2,421 |
number-of-good-paths
|
[
"Can you process nodes from smallest to largest value?",
"Try to build the graph from nodes with the smallest value to the largest value.",
"May union find help?"
] |
/**
* @param {number[]} vals
* @param {number[][]} edges
* @return {number}
*/
var numberOfGoodPaths = function(vals, edges) {
};
|
There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges.
You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node. 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 good path is a simple path that satisfies the following conditions:
The starting node and the ending node have the same value.
All nodes between the starting node and the ending node have values less than or equal to the starting node (i.e. the starting node's value should be the maximum value along the path).
Return the number of distinct good paths.
Note that a path and its reverse are counted as the same path. For example, 0 -> 1 is considered to be the same as 1 -> 0. A single node is also considered as a valid path.
Example 1:
Input: vals = [1,3,2,1,3], edges = [[0,1],[0,2],[2,3],[2,4]]
Output: 6
Explanation: There are 5 good paths consisting of a single node.
There is 1 additional good path: 1 -> 0 -> 2 -> 4.
(The reverse path 4 -> 2 -> 0 -> 1 is treated as the same as 1 -> 0 -> 2 -> 4.)
Note that 0 -> 2 -> 3 is not a good path because vals[2] > vals[0].
Example 2:
Input: vals = [1,1,2,2,3], edges = [[0,1],[1,2],[2,3],[2,4]]
Output: 7
Explanation: There are 5 good paths consisting of a single node.
There are 2 additional good paths: 0 -> 1 and 2 -> 3.
Example 3:
Input: vals = [1], edges = []
Output: 1
Explanation: The tree consists of only one node, so there is one good path.
Constraints:
n == vals.length
1 <= n <= 3 * 104
0 <= vals[i] <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree.
|
Hard
|
[
"array",
"tree",
"union-find",
"graph"
] |
[
"const numberOfGoodPaths = function (vals, edges) {\n const n = vals.length\n let res = 0\n const adj = Array.from({ length: n }, () => [])\n const sameValues = new Map()\n const valWithIdx = vals.map((v, i) => [v, i])\n valWithIdx.sort((a, b) => a[0] - b[0])\n for (let i = 0; i < n; i++) {\n const [val, idx] = valWithIdx[i]\n if (sameValues.get(val) == null) sameValues.set(val, [])\n sameValues.get(val).push(idx)\n }\n for (const e of edges) {\n const [u, v] = e\n if (vals[u] >= vals[v]) {\n adj[u].push(v)\n } else if (vals[v] >= vals[u]) {\n adj[v].push(u)\n }\n }\n const uf = new UF(n)\n for (const [_, allNodes] of sameValues) {\n for (let u of allNodes) {\n for (const v of adj[u]) {\n uf.union(u, v)\n }\n }\n const group = {}\n for (let u of allNodes) {\n const uroot = uf.find(u)\n if (group[uroot] == null) group[uroot] = 0\n group[uroot]++\n }\n res += allNodes.length\n for (let [_, size] of Object.entries(group)) {\n res += (size * (size - 1)) / 2\n }\n }\n return res\n}\nclass UF {\n constructor(n) {\n this.root = Array(n)\n .fill(null)\n .map((_, i) => i)\n }\n find(x) {\n if (this.root[x] !== x) {\n this.root[x] = this.find(this.root[x])\n }\n return this.root[x]\n }\n union(x, y) {\n const xr = this.find(x)\n const yr = this.find(y)\n this.root[yr] = xr\n }\n}"
] |
|
2,423 |
remove-letter-to-equalize-frequency
|
[
"Brute force all letters that could be removed.",
"Use a frequency array of size 26."
] |
/**
* @param {string} word
* @return {boolean}
*/
var equalFrequency = function(word) {
};
|
You are given a 0-indexed string word, consisting of lowercase English letters. You need to select one index and remove the letter at that index from word so that the frequency of every letter present in word is equal.
Return true if it is possible to remove one letter so that the frequency of all letters in word are equal, and false otherwise.
Note:
The frequency of a letter x is the number of times it occurs in the string.
You must remove exactly one letter and cannot chose to do nothing.
Example 1:
Input: word = "abcc"
Output: true
Explanation: Select index 3 and delete it: word becomes "abc" and each character has a frequency of 1.
Example 2:
Input: word = "aazz"
Output: false
Explanation: We must delete a character, so either the frequency of "a" is 1 and the frequency of "z" is 2, or vice versa. It is impossible to make all present letters have equal frequency.
Constraints:
2 <= word.length <= 100
word consists of lowercase English letters only.
|
Easy
|
[
"hash-table",
"string",
"counting"
] |
[
"const equalFrequency = function (word) {\n const cnt = {}\n for(const ch of word) {\n if(cnt[ch] == null) cnt[ch] = 0\n cnt[ch]++\n }\n\n for(const ch of word) {\n cnt[ch]--\n if(cnt[ch] === 0) delete cnt[ch]\n const s = new Set([...Object.values(cnt)])\n if(s.size === 1) return true\n\n if(cnt[ch] == null) cnt[ch] = 0\n cnt[ch]++ \n }\n\n return false\n}"
] |
|
2,424 |
longest-uploaded-prefix
|
[
"Maintain an array keeping track of whether video “i” has been uploaded yet."
] |
/**
* @param {number} n
*/
var LUPrefix = function(n) {
};
/**
* @param {number} video
* @return {void}
*/
LUPrefix.prototype.upload = function(video) {
};
/**
* @return {number}
*/
LUPrefix.prototype.longest = function() {
};
/**
* Your LUPrefix object will be instantiated and called as such:
* var obj = new LUPrefix(n)
* obj.upload(video)
* var param_2 = obj.longest()
*/
|
You are given a stream of n videos, each represented by a distinct number from 1 to n that you need to "upload" to a server. You need to implement a data structure that calculates the length of the longest uploaded prefix at various points in the upload process.
We consider i to be an uploaded prefix if all videos in the range 1 to i (inclusive) have been uploaded to the server. The longest uploaded prefix is the maximum value of i that satisfies this definition.
Implement the LUPrefix class:
LUPrefix(int n) Initializes the object for a stream of n videos.
void upload(int video) Uploads video to the server.
int longest() Returns the length of the longest uploaded prefix defined above.
Example 1:
Input
["LUPrefix", "upload", "longest", "upload", "longest", "upload", "longest"]
[[4], [3], [], [1], [], [2], []]
Output
[null, null, 0, null, 1, null, 3]
Explanation
LUPrefix server = new LUPrefix(4); // Initialize a stream of 4 videos.
server.upload(3); // Upload video 3.
server.longest(); // Since video 1 has not been uploaded yet, there is no prefix.
// So, we return 0.
server.upload(1); // Upload video 1.
server.longest(); // The prefix [1] is the longest uploaded prefix, so we return 1.
server.upload(2); // Upload video 2.
server.longest(); // The prefix [1,2,3] is the longest uploaded prefix, so we return 3.
Constraints:
1 <= n <= 105
1 <= video <= n
All values of video are distinct.
At most 2 * 105 calls in total will be made to upload and longest.
At least one call will be made to longest.
|
Medium
|
[
"binary-search",
"union-find",
"design",
"binary-indexed-tree",
"segment-tree",
"heap-priority-queue",
"ordered-set"
] | null |
[] |
2,425 |
bitwise-xor-of-all-pairings
|
[
"Think how the count of each individual integer affects the final answer.",
"If the length of nums1 is m and the length of nums2 is n, then each number in nums1 is repeated n times and each number in nums2 is repeated m times."
] |
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var xorAllNums = function(nums1, nums2) {
};
|
You are given two 0-indexed arrays, nums1 and nums2, consisting of non-negative integers. There exists another array, nums3, which contains the bitwise XOR of all pairings of integers between nums1 and nums2 (every integer in nums1 is paired with every integer in nums2 exactly once).
Return the bitwise XOR of all integers in nums3.
Example 1:
Input: nums1 = [2,1,3], nums2 = [10,2,5,0]
Output: 13
Explanation:
A possible nums3 array is [8,0,7,2,11,3,4,1,9,1,6,3].
The bitwise XOR of all these numbers is 13, so we return 13.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 0
Explanation:
All possible pairs of bitwise XORs are nums1[0] ^ nums2[0], nums1[0] ^ nums2[1], nums1[1] ^ nums2[0],
and nums1[1] ^ nums2[1].
Thus, one possible nums3 array is [2,5,1,6].
2 ^ 5 ^ 1 ^ 6 = 0, so we return 0.
Constraints:
1 <= nums1.length, nums2.length <= 105
0 <= nums1[i], nums2[j] <= 109
|
Medium
|
[
"array",
"bit-manipulation",
"brainteaser"
] | null |
[] |
2,426 |
number-of-pairs-satisfying-inequality
|
[
"Try rearranging the equation.",
"Once the equation is rearranged properly, think how a segment tree or a Fenwick tree can be used to solve the rearranged equation.",
"Iterate through the array backwards."
] |
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number} diff
* @return {number}
*/
var numberOfPairs = function(nums1, nums2, diff) {
};
|
You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an integer diff. Find the number of pairs (i, j) such that:
0 <= i < j <= n - 1 and
nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff.
Return the number of pairs that satisfy the conditions.
Example 1:
Input: nums1 = [3,2,5], nums2 = [2,2,1], diff = 1
Output: 3
Explanation:
There are 3 pairs that satisfy the conditions:
1. i = 0, j = 1: 3 - 2 <= 2 - 2 + 1. Since i < j and 1 <= 1, this pair satisfies the conditions.
2. i = 0, j = 2: 3 - 5 <= 2 - 1 + 1. Since i < j and -2 <= 2, this pair satisfies the conditions.
3. i = 1, j = 2: 2 - 5 <= 2 - 1 + 1. Since i < j and -3 <= 2, this pair satisfies the conditions.
Therefore, we return 3.
Example 2:
Input: nums1 = [3,-1], nums2 = [-2,2], diff = -1
Output: 0
Explanation:
Since there does not exist any pair that satisfies the conditions, we return 0.
Constraints:
n == nums1.length == nums2.length
2 <= n <= 105
-104 <= nums1[i], nums2[i] <= 104
-104 <= diff <= 104
|
Hard
|
[
"array",
"binary-search",
"divide-and-conquer",
"binary-indexed-tree",
"segment-tree",
"merge-sort",
"ordered-set"
] |
[
"const numberOfPairs = function (nums1, nums2, diff) {\n const n = nums1.length, limit = 6 * 1e4, add = 3 * 1e4\n const bit = new BIT(limit)\n\n let res = 0\n for(let j = 0; j < n; j++) {\n const d = nums1[j] - nums2[j] + add\n res += bit.query(d + diff)\n bit.update(d, 1)\n }\n\n return res\n}\n\nfunction lowBit(x) {\n return x & -x\n}\nclass BIT {\n constructor(n) {\n this.arr = Array(n + 1).fill(0)\n }\n\n update(i, delta) {\n if(i < 1) return\n while (i < this.arr.length) {\n this.arr[i] += delta\n i += lowBit(i)\n }\n }\n\n query(i) {\n let res = 0\n if(i < 1) return res\n while (i > 0) {\n res += this.arr[i]\n i -= lowBit(i)\n }\n return res\n }\n}"
] |
|
2,427 |
number-of-common-factors
|
[
"For each integer in range [1,1000], check if it’s divisible by both A and B."
] |
/**
* @param {number} a
* @param {number} b
* @return {number}
*/
var commonFactors = function(a, b) {
};
|
Given two positive integers a and b, return the number of common factors of a and b.
An integer x is a common factor of a and b if x divides both a and b.
Example 1:
Input: a = 12, b = 6
Output: 4
Explanation: The common factors of 12 and 6 are 1, 2, 3, 6.
Example 2:
Input: a = 25, b = 30
Output: 2
Explanation: The common factors of 25 and 30 are 1, 5.
Constraints:
1 <= a, b <= 1000
|
Easy
|
[
"math",
"enumeration",
"number-theory"
] |
[
"var commonFactors = function(a, b) {\n let res = 0\n const r = Math.max(a, b)\n for(let i = 1; i <= r; i++) {\n if(a % i === 0 && b % i === 0) res++\n }\n \n return res\n};"
] |
|
2,428 |
maximum-sum-of-an-hourglass
|
[
"Each 3x3 submatrix has exactly one hourglass.",
"Find the sum of each hourglass in the matrix and return the largest of these values."
] |
/**
* @param {number[][]} grid
* @return {number}
*/
var maxSum = function(grid) {
};
|
You are given an m x n integer matrix grid.
We define an hourglass as a part of the matrix with the following form:
Return the maximum sum of the elements of an hourglass.
Note that an hourglass cannot be rotated and must be entirely contained within the matrix.
Example 1:
Input: grid = [[6,2,1,3],[4,2,1,5],[9,2,8,7],[4,1,2,9]]
Output: 30
Explanation: The cells shown above represent the hourglass with the maximum sum: 6 + 2 + 1 + 2 + 9 + 2 + 8 = 30.
Example 2:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: 35
Explanation: There is only one hourglass in the matrix, with the sum: 1 + 2 + 3 + 5 + 7 + 8 + 9 = 35.
Constraints:
m == grid.length
n == grid[i].length
3 <= m, n <= 150
0 <= grid[i][j] <= 106
|
Medium
|
[
"array",
"matrix",
"prefix-sum"
] |
[
"var maxSum = function(grid) {\n let res = 0 \n const m = grid.length, n = grid[0].length\n \n for(let i = 0; i < m - 2; i++) {\n for(let j = 0; j < n - 2; j++) {\n res = Math.max(res, helper(i, j))\n }\n }\n \n return res\n \n function helper(i, j) {\n let sum = 0\n for(let r = i; r < i + 3; r++) {\n for(let c = j; c < j + 3; c++) {\n sum += grid[r][c]\n }\n }\n sum -= grid[i + 1][j]\n sum -= grid[i + 1][j + 2]\n // console.log(sum)\n \n return sum\n }\n};"
] |
|
2,429 |
minimize-xor
|
[
"To arrive at a small xor, try to turn off some bits from num1",
"If there are still left bits to set, try to set them from the least significant bit"
] |
/**
* @param {number} num1
* @param {number} num2
* @return {number}
*/
var minimizeXor = function(num1, num2) {
};
|
Given two positive integers num1 and num2, find the positive integer x such that:
x has the same number of set bits as num2, and
The value x XOR num1 is minimal.
Note that XOR is the bitwise XOR operation.
Return the integer x. The test cases are generated such that x is uniquely determined.
The number of set bits of an integer is the number of 1's in its binary representation.
Example 1:
Input: num1 = 3, num2 = 5
Output: 3
Explanation:
The binary representations of num1 and num2 are 0011 and 0101, respectively.
The integer 3 has the same number of set bits as num2, and the value 3 XOR 3 = 0 is minimal.
Example 2:
Input: num1 = 1, num2 = 12
Output: 3
Explanation:
The binary representations of num1 and num2 are 0001 and 1100, respectively.
The integer 3 has the same number of set bits as num2, and the value 3 XOR 1 = 2 is minimal.
Constraints:
1 <= num1, num2 <= 109
|
Medium
|
[
"greedy",
"bit-manipulation"
] |
[
"const minimizeXor = function(num1, num2) {\n let num = 0\n let n2 = num2\n while(n2 > 0) {\n if(n2 & 1 === 1) num++\n n2 = n2 >>> 1\n }\n \n let arr1 = num1.toString(2).split('').map(e => +e)\n // console.log(arr1)\n let res = Array(arr1.length).fill(0)\n for(let i = 0; i < arr1.length && num > 0; i++) {\n if(arr1[i] === 1) {\n num--\n res[i] = 1\n }\n }\n \n for(let i = arr1.length - 1; i >= 0 && num > 0; i--) {\n if(arr1[i] === 0) {\n num--\n res[i] = 1\n }\n }\n \n while(num) {\n res.unshift(1)\n num--\n }\n \n return Number.parseInt(res.join(''), 2)\n};"
] |
|
2,430 |
maximum-deletions-on-a-string
|
[
"We can use dynamic programming to find the answer. Create a 0-indexed dp array where dp[i] represents the maximum number of moves needed to remove the first i + 1 letters from s.",
"What should we do if there is an i where it is impossible to remove the first i + 1 letters?",
"Use a sentinel value such as -1 to show that it is impossible.",
"How can we quickly determine if two substrings of s are equal? We can use hashing."
] |
/**
* @param {string} s
* @return {number}
*/
var deleteString = function(s) {
};
|
You are given a string s consisting of only lowercase English letters. In one operation, you can:
Delete the entire string s, or
Delete the first i letters of s if the first i letters of s are equal to the following i letters in s, for any i in the range 1 <= i <= s.length / 2.
For example, if s = "ababc", then in one operation, you could delete the first two letters of s to get "abc", since the first two letters of s and the following two letters of s are both equal to "ab".
Return the maximum number of operations needed to delete all of s.
Example 1:
Input: s = "abcabcdabc"
Output: 2
Explanation:
- Delete the first 3 letters ("abc") since the next 3 letters are equal. Now, s = "abcdabc".
- Delete all the letters.
We used 2 operations so return 2. It can be proven that 2 is the maximum number of operations needed.
Note that in the second operation we cannot delete "abc" again because the next occurrence of "abc" does not happen in the next 3 letters.
Example 2:
Input: s = "aaabaab"
Output: 4
Explanation:
- Delete the first letter ("a") since the next letter is equal. Now, s = "aabaab".
- Delete the first 3 letters ("aab") since the next 3 letters are equal. Now, s = "aab".
- Delete the first letter ("a") since the next letter is equal. Now, s = "ab".
- Delete all the letters.
We used 4 operations so return 4. It can be proven that 4 is the maximum number of operations needed.
Example 3:
Input: s = "aaaaa"
Output: 5
Explanation: In each operation, we can delete the first letter of s.
Constraints:
1 <= s.length <= 4000
s consists only of lowercase English letters.
|
Hard
|
[
"string",
"dynamic-programming",
"rolling-hash",
"string-matching",
"hash-function"
] |
[
"const deleteString = function (s) {\n const dp = Array(4000).fill(0)\n const n = s.length\n return helper(0)\n \n function helper(i) {\n if(dp[i] === 0) {\n dp[i] = 1\n for(let len = 1; dp[i] <= n - i - len; len++) {\n if(s.slice(i, i + len) === s.slice(i + len, i + 2 * len)) {\n dp[i] = Math.max(dp[i], 1 + helper(i + len)) \n }\n }\n }\n return dp[i]\n }\n}",
"const deleteString = function (s) {\n const dp = Array(4000).fill(0), lps = Array(4000).fill(0)\n for (let k = s.length - 1; k >= 0; --k) {\n dp[k] = 1; \n for (let i = 1, j = 0; dp[k] <= s.length - i - k + 1; ++i) {\n while (j && s[i + k] != s[j + k]) j = Math.max(0, lps[j] - 1);\n j += s[i + k] == s[j + k];\n lps[i] = j;\n if (i % 2) {\n const len = ~~((i + 1) / 2);\n if (lps[len * 2 - 1] == len) {\n dp[k] = Math.max(dp[k], 1 + dp[k + len]);\n }\n }\n }\n }\n return dp[0];\n}",
"const deleteString = function (t) {\n let n = t.length\n const set = new Set(t.split(''))\n if (set.size == 1) return n\n\n let s = t.split('')\n if (n === 1 || (n === 2 && s[0] !== s[1])) return 1\n if (n === 2 && s[0] === s[1]) return 2\n if (n === 3 && s[0] === s[1]) return s[1] === s[2] ? 3 : 2\n else if (n === 3) return 1\n const f = new Array(n).fill(null)\n dfsSearchWithMemory(0)\n return f[0]\n\n function dfsSearchWithMemory(i) {\n if (i >= n) return 0\n if (f[i] !== null) return f[i]\n if (i === n - 1) return (f[i] = 1)\n let max = 0,\n cur = 0,\n j = i + 1\n for (j = i + 1; j <= ~~((n - i) / 2 + i); j++) {\n if (t.slice(j).startsWith(t.slice(i, j))) {\n cur = 1 + dfsSearchWithMemory(j)\n if (cur > max) max = cur\n }\n }\n if (j > (n - i) / 2 + i && max === 0) return (f[i] = 1)\n return (f[i] = max)\n }\n}"
] |
|
2,432 |
the-employee-that-worked-on-the-longest-task
|
[
"Find the time of the longest task",
"Store each employee’s longest task time in a hash table",
"For employees that have the same longest task time, we only need the employee with the smallest ID"
] |
/**
* @param {number} n
* @param {number[][]} logs
* @return {number}
*/
var hardestWorker = function(n, logs) {
};
|
There are n employees, each with a unique id from 0 to n - 1.
You are given a 2D integer array logs where logs[i] = [idi, leaveTimei] where:
idi is the id of the employee that worked on the ith task, and
leaveTimei is the time at which the employee finished the ith task. All the values leaveTimei are unique.
Note that the ith task starts the moment right after the (i - 1)th task ends, and the 0th task starts at time 0.
Return the id of the employee that worked the task with the longest time. If there is a tie between two or more employees, return the smallest id among them.
Example 1:
Input: n = 10, logs = [[0,3],[2,5],[0,9],[1,15]]
Output: 1
Explanation:
Task 0 started at 0 and ended at 3 with 3 units of times.
Task 1 started at 3 and ended at 5 with 2 units of times.
Task 2 started at 5 and ended at 9 with 4 units of times.
Task 3 started at 9 and ended at 15 with 6 units of times.
The task with the longest time is task 3 and the employee with id 1 is the one that worked on it, so we return 1.
Example 2:
Input: n = 26, logs = [[1,1],[3,7],[2,12],[7,17]]
Output: 3
Explanation:
Task 0 started at 0 and ended at 1 with 1 unit of times.
Task 1 started at 1 and ended at 7 with 6 units of times.
Task 2 started at 7 and ended at 12 with 5 units of times.
Task 3 started at 12 and ended at 17 with 5 units of times.
The tasks with the longest time is task 1. The employee that worked on it is 3, so we return 3.
Example 3:
Input: n = 2, logs = [[0,10],[1,20]]
Output: 0
Explanation:
Task 0 started at 0 and ended at 10 with 10 units of times.
Task 1 started at 10 and ended at 20 with 10 units of times.
The tasks with the longest time are tasks 0 and 1. The employees that worked on them are 0 and 1, so we return the smallest id 0.
Constraints:
2 <= n <= 500
1 <= logs.length <= 500
logs[i].length == 2
0 <= idi <= n - 1
1 <= leaveTimei <= 500
idi != idi+1
leaveTimei are sorted in a strictly increasing order.
|
Easy
|
[
"array"
] |
[
"var hardestWorker = function(n, logs) {\n const arr = Array(n).fill(0)\n const m = logs.length\n let pre = 0\n for(let i = 0; i < m; i++) {\n const [id, leave] = logs[i]\n arr[id] = Math.max(arr[id], leave - pre)\n pre = leave\n }\n // console.log(arr)\n const max = Math.max(...arr)\n \n return arr.indexOf(max)\n};"
] |
|
2,433 |
find-the-original-array-of-prefix-xor
|
[
"Consider the following equation: x ^ a = b. How can you find x?",
"Notice that arr[i] ^ pref[i-1] = pref[i]. This is the same as the previous equation."
] |
/**
* @param {number[]} pref
* @return {number[]}
*/
var findArray = function(pref) {
};
|
You are given an integer array pref of size n. Find and return the array arr of size n that satisfies:
pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].
Note that ^ denotes the bitwise-xor operation.
It can be proven that the answer is unique.
Example 1:
Input: pref = [5,2,0,3,1]
Output: [5,7,2,3,2]
Explanation: From the array [5,7,2,3,2] we have the following:
- pref[0] = 5.
- pref[1] = 5 ^ 7 = 2.
- pref[2] = 5 ^ 7 ^ 2 = 0.
- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3.
- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1.
Example 2:
Input: pref = [13]
Output: [13]
Explanation: We have pref[0] = arr[0] = 13.
Constraints:
1 <= pref.length <= 105
0 <= pref[i] <= 106
|
Medium
|
[
"array",
"bit-manipulation"
] |
[
"const findArray = function(pref) {\n const n = pref.length\n if(n == 0 || n==1) return pref\n const res = [pref[0]]\n let xor = pref[0]\n for(let i = 1; i < n; i++) {\n const v = pref[i]\n // v = xor ^ e\n // v ^ xor = e\n const tmp = v ^ xor\n res.push(tmp)\n xor = xor ^ tmp\n }\n \n return res\n};"
] |
|
2,434 |
using-a-robot-to-print-the-lexicographically-smallest-string
|
[
"If there are some character “a” ’ s in the string, they can be written on paper before anything else.",
"Every character in the string before the last “a” should be written in reversed order.",
"After the robot writes every “a” on paper, the same holds for other characters “b”, ”c”, …etc."
] |
/**
* @param {string} s
* @return {string}
*/
var robotWithString = function(s) {
};
|
You are given a string s and a robot that currently holds an empty string t. Apply one of the following operations until s and t are both empty:
Remove the first character of a string s and give it to the robot. The robot will append this character to the string t.
Remove the last character of a string t and give it to the robot. The robot will write this character on paper.
Return the lexicographically smallest string that can be written on the paper.
Example 1:
Input: s = "zza"
Output: "azz"
Explanation: Let p denote the written string.
Initially p="", s="zza", t="".
Perform first operation three times p="", s="", t="zza".
Perform second operation three times p="azz", s="", t="".
Example 2:
Input: s = "bac"
Output: "abc"
Explanation: Let p denote the written string.
Perform first operation twice p="", s="c", t="ba".
Perform second operation twice p="ab", s="c", t="".
Perform first operation p="ab", s="", t="c".
Perform second operation p="abc", s="", t="".
Example 3:
Input: s = "bdda"
Output: "addb"
Explanation: Let p denote the written string.
Initially p="", s="bdda", t="".
Perform first operation four times p="", s="", t="bdda".
Perform second operation four times p="addb", s="", t="".
Constraints:
1 <= s.length <= 105
s consists of only English lowercase letters.
|
Medium
|
[
"hash-table",
"string",
"stack",
"greedy"
] |
[
"const robotWithString = function (s) {\n const stk = []\n const freq = Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n for (const ch of s) {\n freq[ch.charCodeAt(0) - a]++\n }\n\n let res = ''\n\n for (const ch of s) {\n stk.push(ch)\n freq[ch.charCodeAt(0) - a]--\n while (stk.length && stk[stk.length - 1] <= helper(freq)) {\n const e = stk.pop()\n res += e\n }\n }\n\n while (stk.length) {\n res += stk.pop()\n }\n\n return res\n\n function helper(arr) {\n const a = 'a'.charCodeAt(0)\n for (let i = 0; i < 26; i++) {\n if (arr[i] !== 0) return String.fromCharCode(a + i)\n }\n\n return ''\n }\n}",
"const ord = (c) => c.charCodeAt();\nconst char = (ascii) => String.fromCharCode(ascii);\n\n\nconst robotWithString = (s) => {\n let f = Array(26).fill(0), t = [], res = '';\n for (const c of s) f[ord(c) - 97]++;\n for (const c of s) {\n f[ord(c) - 97]--;\n t.push(c);\n while (t.length) {\n let find = false;\n for (let i = 0; i < 26; i++) {\n let curC = char(i + 97);\n if (curC < t[t.length - 1]) { // check if can find smaller char < t's last char, in the rest of S\n if (f[i] > 0) {\n find = true;\n break;\n }\n }\n }\n if (find) { // find means there is lexical smaller one, by moving much more right\n break;\n } else { // not find, current is lexical smaller\n res += t.pop();\n }\n }\n }\n return res;\n};"
] |
|
2,435 |
paths-in-matrix-whose-sum-is-divisible-by-k
|
[
"The actual numbers in grid do not matter. What matters are the remainders you get when you divide the numbers by k.",
"We can use dynamic programming to solve this problem. What can we use as states?",
"Let dp[i][j][value] represent the number of paths where the sum of the elements on the path has a remainder of value when divided by k."
] |
/**
* @param {number[][]} grid
* @param {number} k
* @return {number}
*/
var numberOfPaths = function(grid, k) {
};
|
You are given a 0-indexed m x n integer matrix grid and an integer k. You are currently at position (0, 0) and you want to reach position (m - 1, n - 1) moving only down or right.
Return the number of paths where the sum of the elements on the path is divisible by k. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: grid = [[5,2,4],[3,0,5],[0,7,2]], k = 3
Output: 2
Explanation: There are two paths where the sum of the elements on the path is divisible by k.
The first path highlighted in red has a sum of 5 + 2 + 4 + 5 + 2 = 18 which is divisible by 3.
The second path highlighted in blue has a sum of 5 + 3 + 0 + 5 + 2 = 15 which is divisible by 3.
Example 2:
Input: grid = [[0,0]], k = 5
Output: 1
Explanation: The path highlighted in red has a sum of 0 + 0 = 0 which is divisible by 5.
Example 3:
Input: grid = [[7,3,4,9],[2,3,6,2],[2,3,7,0]], k = 1
Output: 10
Explanation: Every integer is divisible by 1 so the sum of the elements on every possible path is divisible by k.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 5 * 104
1 <= m * n <= 5 * 104
0 <= grid[i][j] <= 100
1 <= k <= 50
|
Hard
|
[
"array",
"dynamic-programming",
"matrix"
] |
[
"const initialize3DArray = (n, m, p) => { let r = []; for (let i = 0; i < n; i++) { let d = []; for (let j = 0; j < m; j++) { let t = Array(p).fill(0); d.push(t); } r.push(d); } return r; };\n\nconst mod = 1e9 + 7;\n\nconst numberOfPaths = (grid, k) => {\n const g = grid, K = k\n let n = g.length, m = g[0].length, dp = initialize3DArray(n + 1, m + 1, K);\n dp[0][1][0] = 1;\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n for (let k = 0; k < K; k++) {\n dp[i + 1][j + 1][(k + g[i][j]) % K] += dp[i][j + 1][k];\n dp[i + 1][j + 1][(k + g[i][j]) % K] %= mod;\n dp[i + 1][j + 1][(k + g[i][j]) % K] += dp[i + 1][j][k];\n dp[i + 1][j + 1][(k + g[i][j]) % K] %= mod;\n }\n }\n }\n return dp[n][m][0];\n};"
] |
|
2,437 |
number-of-valid-clock-times
|
[
"Brute force all possible clock times.",
"Checking if a clock time is valid can be done with Regex."
] |
/**
* @param {string} time
* @return {number}
*/
var countTime = function(time) {
};
|
You are given a string of length 5 called time, representing the current time on a digital clock in the format "hh:mm". The earliest possible time is "00:00" and the latest possible time is "23:59".
In the string time, the digits represented by the ? symbol are unknown, and must be replaced with a digit from 0 to 9.
Return an integer answer, the number of valid clock times that can be created by replacing every ? with a digit from 0 to 9.
Example 1:
Input: time = "?5:00"
Output: 2
Explanation: We can replace the ? with either a 0 or 1, producing "05:00" or "15:00". Note that we cannot replace it with a 2, since the time "25:00" is invalid. In total, we have two choices.
Example 2:
Input: time = "0?:0?"
Output: 100
Explanation: Each ? can be replaced by any digit from 0 to 9, so we have 100 total choices.
Example 3:
Input: time = "??:??"
Output: 1440
Explanation: There are 24 possible choices for the hours, and 60 possible choices for the minutes. In total, we have 24 * 60 = 1440 choices.
Constraints:
time is a valid string of length 5 in the format "hh:mm".
"00" <= hh <= "23"
"00" <= mm <= "59"
Some of the digits might be replaced with '?' and need to be replaced with digits from 0 to 9.
|
Easy
|
[
"string",
"enumeration"
] | null |
[] |
2,438 |
range-product-queries-of-powers
|
[
"The <code>powers</code> array can be created using the binary representation of <code>n</code>.",
"Once <code>powers</code> is formed, the products can be taken using brute force."
] |
/**
* @param {number} n
* @param {number[][]} queries
* @return {number[]}
*/
var productQueries = function(n, queries) {
};
|
Given a positive integer n, there exists a 0-indexed array called powers, composed of the minimum number of powers of 2 that sum to n. The array is sorted in non-decreasing order, and there is only one way to form the array.
You are also given a 0-indexed 2D integer array queries, where queries[i] = [lefti, righti]. Each queries[i] represents a query where you have to find the product of all powers[j] with lefti <= j <= righti.
Return an array answers, equal in length to queries, where answers[i] is the answer to the ith query. Since the answer to the ith query may be too large, each answers[i] should be returned modulo 109 + 7.
Example 1:
Input: n = 15, queries = [[0,1],[2,2],[0,3]]
Output: [2,4,64]
Explanation:
For n = 15, powers = [1,2,4,8]. It can be shown that powers cannot be a smaller size.
Answer to 1st query: powers[0] * powers[1] = 1 * 2 = 2.
Answer to 2nd query: powers[2] = 4.
Answer to 3rd query: powers[0] * powers[1] * powers[2] * powers[3] = 1 * 2 * 4 * 8 = 64.
Each answer modulo 109 + 7 yields the same answer, so [2,4,64] is returned.
Example 2:
Input: n = 2, queries = [[0,0]]
Output: [2]
Explanation:
For n = 2, powers = [2].
The answer to the only query is powers[0] = 2. The answer modulo 109 + 7 is the same, so [2] is returned.
Constraints:
1 <= n <= 109
1 <= queries.length <= 105
0 <= starti <= endi < powers.length
|
Medium
|
[
"array",
"bit-manipulation",
"prefix-sum"
] |
[
"const productQueries = function(n, queries) {\n const mod = 1e9 + 7\n const powers = []\n let pow = 1\n while(n) {\n const tmp = (n & 1) * pow\n if(tmp) powers.push(tmp)\n n = n >> 1\n pow *= 2\n }\n\n // console.log(powers)\n const res = []\n \n for(const [s, e] of queries) {\n let tmp = 1\n for(let i = s; i <= e; i++) {\n tmp = (tmp * powers[i]) % mod\n }\n res.push(tmp)\n }\n \n return res\n};"
] |
|
2,439 |
minimize-maximum-of-array
|
[
"Try a binary search approach.",
"Perform a binary search over the minimum value that can be achieved for the maximum number of the array.",
"In each binary search iteration, iterate through the array backwards, greedily decreasing the current element until it is within the limit."
] |
/**
* @param {number[]} nums
* @return {number}
*/
var minimizeArrayValue = function(nums) {
};
|
You are given a 0-indexed array nums comprising of n non-negative integers.
In one operation, you must:
Choose an integer i such that 1 <= i < n and nums[i] > 0.
Decrease nums[i] by 1.
Increase nums[i - 1] by 1.
Return the minimum possible value of the maximum integer of nums after performing any number of operations.
Example 1:
Input: nums = [3,7,1,6]
Output: 5
Explanation:
One set of optimal operations is as follows:
1. Choose i = 1, and nums becomes [4,6,1,6].
2. Choose i = 3, and nums becomes [4,6,2,5].
3. Choose i = 1, and nums becomes [5,5,2,5].
The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.
Therefore, we return 5.
Example 2:
Input: nums = [10,1]
Output: 10
Explanation:
It is optimal to leave nums as is, and since 10 is the maximum value, we return 10.
Constraints:
n == nums.length
2 <= n <= 105
0 <= nums[i] <= 109
|
Medium
|
[
"array",
"binary-search",
"dynamic-programming",
"greedy",
"prefix-sum"
] |
[
"const minimizeArrayValue = function(nums) {\n const n = nums.length\n let sum = 0, res = 0;\n for (let i = 0; i < n; ++i) {\n sum += nums[i];\n res = Math.max(res, Math.ceil(sum / (i + 1)));\n }\n return res;\n};"
] |
|
2,440 |
create-components-with-same-value
|
[
"Consider all divisors of the sum of values."
] |
/**
* @param {number[]} nums
* @param {number[][]} edges
* @return {number}
*/
var componentValue = function(nums, edges) {
};
|
There is an undirected tree with n nodes labeled from 0 to n - 1.
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.
You are allowed to delete some edges, splitting the tree into multiple connected components. Let the value of a component be the sum of all nums[i] for which node i is in the component.
Return the maximum number of edges you can delete, such that every connected component in the tree has the same value.
Example 1:
Input: nums = [6,2,2,2,6], edges = [[0,1],[1,2],[1,3],[3,4]]
Output: 2
Explanation: The above figure shows how we can delete the edges [0,1] and [3,4]. The created components are nodes [0], [1,2,3] and [4]. The sum of the values in each component equals 6. It can be proven that no better deletion exists, so the answer is 2.
Example 2:
Input: nums = [2], edges = []
Output: 0
Explanation: There are no edges to be deleted.
Constraints:
1 <= n <= 2 * 104
nums.length == n
1 <= nums[i] <= 50
edges.length == n - 1
edges[i].length == 2
0 <= edges[i][0], edges[i][1] <= n - 1
edges represents a valid tree.
|
Hard
|
[
"array",
"math",
"tree",
"depth-first-search",
"enumeration"
] | null |
[] |
2,441 |
largest-positive-integer-that-exists-with-its-negative
|
[
"What data structure can help you to determine if an element exists?",
"Would a hash table help?"
] |
/**
* @param {number[]} nums
* @return {number}
*/
var findMaxK = function(nums) {
};
|
Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array.
Return the positive integer k. If there is no such integer, return -1.
Example 1:
Input: nums = [-1,2,-3,3]
Output: 3
Explanation: 3 is the only valid k we can find in the array.
Example 2:
Input: nums = [-1,10,6,7,-7,1]
Output: 7
Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.
Example 3:
Input: nums = [-10,8,6,7,-2,-3]
Output: -1
Explanation: There is no a single valid k, we return -1.
Constraints:
1 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
nums[i] != 0
|
Easy
|
[
"array",
"hash-table",
"two-pointers",
"sorting"
] |
[
"var findMaxK = function(nums) {\n nums.sort((a, b) => a - b)\n const n = nums.length\n for(let i = n - 1; i > 0; i--) {\n const cur = nums[i]\n if(nums.indexOf(-cur) !== -1) return cur\n }\n return -1\n};"
] |
|
2,442 |
count-number-of-distinct-integers-after-reverse-operations
|
[
"What data structure allows us to insert numbers and find the number of distinct numbers in it?",
"Try using a set, insert all the numbers and their reverse into it, and return its size."
] |
/**
* @param {number[]} nums
* @return {number}
*/
var countDistinctIntegers = function(nums) {
};
|
You are given an array nums consisting of positive integers.
You have to take each integer in the array, reverse its digits, and add it to the end of the array. You should apply this operation to the original integers in nums.
Return the number of distinct integers in the final array.
Example 1:
Input: nums = [1,13,10,12,31]
Output: 6
Explanation: After including the reverse of each number, the resulting array is [1,13,10,12,31,1,31,1,21,13].
The reversed integers that were added to the end of the array are underlined. Note that for the integer 10, after reversing it, it becomes 01 which is just 1.
The number of distinct integers in this array is 6 (The numbers 1, 10, 12, 13, 21, and 31).
Example 2:
Input: nums = [2,2,2]
Output: 1
Explanation: After including the reverse of each number, the resulting array is [2,2,2,2,2,2].
The number of distinct integers in this array is 1 (The number 2).
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106
|
Medium
|
[
"array",
"hash-table",
"math"
] |
[
"var countDistinctIntegers = function(nums) {\n const set = new Set()\n \n for(const e of nums) set.add(e)\n for(const e of nums) set.add(reverse(e))\n return set.size\n \n function reverse(num) {\n return parseInt(('' + num).split('').reverse().join(''))\n }\n};"
] |
|
2,443 |
sum-of-number-and-its-reverse
|
[
"The constraints are small enough that we can check every number.",
"To reverse a number, first convert it to a string. Then, create a new string that is the reverse of the first one. Finally, convert the new string back into a number."
] |
/**
* @param {number} num
* @return {boolean}
*/
var sumOfNumberAndReverse = function(num) {
};
|
Given a non-negative integer num, return true if num can be expressed as the sum of any non-negative integer and its reverse, or false otherwise.
Example 1:
Input: num = 443
Output: true
Explanation: 172 + 271 = 443 so we return true.
Example 2:
Input: num = 63
Output: false
Explanation: 63 cannot be expressed as the sum of a non-negative integer and its reverse so we return false.
Example 3:
Input: num = 181
Output: true
Explanation: 140 + 041 = 181 so we return true. Note that when a number is reversed, there may be leading zeros.
Constraints:
0 <= num <= 105
|
Medium
|
[
"math",
"enumeration"
] |
[
"var sumOfNumberAndReverse = function(num) {\n // let l = 0, r = num\n // while(l < r) {\n // const mid = ~~((l + r) / 2)\n // if(valid(mid) === 0) return true\n // else if(valid(mid) < 0) l = mid + 1\n // else r = mid - 1\n // }\n for(let i = 0; i <= num; i++) {\n if(valid(i) === 0) {\n // console.log(i)\n return true\n }\n }\n return false\n \n function valid(n) {\n return n + (parseInt( (''+n).split('').reverse().join('') ) ) - num\n }\n};"
] |
|
2,444 |
count-subarrays-with-fixed-bounds
|
[
"Can you solve the problem if all the numbers in the array were between minK and maxK inclusive?",
"Think of the inclusion-exclusion principle.",
"Divide the array into multiple subarrays such that each number in each subarray is between minK and maxK inclusive, solve the previous problem for each subarray, and sum all the answers."
] |
/**
* @param {number[]} nums
* @param {number} minK
* @param {number} maxK
* @return {number}
*/
var countSubarrays = function(nums, minK, maxK) {
};
|
You are given an integer array nums and two integers minK and maxK.
A fixed-bound subarray of nums is a subarray that satisfies the following conditions:
The minimum value in the subarray is equal to minK.
The maximum value in the subarray is equal to maxK.
Return the number of fixed-bound subarrays.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output: 2
Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].
Example 2:
Input: nums = [1,1,1,1], minK = 1, maxK = 1
Output: 10
Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
Constraints:
2 <= nums.length <= 105
1 <= nums[i], minK, maxK <= 106
|
Hard
|
[
"array",
"queue",
"sliding-window",
"monotonic-queue"
] |
[
"const countSubarrays = function(nums, minK, maxK) {\n let res = 0, n = nums.length\n let minIdx = -1, maxIdx = -1\n\n for(let i = 0, j = 0; i < n; i++) {\n if(nums[i] < minK || nums[i] > maxK) {\n minIdx = -1\n maxIdx = -1\n j = i + 1\n }\n if(nums[i] === minK) minIdx = i\n if(nums[i] === maxK) maxIdx = i\n if(minIdx !== -1 && maxIdx !== -1) {\n res += Math.min(minIdx, maxIdx) - j + 1\n }\n }\n \n return res\n};",
"var countSubarrays = function(nums, minK, maxK) {\n let res = 0, j = 0, jmin = -1, jmax = -1, n = nums.length;\n for (let i = 0; i < n; ++i) {\n if (nums[i] < minK || nums[i] > maxK) {\n jmin = jmax = -1;\n j = i + 1;\n }\n if (nums[i] == minK) jmin = i;\n if (nums[i] == maxK) jmax = i;\n res += Math.max(0, Math.min(jmin, jmax) - j + 1);\n }\n return res;\n};"
] |
|
2,446 |
determine-if-two-events-have-conflict
|
[
"Parse time format to some integer interval first",
"How would you determine if two intervals overlap?"
] |
/**
* @param {string[]} event1
* @param {string[]} event2
* @return {boolean}
*/
var haveConflict = function(event1, event2) {
};
|
You are given two arrays of strings that represent two inclusive events that happened on the same day, event1 and event2, where:
event1 = [startTime1, endTime1] and
event2 = [startTime2, endTime2].
Event times are valid 24 hours format in the form of HH:MM.
A conflict happens when two events have some non-empty intersection (i.e., some moment is common to both events).
Return true if there is a conflict between two events. Otherwise, return false.
Example 1:
Input: event1 = ["01:15","02:00"], event2 = ["02:00","03:00"]
Output: true
Explanation: The two events intersect at time 2:00.
Example 2:
Input: event1 = ["01:00","02:00"], event2 = ["01:20","03:00"]
Output: true
Explanation: The two events intersect starting from 01:20 to 02:00.
Example 3:
Input: event1 = ["10:00","11:00"], event2 = ["14:00","15:00"]
Output: false
Explanation: The two events do not intersect.
Constraints:
evnet1.length == event2.length == 2.
event1[i].length == event2[i].length == 5
startTime1 <= endTime1
startTime2 <= endTime2
All the event times follow the HH:MM format.
|
Easy
|
[
"array",
"string"
] | null |
[] |
2,447 |
number-of-subarrays-with-gcd-equal-to-k
|
[
"The constraints on nums.length are small. It is possible to check every subarray.",
"To calculate GCD, you can use a built-in function or the Euclidean Algorithm."
] |
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var subarrayGCD = function(nums, k) {
};
|
Given an integer array nums and an integer k, return the number of subarrays of nums where the greatest common divisor of the subarray's elements is k.
A subarray is a contiguous non-empty sequence of elements within an array.
The greatest common divisor of an array is the largest integer that evenly divides all the array elements.
Example 1:
Input: nums = [9,3,1,2,6,3], k = 3
Output: 4
Explanation: The subarrays of nums where 3 is the greatest common divisor of all the subarray's elements are:
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
Example 2:
Input: nums = [4], k = 7
Output: 0
Explanation: There are no subarrays of nums where 7 is the greatest common divisor of all the subarray's elements.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i], k <= 109
|
Medium
|
[
"array",
"math",
"number-theory"
] |
[
"const subarrayGCD = function (nums, k) {\n let res = 0\n const n = nums.length\n for (let i = 0; i < n; i++) {\n let cur = nums[i]\n for (let j = i; j < n; j++) {\n if (nums[j] % k !== 0) break\n cur = gcd(cur, nums[j])\n if (cur === k) res++\n }\n }\n\n return res\n\n function gcd(a, b) {\n return b === 0 ? a : gcd(b, a % b)\n }\n}"
] |
|
2,448 |
minimum-cost-to-make-array-equal
|
[
"Changing the elements into one of the numbers already existing in the array nums is optimal.",
"Try finding the cost of changing the array into each element, and return the minimum value."
] |
/**
* @param {number[]} nums
* @param {number[]} cost
* @return {number}
*/
var minCost = function(nums, cost) {
};
|
You are given two 0-indexed arrays nums and cost consisting each of n positive integers.
You can do the following operation any number of times:
Increase or decrease any element of the array nums by 1.
The cost of doing one operation on the ith element is cost[i].
Return the minimum total cost such that all the elements of the array nums become equal.
Example 1:
Input: nums = [1,3,5,2], cost = [2,3,1,14]
Output: 8
Explanation: We can make all the elements equal to 2 in the following way:
- Increase the 0th element one time. The cost is 2.
- Decrease the 1st element one time. The cost is 3.
- Decrease the 2nd element three times. The cost is 1 + 1 + 1 = 3.
The total cost is 2 + 3 + 3 = 8.
It can be shown that we cannot make the array equal with a smaller cost.
Example 2:
Input: nums = [2,2,2,2,2], cost = [4,2,8,1,3]
Output: 0
Explanation: All the elements are already equal, so no operations are needed.
Constraints:
n == nums.length == cost.length
1 <= n <= 105
1 <= nums[i], cost[i] <= 106
Test cases are generated in a way that the output doesn't exceed 253-1
|
Hard
|
[
"array",
"binary-search",
"greedy",
"sorting",
"prefix-sum"
] |
[
"const minCost = function (nums, cost) {\n const n = nums.length\n let l = Math.min(...nums)\n let r = Math.max(...nums)\n\n while(l < r) {\n const mid = Math.floor((l + r) / 2)\n const v1 = calc(mid)\n const v2 = calc(mid + 1)\n if(v1 < v2) {\n r = mid\n } else {\n l = mid + 1\n }\n }\n\n return calc(l)\n\n function calc(v) {\n let res = 0\n for (let i = 0; i < n; i++) {\n res += Math.abs(nums[i] - v) * cost[i]\n }\n return res\n }\n}"
] |
|
2,449 |
minimum-number-of-operations-to-make-arrays-similar
|
[
"Solve for even and odd numbers separately.",
"Greedily match smallest even element from nums to smallest even element from target, then similarly next smallest element and so on.",
"Similarly, match odd elements too."
] |
/**
* @param {number[]} nums
* @param {number[]} target
* @return {number}
*/
var makeSimilar = function(nums, target) {
};
|
You are given two positive integer arrays nums and target, of the same length.
In one operation, you can choose any two distinct indices i and j where 0 <= i, j < nums.length and:
set nums[i] = nums[i] + 2 and
set nums[j] = nums[j] - 2.
Two arrays are considered to be similar if the frequency of each element is the same.
Return the minimum number of operations required to make nums similar to target. The test cases are generated such that nums can always be similar to target.
Example 1:
Input: nums = [8,12,6], target = [2,14,10]
Output: 2
Explanation: It is possible to make nums similar to target in two operations:
- Choose i = 0 and j = 2, nums = [10,12,4].
- Choose i = 1 and j = 2, nums = [10,14,2].
It can be shown that 2 is the minimum number of operations needed.
Example 2:
Input: nums = [1,2,5], target = [4,1,3]
Output: 1
Explanation: We can make nums similar to target in one operation:
- Choose i = 1 and j = 2, nums = [1,4,3].
Example 3:
Input: nums = [1,1,1,1,1], target = [1,1,1,1,1]
Output: 0
Explanation: The array nums is already similiar to target.
Constraints:
n == nums.length == target.length
1 <= n <= 105
1 <= nums[i], target[i] <= 106
It is possible to make nums similar to target.
|
Hard
|
[
"array",
"greedy",
"sorting"
] |
[
"const makeSimilar = function (nums, target) {\n const odd = [], even = []\n const todd = [], teven = []\n for(const e of nums) {\n if(e % 2 === 0) even.push(e)\n else odd.push(e)\n }\n for(const e of target) {\n if(e % 2 === 0) teven.push(e)\n else todd.push(e)\n }\n const sfn = (a, b) => a - b\n odd.sort(sfn)\n todd.sort(sfn)\n even.sort(sfn)\n teven.sort(sfn)\n let res = 0\n for(let i = 0, n = odd.length; i < n; i++) {\n res += Math.abs(odd[i] - todd[i]) / 2\n }\n for(let i = 0, n = even.length; i < n; i++) {\n res += Math.abs(even[i] - teven[i]) / 2\n }\n return res / 2\n}"
] |
|
2,451 |
odd-string-difference
|
[
"Find the difference integer array for each string.",
"Compare them to find the odd one out."
] |
/**
* @param {string[]} words
* @return {string}
*/
var oddString = function(words) {
};
|
You are given an array of equal-length strings words. Assume that the length of each string is n.
Each string words[i] can be converted into a difference integer array difference[i] of length n - 1 where difference[i][j] = words[i][j+1] - words[i][j] where 0 <= j <= n - 2. Note that the difference between two letters is the difference between their positions in the alphabet i.e. the position of 'a' is 0, 'b' is 1, and 'z' is 25.
For example, for the string "acb", the difference integer array is [2 - 0, 1 - 2] = [2, -1].
All the strings in words have the same difference integer array, except one. You should find that string.
Return the string in words that has different difference integer array.
Example 1:
Input: words = ["adc","wzy","abc"]
Output: "abc"
Explanation:
- The difference integer array of "adc" is [3 - 0, 2 - 3] = [3, -1].
- The difference integer array of "wzy" is [25 - 22, 24 - 25]= [3, -1].
- The difference integer array of "abc" is [1 - 0, 2 - 1] = [1, 1].
The odd array out is [1, 1], so we return the corresponding string, "abc".
Example 2:
Input: words = ["aaa","bob","ccc","ddd"]
Output: "bob"
Explanation: All the integer arrays are [0, 0] except for "bob", which corresponds to [13, -13].
Constraints:
3 <= words.length <= 100
n == words[i].length
2 <= n <= 20
words[i] consists of lowercase English letters.
|
Easy
|
[
"array",
"hash-table",
"string"
] | null |
[] |
2,452 |
words-within-two-edits-of-dictionary
|
[
"Try brute-forcing the problem.",
"For each word in queries, try comparing to each word in dictionary.",
"If there is a maximum of two edit differences, the word should be present in answer."
] |
/**
* @param {string[]} queries
* @param {string[]} dictionary
* @return {string[]}
*/
var twoEditWords = function(queries, dictionary) {
};
|
You are given two string arrays, queries and dictionary. All words in each array comprise of lowercase English letters and have the same length.
In one edit you can take a word from queries, and change any letter in it to any other letter. Find all words from queries that, after a maximum of two edits, equal some word from dictionary.
Return a list of all words from queries, that match with some word from dictionary after a maximum of two edits. Return the words in the same order they appear in queries.
Example 1:
Input: queries = ["word","note","ants","wood"], dictionary = ["wood","joke","moat"]
Output: ["word","note","wood"]
Explanation:
- Changing the 'r' in "word" to 'o' allows it to equal the dictionary word "wood".
- Changing the 'n' to 'j' and the 't' to 'k' in "note" changes it to "joke".
- It would take more than 2 edits for "ants" to equal a dictionary word.
- "wood" can remain unchanged (0 edits) and match the corresponding dictionary word.
Thus, we return ["word","note","wood"].
Example 2:
Input: queries = ["yes"], dictionary = ["not"]
Output: []
Explanation:
Applying any two edits to "yes" cannot make it equal to "not". Thus, we return an empty array.
Constraints:
1 <= queries.length, dictionary.length <= 100
n == queries[i].length == dictionary[j].length
1 <= n <= 100
All queries[i] and dictionary[j] are composed of lowercase English letters.
|
Medium
|
[
"array",
"string"
] | null |
[] |
2,453 |
destroy-sequential-targets
|
[
"Keep track of nums[i] modulo k.",
"Iterate over nums in sorted order."
] |
/**
* @param {number[]} nums
* @param {number} space
* @return {number}
*/
var destroyTargets = function(nums, space) {
};
|
You are given a 0-indexed array nums consisting of positive integers, representing targets on a number line. You are also given an integer space.
You have a machine which can destroy targets. Seeding the machine with some nums[i] allows it to destroy all targets with values that can be represented as nums[i] + c * space, where c is any non-negative integer. You want to destroy the maximum number of targets in nums.
Return the minimum value of nums[i] you can seed the machine with to destroy the maximum number of targets.
Example 1:
Input: nums = [3,7,8,1,1,5], space = 2
Output: 1
Explanation: If we seed the machine with nums[3], then we destroy all targets equal to 1,3,5,7,9,...
In this case, we would destroy 5 total targets (all except for nums[2]).
It is impossible to destroy more than 5 targets, so we return nums[3].
Example 2:
Input: nums = [1,3,5,2,4,6], space = 2
Output: 1
Explanation: Seeding the machine with nums[0], or nums[3] destroys 3 targets.
It is not possible to destroy more than 3 targets.
Since nums[0] is the minimal integer that can destroy 3 targets, we return 1.
Example 3:
Input: nums = [6,2,5], space = 100
Output: 2
Explanation: Whatever initial seed we select, we can only destroy 1 target. The minimal seed is nums[1].
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= space <= 109
|
Medium
|
[
"array",
"hash-table",
"counting"
] |
[
"const destroyTargets = function(nums, space) {\n let maxCount = -Infinity;\n const map = {};\n\n for (const num of nums) {\n const reminder = num % space;\n map[reminder] = (map[reminder] || 0) + 1;\n maxCount = Math.max(maxCount, map[reminder]);\n }\n\n let ans = Infinity;\n for (const num of nums) {\n if (map[num % space] === maxCount) {\n ans = Math.min(ans, num);\n }\n }\n\n return ans;\n};"
] |
|
2,454 |
next-greater-element-iv
|
[
"Move forward in nums and store the value in a non-increasing stack for the first greater value.",
"Move the value in the stack to an ordered data structure for the second greater value.",
"Move value from the ordered data structure for the answer."
] |
/**
* @param {number[]} nums
* @return {number[]}
*/
var secondGreaterElement = function(nums) {
};
|
You are given a 0-indexed array of non-negative integers nums. For each integer in nums, you must find its respective second greater integer.
The second greater integer of nums[i] is nums[j] such that:
j > i
nums[j] > nums[i]
There exists exactly one index k such that nums[k] > nums[i] and i < k < j.
If there is no such nums[j], the second greater integer is considered to be -1.
For example, in the array [1, 2, 4, 3], the second greater integer of 1 is 4, 2 is 3, and that of 3 and 4 is -1.
Return an integer array answer, where answer[i] is the second greater integer of nums[i].
Example 1:
Input: nums = [2,4,0,9,6]
Output: [9,6,6,-1,-1]
Explanation:
0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2.
1st index: 9 is the first, and 6 is the second integer greater than 4, to the right of 4.
2nd index: 9 is the first, and 6 is the second integer greater than 0, to the right of 0.
3rd index: There is no integer greater than 9 to its right, so the second greater integer is considered to be -1.
4th index: There is no integer greater than 6 to its right, so the second greater integer is considered to be -1.
Thus, we return [9,6,6,-1,-1].
Example 2:
Input: nums = [3,3]
Output: [-1,-1]
Explanation:
We return [-1,-1] since neither integer has any integer greater than it.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
|
Hard
|
[
"array",
"binary-search",
"stack",
"sorting",
"heap-priority-queue",
"monotonic-stack"
] |
[
"var secondGreaterElement = function(nums) {\n let n = nums.length, res = new Array(n).fill(-1);\n const s1 = [], s2 = [], tmp = [];\n for (let i = 0; i < n; i++) {\n while (s2.length && nums[s2.at(-1)] < nums[i]) res[s2.pop()] = nums[i];\n while (s1.length && nums[s1.at(-1)] < nums[i]) tmp.push(s1.pop());\n while (tmp.length) s2.push(tmp.pop());\n s1.push(i);\n }\n return res;\n};"
] |
|
2,455 |
average-value-of-even-numbers-that-are-divisible-by-three
|
[
"What is the property of a number if it is divisible by both 2 and 3 at the same time?",
"It is equivalent to finding all the numbers that are divisible by 6."
] |
/**
* @param {number[]} nums
* @return {number}
*/
var averageValue = function(nums) {
};
|
Given an integer array nums of positive integers, return the average value of all even integers that are divisible by 3.
Note that the average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.
Example 1:
Input: nums = [1,3,6,10,12,15]
Output: 9
Explanation: 6 and 12 are even numbers that are divisible by 3. (6 + 12) / 2 = 9.
Example 2:
Input: nums = [1,2,4,7,10]
Output: 0
Explanation: There is no single number that satisfies the requirement, so return 0.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 1000
|
Easy
|
[
"array",
"math"
] | null |
[] |
2,456 |
most-popular-video-creator
|
[
"Use a hash table to store and categorize videos based on their creator.",
"For each creator, iterate through all their videos and use three variables to keep track of their popularity, their most popular video, and the id of their most popular video."
] |
/**
* @param {string[]} creators
* @param {string[]} ids
* @param {number[]} views
* @return {string[][]}
*/
var mostPopularCreator = function(creators, ids, views) {
};
|
You are given two string arrays creators and ids, and an integer array views, all of length n. The ith video on a platform was created by creator[i], has an id of ids[i], and has views[i] views.
The popularity of a creator is the sum of the number of views on all of the creator's videos. Find the creator with the highest popularity and the id of their most viewed video.
If multiple creators have the highest popularity, find all of them.
If multiple videos have the highest view count for a creator, find the lexicographically smallest id.
Return a 2D array of strings answer where answer[i] = [creatori, idi] means that creatori has the highest popularity and idi is the id of their most popular video. The answer can be returned in any order.
Example 1:
Input: creators = ["alice","bob","alice","chris"], ids = ["one","two","three","four"], views = [5,10,5,4]
Output: [["alice","one"],["bob","two"]]
Explanation:
The popularity of alice is 5 + 5 = 10.
The popularity of bob is 10.
The popularity of chris is 4.
alice and bob are the most popular creators.
For bob, the video with the highest view count is "two".
For alice, the videos with the highest view count are "one" and "three". Since "one" is lexicographically smaller than "three", it is included in the answer.
Example 2:
Input: creators = ["alice","alice","alice"], ids = ["a","b","c"], views = [1,2,2]
Output: [["alice","b"]]
Explanation:
The videos with id "b" and "c" have the highest view count.
Since "b" is lexicographically smaller than "c", it is included in the answer.
Constraints:
n == creators.length == ids.length == views.length
1 <= n <= 105
1 <= creators[i].length, ids[i].length <= 5
creators[i] and ids[i] consist only of lowercase English letters.
0 <= views[i] <= 105
|
Medium
|
[
"array",
"hash-table",
"string",
"sorting",
"heap-priority-queue"
] | null |
[] |
2,457 |
minimum-addition-to-make-integer-beautiful
|
[
"Think about each digit independently.",
"Turn the rightmost non-zero digit to zero until the digit sum is greater than target."
] |
/**
* @param {number} n
* @param {number} target
* @return {number}
*/
var makeIntegerBeautiful = function(n, target) {
};
|
You are given two positive integers n and target.
An integer is considered beautiful if the sum of its digits is less than or equal to target.
Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful.
Example 1:
Input: n = 16, target = 6
Output: 4
Explanation: Initially n is 16 and its digit sum is 1 + 6 = 7. After adding 4, n becomes 20 and digit sum becomes 2 + 0 = 2. It can be shown that we can not make n beautiful with adding non-negative integer less than 4.
Example 2:
Input: n = 467, target = 6
Output: 33
Explanation: Initially n is 467 and its digit sum is 4 + 6 + 7 = 17. After adding 33, n becomes 500 and digit sum becomes 5 + 0 + 0 = 5. It can be shown that we can not make n beautiful with adding non-negative integer less than 33.
Example 3:
Input: n = 1, target = 1
Output: 0
Explanation: Initially n is 1 and its digit sum is 1, which is already smaller than or equal to target.
Constraints:
1 <= n <= 1012
1 <= target <= 150
The input will be generated such that it is always possible to make n beautiful.
|
Medium
|
[
"math",
"greedy"
] |
[
"const makeIntegerBeautiful = function(n, target) {\n let res = 0, carry = 0\n const arr = []\n while(n) {\n if(digitSum(n) <= target) break\n const remain = (n % 10)\n if(remain === 0) {\n arr.push(0)\n carry = 0\n } else {\n arr.push(10 - remain)\n carry = 1\n }\n \n n = (Math.floor(n / 10)) + carry\n }\n if(arr.length === 0) return 0\n arr.reverse()\n return +arr.map(e => '' + e).join('')\n \n function digitSum(num) {\n let res = 0\n while(num > 0) {\n res += (num % 10)\n num = Math.floor(num/10)\n }\n return res\n }\n};"
] |
|
2,458 |
height-of-binary-tree-after-subtree-removal-queries
|
[
"Try pre-computing the answer for each node from 1 to n, and answer each query in O(1).",
"The answers can be precomputed in a single tree traversal after computing the height of each 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
* @param {number[]} queries
* @return {number[]}
*/
var treeQueries = function(root, queries) {
};
|
You are given the root of a binary tree with n nodes. Each node is assigned a unique value from 1 to n. You are also given an array queries of size m.
You have to perform m independent queries on the tree where in the ith query you do the following:
Remove the subtree rooted at the node with the value queries[i] from the tree. It is guaranteed that queries[i] will not be equal to the value of the root.
Return an array answer of size m where answer[i] is the height of the tree after performing the ith query.
Note:
The queries are independent, so the tree returns to its initial state after each query.
The height of a tree is the number of edges in the longest simple path from the root to some node in the tree.
Example 1:
Input: root = [1,3,4,2,null,6,5,null,null,null,null,null,7], queries = [4]
Output: [2]
Explanation: The diagram above shows the tree after removing the subtree rooted at node with value 4.
The height of the tree is 2 (The path 1 -> 3 -> 2).
Example 2:
Input: root = [5,8,9,2,1,3,7,4,6], queries = [3,2,4,8]
Output: [3,2,3,2]
Explanation: We have the following queries:
- Removing the subtree rooted at node with value 3. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 4).
- Removing the subtree rooted at node with value 2. The height of the tree becomes 2 (The path 5 -> 8 -> 1).
- Removing the subtree rooted at node with value 4. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 6).
- Removing the subtree rooted at node with value 8. The height of the tree becomes 2 (The path 5 -> 9 -> 3).
Constraints:
The number of nodes in the tree is n.
2 <= n <= 105
1 <= Node.val <= n
All the values in the tree are unique.
m == queries.length
1 <= m <= min(n, 104)
1 <= queries[i] <= n
queries[i] != root.val
|
Hard
|
[
"array",
"tree",
"depth-first-search",
"breadth-first-search",
"binary-tree"
] | null |
[] |
2,460 |
apply-operations-to-an-array
|
[
"Iterate over the array and simulate the described process."
] |
/**
* @param {number[]} nums
* @return {number[]}
*/
var applyOperations = function(nums) {
};
|
You are given a 0-indexed array nums of size n consisting of non-negative integers.
You need to apply n - 1 operations to this array where, in the ith operation (0-indexed), you will apply the following on the ith element of nums:
If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. Otherwise, you skip this operation.
After performing all the operations, shift all the 0's to the end of the array.
For example, the array [1,0,2,0,0,1] after shifting all its 0's to the end, is [1,2,1,0,0,0].
Return the resulting array.
Note that the operations are applied sequentially, not all at once.
Example 1:
Input: nums = [1,2,2,1,1,0]
Output: [1,4,2,0,0,0]
Explanation: We do the following operations:
- i = 0: nums[0] and nums[1] are not equal, so we skip this operation.
- i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0].
- i = 2: nums[2] and nums[3] are not equal, so we skip this operation.
- i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0].
- i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0].
After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0].
Example 2:
Input: nums = [0,1]
Output: [1,0]
Explanation: No operation can be applied, we just shift the 0 to the end.
Constraints:
2 <= nums.length <= 2000
0 <= nums[i] <= 1000
|
Easy
|
[
"array",
"simulation"
] |
[
"var applyOperations = function(nums) {\n const n = nums.length\n for(let i = 0; i < n - 1; i++) {\n if(nums[i] === nums[i + 1]) {\n nums[i] *= 2\n nums[i + 1] = 0\n }\n }\n const res = nums.filter(e => e !== 0)\n while(res.length !== n) res.push(0)\n return res\n};"
] |
|
2,461 |
maximum-sum-of-distinct-subarrays-with-length-k
|
[
"Which elements change when moving from the subarray of size k that ends at index i to the subarray of size k that ends at index i + 1?",
"Only two elements change, the element at i + 1 is added into the subarray, and the element at i - k + 1 gets removed from the subarray.",
"Iterate through each subarray of size k and keep track of the sum of the subarray and the frequency of each element."
] |
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var maximumSubarraySum = function(nums, k) {
};
|
You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:
The length of the subarray is k, and
All the elements of the subarray are distinct.
Return the maximum subarray sum of all the subarrays that meet the conditions. If no subarray meets the conditions, return 0.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,5,4,2,9,9,9], k = 3
Output: 15
Explanation: The subarrays of nums with length 3 are:
- [1,5,4] which meets the requirements and has a sum of 10.
- [5,4,2] which meets the requirements and has a sum of 11.
- [4,2,9] which meets the requirements and has a sum of 15.
- [2,9,9] which does not meet the requirements because the element 9 is repeated.
- [9,9,9] which does not meet the requirements because the element 9 is repeated.
We return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions
Example 2:
Input: nums = [4,4,4], k = 3
Output: 0
Explanation: The subarrays of nums with length 3 are:
- [4,4,4] which does not meet the requirements because the element 4 is repeated.
We return 0 because no subarrays meet the conditions.
Constraints:
1 <= k <= nums.length <= 105
1 <= nums[i] <= 105
|
Medium
|
[
"array",
"hash-table",
"sliding-window"
] |
[
"const maximumSubarraySum = function (nums, k) {\n const map = new Map(), n = nums.length\n let i = 0, res = 0, sum = 0\n\n while(i < n && i < k) {\n const cur = nums[i]\n map.set(cur, (map.get(cur) || 0) + 1 )\n sum += cur\n i++\n }\n if(map.size === k) res = sum\n\n for(i = k; i < n; i++) {\n const cur = nums[i]\n map.set(cur, (map.get(cur) || 0) + 1)\n const pre = nums[i - k]\n map.set(pre, (map.get(pre) || 0) - 1)\n if(map.get(pre) === 0) map.delete(pre)\n\n sum += cur\n sum -= nums[i - k]\n\n if(map.size === k) res = Math.max(res, sum)\n }\n\n return res\n}",
"const maximumSubarraySum = function(nums, k) {\n let res = 0\n const n = nums.length\n \n const preSum = Array(n).fill(0)\n preSum[0] = nums[0]\n for(let i = 1; i < n; i++) {\n preSum[i] = preSum[i - 1] + nums[i]\n }\n \n const set = new Set()\n \n const lastHash = {}\n \n for(let i = 0; i < n; i++) {\n const cur = nums[i]\n lastHash[cur] = i\n if(i < k - 1) set.add(cur)\n else if(i === k - 1) {\n set.add(cur)\n if(set.size === k) {\n res = preSum[i]\n }\n } else {\n if(lastHash[nums[i - k]] == i - k) set.delete(nums[i - k])\n set.add(nums[i])\n if(set.size === k) {\n res = Math.max(res, preSum[i] - preSum[i - k])\n }\n }\n }\n \n return res\n};"
] |
|
2,462 |
total-cost-to-hire-k-workers
|
[
"Maintain two minheaps: one for the left and one for the right.",
"Compare the top element from two heaps and remove the appropriate one.",
"Add a new element to the heap and maintain its size as k."
] |
/**
* @param {number[]} costs
* @param {number} k
* @param {number} candidates
* @return {number}
*/
var totalCost = function(costs, k, candidates) {
};
|
You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the ith worker.
You are also given two integers k and candidates. We want to hire exactly k workers according to the following rules:
You will run k sessions and hire exactly one worker in each session.
In each hiring session, choose the worker with the lowest cost from either the first candidates workers or the last candidates workers. Break the tie by the smallest index.
For example, if costs = [3,2,7,7,1,2] and candidates = 2, then in the first hiring session, we will choose the 4th worker because they have the lowest cost [3,2,7,7,1,2].
In the second hiring session, we will choose 1st worker because they have the same lowest cost as 4th worker but they have the smallest index [3,2,7,7,2]. Please note that the indexing may be changed in the process.
If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index.
A worker can only be chosen once.
Return the total cost to hire exactly k workers.
Example 1:
Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4
Output: 11
Explanation: We hire 3 workers in total. The total cost is initially 0.
- In the first hiring round we choose the worker from [17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2.
- In the second hiring round we choose the worker from [17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4.
- In the third hiring round we choose the worker from [17,12,10,7,11,20,8]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers.
The total hiring cost is 11.
Example 2:
Input: costs = [1,2,4,1], k = 3, candidates = 3
Output: 4
Explanation: We hire 3 workers in total. The total cost is initially 0.
- In the first hiring round we choose the worker from [1,2,4,1]. The lowest cost is 1, and we break the tie by the smallest index, which is 0. The total cost = 0 + 1 = 1. Notice that workers with index 1 and 2 are common in the first and last 3 workers.
- In the second hiring round we choose the worker from [2,4,1]. The lowest cost is 1 (index 2). The total cost = 1 + 1 = 2.
- In the third hiring round there are less than three candidates. We choose the worker from the remaining workers [2,4]. The lowest cost is 2 (index 0). The total cost = 2 + 2 = 4.
The total hiring cost is 4.
Constraints:
1 <= costs.length <= 105
1 <= costs[i] <= 105
1 <= k, candidates <= costs.length
|
Medium
|
[
"array",
"two-pointers",
"heap-priority-queue",
"simulation"
] |
[
"const totalCost = function(costs, k, candidates) {\n const fn = (a, b) => a[0] === b[0] ? a[1] < b[1] : a[0] < b[0]\n const n = costs.length\n let l = 0, r = n - 1\n const first = new PriorityQueue(fn)\n const last = new PriorityQueue(fn)\n \n for(let i = 0; i < Math.min(candidates, n); i++) {\n first.push([costs[i], i])\n l = i\n }\n \n for(let i = n - 1; i > Math.max(0, candidates - 1, n - 1 - candidates); i--) {\n last.push([costs[i], i])\n r = i\n }\n \n // console.log(first, last)\n \n let res = 0\n let num = k\n while(num) {\n const ft = first.peek()\n const lt = last.peek()\n \n if(ft && lt) {\n if(ft[0] < lt[0]) {\n first.pop()\n res += ft[0]\n if(r - l > 1) {\n l++\n first.push([costs[l], l])\n }\n } else if(ft[0] > lt[0]) {\n last.pop()\n res += lt[0]\n if(r - l > 1) {\n r--\n last.push([costs[r], r])\n }\n } else {\n first.pop()\n res += ft[0]\n if(r - l > 1) {\n l++\n first.push([costs[l], l])\n } \n }\n } else if(ft) {\n first.pop()\n res += ft[0]\n } else if(lt) {\n last.pop()\n res += lt[0]\n }\n // console.log(res)\n num--\n }\n \n \n return res\n \n};\n\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}"
] |
|
2,463 |
minimum-total-distance-traveled
|
[
"Sort robots and factories by their positions.",
"After sorting, notice that each factory should repair some subsegment of robots.",
"Find the minimum total distance to repair first i robots with first j factories."
] |
/**
* @param {number[]} robot
* @param {number[][]} factory
* @return {number}
*/
var minimumTotalDistance = function(robot, factory) {
};
|
There are some robots and factories on the X-axis. You are given an integer array robot where robot[i] is the position of the ith robot. You are also given a 2D integer array factory where factory[j] = [positionj, limitj] indicates that positionj is the position of the jth factory and that the jth factory can repair at most limitj robots.
The positions of each robot are unique. The positions of each factory are also unique. Note that a robot can be in the same position as a factory initially.
All the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving.
At any moment, you can set the initial direction of moving for some robot. Your target is to minimize the total distance traveled by all the robots.
Return the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired.
Note that
All robots move at the same speed.
If two robots move in the same direction, they will never collide.
If two robots move in opposite directions and they meet at some point, they do not collide. They cross each other.
If a robot passes by a factory that reached its limits, it crosses it as if it does not exist.
If the robot moved from a position x to a position y, the distance it moved is |y - x|.
Example 1:
Input: robot = [0,4,6], factory = [[2,2],[6,2]]
Output: 4
Explanation: As shown in the figure:
- The first robot at position 0 moves in the positive direction. It will be repaired at the first factory.
- The second robot at position 4 moves in the negative direction. It will be repaired at the first factory.
- The third robot at position 6 will be repaired at the second factory. It does not need to move.
The limit of the first factory is 2, and it fixed 2 robots.
The limit of the second factory is 2, and it fixed 1 robot.
The total distance is |2 - 0| + |2 - 4| + |6 - 6| = 4. It can be shown that we cannot achieve a better total distance than 4.
Example 2:
Input: robot = [1,-1], factory = [[-2,1],[2,1]]
Output: 2
Explanation: As shown in the figure:
- The first robot at position 1 moves in the positive direction. It will be repaired at the second factory.
- The second robot at position -1 moves in the negative direction. It will be repaired at the first factory.
The limit of the first factory is 1, and it fixed 1 robot.
The limit of the second factory is 1, and it fixed 1 robot.
The total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we cannot achieve a better total distance than 2.
Constraints:
1 <= robot.length, factory.length <= 100
factory[j].length == 2
-109 <= robot[i], positionj <= 109
0 <= limitj <= robot.length
The input will be generated such that it is always possible to repair every robot.
|
Hard
|
[
"array",
"dynamic-programming",
"sorting"
] |
[
"const minimumTotalDistance = function(robot, factory) {\n robot.sort((a, b) => a - b)\n factory.sort((a, b) => a[0] - b[0])\n const facs = []\n for(const f of factory) {\n for(let i = 0; i < f[1]; i++) facs.push(f[0])\n }\n const n = facs.length\n let dp = Array(n + 1).fill(0)\n for(let i = 0; i < robot.length; i++) {\n const nxt = Array(n + 1).fill(Infinity)\n for(let j = 0; j < n; j++) {\n nxt[j + 1] = Math.min(nxt[j], dp[j] + Math.abs(robot[i] - facs[j]))\n }\n dp = nxt\n }\n \n \n return dp[n]\n};"
] |
|
2,465 |
number-of-distinct-averages
|
[
"Try sorting the array.",
"Store the averages being calculated, and find the distinct ones."
] |
/**
* @param {number[]} nums
* @return {number}
*/
var distinctAverages = function(nums) {
};
|
You are given a 0-indexed integer array nums of even length.
As long as nums is not empty, you must repetitively:
Find the minimum number in nums and remove it.
Find the maximum number in nums and remove it.
Calculate the average of the two removed numbers.
The average of two numbers a and b is (a + b) / 2.
For example, the average of 2 and 3 is (2 + 3) / 2 = 2.5.
Return the number of distinct averages calculated using the above process.
Note that when there is a tie for a minimum or maximum number, any can be removed.
Example 1:
Input: nums = [4,1,4,0,3,5]
Output: 2
Explanation:
1. Remove 0 and 5, and the average is (0 + 5) / 2 = 2.5. Now, nums = [4,1,4,3].
2. Remove 1 and 4. The average is (1 + 4) / 2 = 2.5, and nums = [4,3].
3. Remove 3 and 4, and the average is (3 + 4) / 2 = 3.5.
Since there are 2 distinct numbers among 2.5, 2.5, and 3.5, we return 2.
Example 2:
Input: nums = [1,100]
Output: 1
Explanation:
There is only one average to be calculated after removing 1 and 100, so we return 1.
Constraints:
2 <= nums.length <= 100
nums.length is even.
0 <= nums[i] <= 100
|
Easy
|
[
"array",
"hash-table",
"two-pointers",
"sorting"
] | null |
[] |
2,466 |
count-ways-to-build-good-strings
|
[
"Calculate the number of good strings with length less or equal to some constant x.",
"Apply dynamic programming using the group size of consecutive zeros and ones."
] |
/**
* @param {number} low
* @param {number} high
* @param {number} zero
* @param {number} one
* @return {number}
*/
var countGoodStrings = function(low, high, zero, one) {
};
|
Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:
Append the character '0' zero times.
Append the character '1' one times.
This can be performed any number of times.
A good string is a string constructed by the above process having a length between low and high (inclusive).
Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo 109 + 7.
Example 1:
Input: low = 3, high = 3, zero = 1, one = 1
Output: 8
Explanation:
One possible valid good string is "011".
It can be constructed as follows: "" -> "0" -> "01" -> "011".
All binary strings from "000" to "111" are good strings in this example.
Example 2:
Input: low = 2, high = 3, zero = 1, one = 2
Output: 5
Explanation: The good strings are "00", "11", "000", "110", and "011".
Constraints:
1 <= low <= high <= 105
1 <= zero, one <= low
|
Medium
|
[
"dynamic-programming"
] | null |
[] |
2,467 |
most-profitable-path-in-a-tree
|
[
"Bob travels along a fixed path (from node “bob” to node 0).",
"Calculate Alice’s distance to each node via DFS.",
"We can calculate Alice’s score along a path ending at some node easily using Hints 1 and 2."
] |
/**
* @param {number[][]} edges
* @param {number} bob
* @param {number[]} amount
* @return {number}
*/
var mostProfitablePath = function(edges, bob, amount) {
};
|
There is an undirected tree with n nodes labeled from 0 to n - 1, rooted at node 0. You are 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.
At every node i, there is a gate. You are also given an array of even integers amount, where amount[i] represents:
the price needed to open the gate at node i, if amount[i] is negative, or,
the cash reward obtained on opening the gate at node i, otherwise.
The game goes on as follows:
Initially, Alice is at node 0 and Bob is at node bob.
At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node 0.
For every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that:
If the gate is already open, no price will be required, nor will there be any cash reward.
If Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is c, then both Alice and Bob pay c / 2 each. Similarly, if the reward at the gate is c, both of them receive c / 2 each.
If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node 0, he stops moving. Note that these events are independent of each other.
Return the maximum net income Alice can have if she travels towards the optimal leaf node.
Example 1:
Input: edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6]
Output: 6
Explanation:
The above diagram represents the given tree. The game goes as follows:
- Alice is initially on node 0, Bob on node 3. They open the gates of their respective nodes.
Alice's net income is now -2.
- Both Alice and Bob move to node 1.
Since they reach here simultaneously, they open the gate together and share the reward.
Alice's net income becomes -2 + (4 / 2) = 0.
- Alice moves on to node 3. Since Bob already opened its gate, Alice's income remains unchanged.
Bob moves on to node 0, and stops moving.
- Alice moves on to node 4 and opens the gate there. Her net income becomes 0 + 6 = 6.
Now, neither Alice nor Bob can make any further moves, and the game ends.
It is not possible for Alice to get a higher net income.
Example 2:
Input: edges = [[0,1]], bob = 1, amount = [-7280,2350]
Output: -7280
Explanation:
Alice follows the path 0->1 whereas Bob follows the path 1->0.
Thus, Alice opens the gate at node 0 only. Hence, her net income is -7280.
Constraints:
2 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree.
1 <= bob < n
amount.length == n
amount[i] is an even integer in the range [-104, 104].
|
Medium
|
[
"array",
"tree",
"depth-first-search",
"breadth-first-search",
"graph"
] | null |
[] |
2,468 |
split-message-based-on-limit
|
[
"Could you solve the problem if you knew how many digits the total number of parts has?",
"Try all possible lengths of the total number of parts, and see if the string can be split such that the total number of parts has that length.",
"Binary search can be used for each part length to find the precise number of parts needed."
] |
/**
* @param {string} message
* @param {number} limit
* @return {string[]}
*/
var splitMessage = function(message, limit) {
};
|
You are given a string, message, and a positive integer, limit.
You must split message into one or more parts based on limit. Each resulting part should have the suffix "<a/b>", where "b" is to be replaced with the total number of parts and "a" is to be replaced with the index of the part, starting from 1 and going up to b. Additionally, the length of each resulting part (including its suffix) should be equal to limit, except for the last part whose length can be at most limit.
The resulting parts should be formed such that when their suffixes are removed and they are all concatenated in order, they should be equal to message. Also, the result should contain as few parts as possible.
Return the parts message would be split into as an array of strings. If it is impossible to split message as required, return an empty array.
Example 1:
Input: message = "this is really a very awesome message", limit = 9
Output: ["thi<1/14>","s i<2/14>","s r<3/14>","eal<4/14>","ly <5/14>","a v<6/14>","ery<7/14>"," aw<8/14>","eso<9/14>","me<10/14>"," m<11/14>","es<12/14>","sa<13/14>","ge<14/14>"]
Explanation:
The first 9 parts take 3 characters each from the beginning of message.
The next 5 parts take 2 characters each to finish splitting message.
In this example, each part, including the last, has length 9.
It can be shown it is not possible to split message into less than 14 parts.
Example 2:
Input: message = "short message", limit = 15
Output: ["short mess<1/2>","age<2/2>"]
Explanation:
Under the given constraints, the string can be split into two parts:
- The first part comprises of the first 10 characters, and has a length 15.
- The next part comprises of the last 3 characters, and has a length 8.
Constraints:
1 <= message.length <= 104
message consists only of lowercase English letters and ' '.
1 <= limit <= 104
|
Hard
|
[
"string",
"binary-search"
] | null |
[] |
2,469 |
convert-the-temperature
|
[
"Implement formulas that are given in the statement."
] |
/**
* @param {number} celsius
* @return {number[]}
*/
var convertTemperature = function(celsius) {
};
|
You are given a non-negative floating point number rounded to two decimal places celsius, that denotes the temperature in Celsius.
You should convert Celsius into Kelvin and Fahrenheit and return it as an array ans = [kelvin, fahrenheit].
Return the array ans. Answers within 10-5 of the actual answer will be accepted.
Note that:
Kelvin = Celsius + 273.15
Fahrenheit = Celsius * 1.80 + 32.00
Example 1:
Input: celsius = 36.50
Output: [309.65000,97.70000]
Explanation: Temperature at 36.50 Celsius converted in Kelvin is 309.65 and converted in Fahrenheit is 97.70.
Example 2:
Input: celsius = 122.11
Output: [395.26000,251.79800]
Explanation: Temperature at 122.11 Celsius converted in Kelvin is 395.26 and converted in Fahrenheit is 251.798.
Constraints:
0 <= celsius <= 1000
|
Easy
|
[
"math"
] |
[
"var convertTemperature = function(celsius) {\n return [celsius + 273.15, celsius * 1.8 + 32] \n};"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.