QID
int64 1
2.85k
| titleSlug
stringlengths 3
77
| Hints
sequence | Code
stringlengths 80
1.34k
| Body
stringlengths 190
4.55k
| Difficulty
stringclasses 3
values | Topics
sequence | Definitions
stringclasses 14
values | Solutions
sequence |
---|---|---|---|---|---|---|---|---|
1,562 | find-latest-group-of-size-m | [
"Since the problem asks for the latest step, can you start the searching from the end of arr?",
"Use a map to store the current “1” groups.",
"At each step (going backwards) you need to split one group and update the map."
] | /**
* @param {number[]} arr
* @param {number} m
* @return {number}
*/
var findLatestStep = function(arr, m) {
}; | Given an array arr that represents a permutation of numbers from 1 to n.
You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1.
You are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction.
Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.
Example 1:
Input: arr = [3,5,1,2,4], m = 1
Output: 4
Explanation:
Step 1: "00100", groups: ["1"]
Step 2: "00101", groups: ["1", "1"]
Step 3: "10101", groups: ["1", "1", "1"]
Step 4: "11101", groups: ["111", "1"]
Step 5: "11111", groups: ["11111"]
The latest step at which there exists a group of size 1 is step 4.
Example 2:
Input: arr = [3,1,5,4,2], m = 2
Output: -1
Explanation:
Step 1: "00100", groups: ["1"]
Step 2: "10100", groups: ["1", "1"]
Step 3: "10101", groups: ["1", "1", "1"]
Step 4: "10111", groups: ["1", "111"]
Step 5: "11111", groups: ["11111"]
No group of size 2 exists during any step.
Constraints:
n == arr.length
1 <= m <= n <= 105
1 <= arr[i] <= n
All integers in arr are distinct.
| Medium | [
"array",
"binary-search",
"simulation"
] | [
"const findLatestStep = function(arr, m) {\n const uF = new UnionFind(arr);\n const mRecords = new Set(); // This contains parents whose rank is m \n const visited = new Set();\n let res = -1;\n\n for (let i = 0; i < arr.length; i++) {\n let val = arr[i];\n visited.add(val);\n \n if (visited.has(val - 1)) {\n let parent1 = uF.find(val);\n let parent2 = uF.find(val - 1);\n\t\t\t // Since merging, the rank for val - 1 & val has changed,\n // they are no longer m. Hence removed them from set.\n mRecords.delete(parent1); \n mRecords.delete(parent2);\n uF.union(val, val - 1);\n }\n \n if (visited.has(val + 1)) {\n let parent1 = uF.find(val);\n let parent2 = uF.find(val + 1);\n mRecords.delete(parent1);\n mRecords.delete(parent2);\n uF.union(val, val + 1);\n }\n \n let parent = uF.find(val);\n if (uF.ranks.get(parent) === m) mRecords.add(parent);\n if (mRecords.size > 0) res = i + 1; \n }\n \n return res; \n};\n\nclass UnionFind {\n constructor(arr) {\n [this.parents, this.ranks] = this.initialise(arr);\n }\n \n initialise(arr) {\n const parents = new Map();\n const ranks = new Map();\n arr.forEach(val => {\n parents.set(val, val);\n ranks.set(val, 1);\n })\n \n return [parents, ranks];\n }\n \n find(val) {\n if (this.parents.get(val) === val) return val;\n this.parents.set(val, this.find(this.parents.get(val)));\n return this.parents.get(val);\n }\n \n union(m, n) {\n const rootM = this.find(m);\n const rootN = this.find(n);\n \n if (rootM === rootN) return;\n if (rootM > rootN) {\n this.updateParent(rootN, rootM);\n } else {\n this.updateParent(rootM, rootN);\n }\n }\n \n updateParent(child, parent) {\n this.ranks.set(parent, this.ranks.get(parent) + this.ranks.get(child));\n this.parents.set(child, parent);\n }\n}"
] |
|
1,563 | stone-game-v | [
"We need to try all possible divisions for the current row to get the max score.",
"As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming."
] | /**
* @param {number[]} stoneValue
* @return {number}
*/
var stoneGameV = function(stoneValue) {
}; | There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.
In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.
The game ends when there is only one stone remaining. Alice's is initially zero.
Return the maximum score that Alice can obtain.
Example 1:
Input: stoneValue = [6,2,3,4,5,5]
Output: 18
Explanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.
In the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).
The last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.
Example 2:
Input: stoneValue = [7,7,7,7,7,7,7]
Output: 28
Example 3:
Input: stoneValue = [4]
Output: 0
Constraints:
1 <= stoneValue.length <= 500
1 <= stoneValue[i] <= 106
| Hard | [
"array",
"math",
"dynamic-programming",
"game-theory"
] | null | [] |
1,566 | detect-pattern-of-length-m-repeated-k-or-more-times | [
"Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times."
] | /**
* @param {number[]} arr
* @param {number} m
* @param {number} k
* @return {boolean}
*/
var containsPattern = function(arr, m, k) {
}; | Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.
A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions.
Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false.
Example 1:
Input: arr = [1,2,4,4,4,4], m = 1, k = 3
Output: true
Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.
Example 2:
Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2
Output: true
Explanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.
Example 3:
Input: arr = [1,2,1,2,1,3], m = 2, k = 3
Output: false
Explanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.
Constraints:
2 <= arr.length <= 100
1 <= arr[i] <= 100
1 <= m <= 100
2 <= k <= 100
| Easy | [
"array",
"enumeration"
] | null | [] |
1,567 | maximum-length-of-subarray-with-positive-product | [
"Split the whole array into subarrays by zeroes since a subarray with positive product cannot contain any zero.",
"If the subarray has even number of negative numbers, the whole subarray has positive product.",
"Otherwise, we have two choices, either - remove the prefix till the first negative element in this subarray, or remove the suffix starting from the last negative element in this subarray."
] | /**
* @param {number[]} nums
* @return {number}
*/
var getMaxLen = function(nums) {
}; | Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
| Medium | [
"array",
"dynamic-programming",
"greedy"
] | [
"const getMaxLen = function(nums) {\n let res = 0, zeroIdx = -1, negIdx = -1, count = 0\n for(let i = 0, len = nums.length; i < len; i++) {\n if(nums[i] < 0) {\n count++\n if(negIdx === -1) negIdx = i\n }\n if(nums[i] === 0) {\n count = 0\n negIdx = -1\n zeroIdx = i\n } else {\n if(count % 2 === 0) res = Math.max(res, i - zeroIdx)\n else res = Math.max(res, i - negIdx)\n }\n }\n \n return res\n};"
] |
|
1,568 | minimum-number-of-days-to-disconnect-island | [
"Return 0 if the grid is already disconnected.",
"Return 1 if changing a single land to water disconnect the island.",
"Otherwise return 2.",
"We can disconnect the grid within at most 2 days."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var minDays = function(grid) {
}; | You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's.
The grid is said to be connected if we have exactly one island, otherwise is said disconnected.
In one day, we are allowed to change any single land cell (1) into a water cell (0).
Return the minimum number of days to disconnect the grid.
Example 1:
Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]
Output: 2
Explanation: We need at least 2 days to get a disconnected grid.
Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island.
Example 2:
Input: grid = [[1,1]]
Output: 2
Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 30
grid[i][j] is either 0 or 1.
| Hard | [
"array",
"depth-first-search",
"breadth-first-search",
"matrix",
"strongly-connected-component"
] | [
"const minDays = function (grid) {\n if (!grid.length || !grid[0].length) return 0\n if (numIslands(grid) != 1) return 0\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[0].length; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0\n if (numIslands(grid) != 1) return 1\n grid[i][j] = 1\n }\n }\n }\n return 2\n}\n\nfunction numIslands(grid) {\n let m = Array.from({ length: grid.length }, (v, i) => {\n return [...grid[i]]\n })\n let count = 0\n for (let i = 0; i < m.length; i++)\n for (let j = 0; j < m[0].length; j++) removeIslandAt(i, j, 1)\n return count\n function removeIslandAt(i, j, firstIteration = 0) {\n if (i >= m.length || j >= m[0].length || i < 0 || j < 0 || m[i][j] == 0)\n return\n m[i][j] = 0\n count += firstIteration\n removeIslandAt(i - 1, j)\n removeIslandAt(i + 1, j)\n removeIslandAt(i, j - 1)\n removeIslandAt(i, j + 1)\n }\n}"
] |
|
1,569 | number-of-ways-to-reorder-array-to-get-same-bst | [
"Use a divide and conquer strategy.",
"The first number will always be the root. Consider the numbers smaller and larger than the root separately. When merging the results together, how many ways can you order x elements in x+y positions?"
] | /**
* @param {number[]} nums
* @return {number}
*/
var numOfWays = function(nums) {
}; | Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums.
For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST.
Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: nums = [2,1,3]
Output: 1
Explanation: We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.
Example 2:
Input: nums = [3,4,5,1,2]
Output: 5
Explanation: The following 5 arrays will yield the same BST:
[3,1,2,4,5]
[3,1,4,2,5]
[3,1,4,5,2]
[3,4,1,2,5]
[3,4,1,5,2]
Example 3:
Input: nums = [1,2,3]
Output: 0
Explanation: There are no other orderings of nums that will yield the same BST.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= nums.length
All integers in nums are distinct.
| Hard | [
"array",
"math",
"divide-and-conquer",
"dynamic-programming",
"tree",
"union-find",
"binary-search-tree",
"memoization",
"combinatorics",
"binary-tree"
] | [
"const numOfWays = function (nums) {\n let root = null\n let cache = new Map()\n\n const MOD = BigInt(10 ** 9 + 7)\n for (let n of nums) {\n root = insert(root, n)\n }\n\n // f(root) -> [length, combination]\n function f(root) {\n if (!root.left && !root.right) {\n return [1n, 1n]\n }\n let [ll, lc] = [0n, 1n]\n let [rl, rc] = [0n, 1n]\n if (root.left) {\n ;[ll, lc] = f(root.left)\n }\n if (root.right) {\n ;[rl, rc] = f(root.right)\n }\n // ((ll + rl)! / (ll! * rl!) )* lc * rc\n return [\n ll + rl + 1n,\n (factorial(ll + rl) / factorial(ll) / factorial(rl)) * lc * rc,\n ]\n }\n\n return (f(root)[1] - 1n) % MOD\n\n function Node(val) {\n this.val = val\n this.left = this.right = null\n }\n\n function insert(root, val) {\n if (!root) {\n return new Node(val)\n }\n if (root.val > val) {\n root.left = insert(root.left, val)\n } else if (root.val < val) {\n root.right = insert(root.right, val)\n }\n return root\n }\n\n function factorial(n) {\n if (n == 0n) {\n return 1n\n }\n if (cache.has(n)) {\n return cache.get(n)\n }\n let ans = 1n\n for (let i = 2n; i <= n; i++) {\n ans *= i\n cache.set(i, ans)\n }\n return ans\n }\n}"
] |
|
1,572 | matrix-diagonal-sum | [
"There will be overlap of elements in the primary and secondary diagonals if and only if the length of the matrix is odd, which is at the center."
] | /**
* @param {number[][]} mat
* @return {number}
*/
var diagonalSum = function(mat) {
}; | Given a square matrix mat, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
Example 1:
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.
Example 2:
Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8
Example 3:
Input: mat = [[5]]
Output: 5
Constraints:
n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100
| Easy | [
"array",
"matrix"
] | [
"const diagonalSum = function(mat) {\n let res = 0, n = mat.length\n for(let i = 0; i < n; i++) {\n const j = i, ii = i, jj = n - 1 - i\n if(j == jj) res += mat[i][j]\n else {\n res += mat[i][j] + mat[ii][jj]\n }\n }\n \n return res\n};"
] |
|
1,573 | number-of-ways-to-split-a-string | [
"There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0.",
"Preffix s1 , and suffix s3 should have sum/3 characters '1'.",
"Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?"
] | /**
* @param {string} s
* @return {number}
*/
var numWays = function(s) {
}; | Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s.
Return the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: s = "10101"
Output: 4
Explanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'.
"1|010|1"
"1|01|01"
"10|10|1"
"10|1|01"
Example 2:
Input: s = "1001"
Output: 0
Example 3:
Input: s = "0000"
Output: 3
Explanation: There are three ways to split s in 3 parts.
"0|0|00"
"0|00|0"
"00|0|0"
Constraints:
3 <= s.length <= 105
s[i] is either '0' or '1'.
| Medium | [
"math",
"string"
] | [
"const numWays = function(s) {\n const n = s.length\n const cnt = Array(n).fill(0)\n let num = 0\n for(let i = 0; i < n; i++) {\n if(s[i] === '1') num++\n cnt[i] = num\n }\n const mod = 1e9 + 7\n let i0 = -1, i1 = -1, i2 = -1, i3 = -1\n for(let i = 0; i < n; i++) {\n if(cnt[i] === num / 3) {\n if(i0 === -1) i0 = i1 = i\n else i1 = i\n } else if(cnt[i] === 2 * num / 3) {\n if(i2 === -1) i2 = i3 = i\n else i3 = i\n }\n }\n if(num === 0) return (n - 1) * (n - 2) / 2 % mod\n if(i0 === -1 || i1 === -1 || i2 === -1 || i3 === -1) return 0\n\n return (i1 - i0 + 1) * (i3 - i2 + 1) % mod\n};"
] |
|
1,574 | shortest-subarray-to-be-removed-to-make-array-sorted | [
"The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively.",
"After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix."
] | /**
* @param {number[]} arr
* @return {number}
*/
var findLengthOfShortestSubarray = function(arr) {
}; | Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
Return the length of the shortest subarray to remove.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Constraints:
1 <= arr.length <= 105
0 <= arr[i] <= 109
| Medium | [
"array",
"two-pointers",
"binary-search",
"stack",
"monotonic-stack"
] | [
"const findLengthOfShortestSubarray = function (arr) {\n const n = arr.length\n let left = 0\n for(let i = 0; i < n - 1; i++) {\n if(arr[i] > arr[i+ 1]) {\n break\n }\n left = i + 1\n }\n\n let right = n - 1\n for(let i = n - 1; i > 0; i--) {\n if(arr[i] < arr[i - 1]) {\n break\n }\n right = i - 1\n }\n // console.log(left, right)\n if(left === n - 1) return 0\n\n let res = Math.min(n - 1 - left, right)\n let l = 0, r = right\n while(l <= left && r < n) {\n if(arr[l] <= arr[r]) {\n res = Math.min(res, r - 1 - l)\n l++\n } else {\n r++\n }\n }\n\n return res\n}"
] |
|
1,575 | count-all-possible-routes | [
"Use dynamic programming to solve this problem with each state defined by the city index and fuel left.",
"Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles."
] | /**
* @param {number[]} locations
* @param {number} start
* @param {number} finish
* @param {number} fuel
* @return {number}
*/
var countRoutes = function(locations, start, finish, fuel) {
}; | You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively.
At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x.
Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish).
Return the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5
Output: 4
Explanation: The following are all possible routes, each uses 5 units of fuel:
1 -> 3
1 -> 2 -> 3
1 -> 4 -> 3
1 -> 4 -> 2 -> 3
Example 2:
Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6
Output: 5
Explanation: The following are all possible routes:
1 -> 0, used fuel = 1
1 -> 2 -> 0, used fuel = 5
1 -> 2 -> 1 -> 0, used fuel = 5
1 -> 0 -> 1 -> 0, used fuel = 3
1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5
Example 3:
Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3
Output: 0
Explanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.
Constraints:
2 <= locations.length <= 100
1 <= locations[i] <= 109
All integers in locations are distinct.
0 <= start, finish < locations.length
1 <= fuel <= 200
| Hard | [
"array",
"dynamic-programming",
"memoization"
] | [
"const countRoutes = function (locations, start, finish, fuel) {\n const n = locations.length\n const mod = 10 ** 9 + 7\n const dp = Array.from({ length: n }, () => Array(fuel + 1).fill(-1))\n return solve(start, finish, fuel)\n function solve(curCity, e, fuel) {\n if (fuel < 0) return 0\n if (dp[curCity][fuel] !== -1) return dp[curCity][fuel]\n let ans = curCity === e ? 1 : 0\n for (let nextCity = 0; nextCity < locations.length; nextCity++) {\n if (nextCity !== curCity) {\n ans +=\n solve(\n nextCity,\n e,\n fuel - Math.abs(locations[curCity] - locations[nextCity])\n ) % mod\n }\n }\n return (dp[curCity][fuel] = ans % mod)\n }\n}"
] |
|
1,576 | replace-all-s-to-avoid-consecutive-repeating-characters | [
"Processing string from left to right, whenever you get a ‘?’, check left character and right character, and select a character not equal to either of them",
"Do take care to compare with replaced occurrence of ‘?’ when checking the left character."
] | /**
* @param {string} s
* @return {string}
*/
var modifyString = function(s) {
}; | Given a string s containing only lowercase English letters and the '?' character, convert all the '?' characters into lowercase letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters.
It is guaranteed that there are no consecutive repeating characters in the given string except for '?'.
Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints.
Example 1:
Input: s = "?zs"
Output: "azs"
Explanation: There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs".
Example 2:
Input: s = "ubv?w"
Output: "ubvaw"
Explanation: There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww".
Constraints:
1 <= s.length <= 100
s consist of lowercase English letters and '?'.
| Easy | [
"string"
] | [
"const modifyString = function(s) {\n const arr = s.split('')\n for(let i = 0, n = s.length; i < n; i++) {\n const cur = arr[i]\n if(cur === '?') {\n for(let j = 0, a = 'a'.charCodeAt(0); j < 26; j++) {\n const ch = String.fromCharCode(a + j)\n if(\n n === 1 ||\n (i === 0 && i < n - 1 && ch !== arr[i + 1]) ||\n (i > 0 && ch !== arr[i - 1] && i < n - 1 && ch !== arr[i + 1]) ||\n (i=== n -1 && i - 1 >= 0 && ch !== arr[i - 1])\n ) {\n \n arr[i] = ch\n break\n }\n }\n }\n }\n \n return arr.join('')\n};",
"const modifyString = function(s) {\n const arr = s.split('')\n for(let i = 0, n = s.length; i < n; i++) {\n const cur = arr[i]\n if(cur === '?') {\n for(let j = 0, a = 'a'.charCodeAt(0); j < 26; j++) {\n const ch = String.fromCharCode(a + j)\n if(\n (i === 0 || arr[i - 1] !== ch) &&\n (i === n - 1 || arr[i + 1] !== ch)\n ) {\n \n arr[i] = ch\n break\n }\n }\n }\n }\n \n return arr.join('')\n};"
] |
|
1,577 | number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers | [
"Precalculate the frequencies of all nums1[i]^2 and nums2[i]^2"
] | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var numTriplets = function(nums1, nums2) {
}; | Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:
Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length.
Type 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length.
Example 1:
Input: nums1 = [7,4], nums2 = [5,2,8,9]
Output: 1
Explanation: Type 1: (1, 1, 2), nums1[1]2 = nums2[1] * nums2[2]. (42 = 2 * 8).
Example 2:
Input: nums1 = [1,1], nums2 = [1,1,1]
Output: 9
Explanation: All Triplets are valid, because 12 = 1 * 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]2 = nums2[j] * nums2[k].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2 = nums1[j] * nums1[k].
Example 3:
Input: nums1 = [7,7,8,3], nums2 = [1,2,9,7]
Output: 2
Explanation: There are 2 valid triplets.
Type 1: (3,0,2). nums1[3]2 = nums2[0] * nums2[2].
Type 2: (3,0,1). nums2[3]2 = nums1[0] * nums1[1].
Constraints:
1 <= nums1.length, nums2.length <= 1000
1 <= nums1[i], nums2[i] <= 105
| Medium | [
"array",
"hash-table",
"math",
"two-pointers"
] | null | [] |
1,578 | minimum-time-to-make-rope-colorful | [
"Maintain the running sum and max value for repeated letters."
] | /**
* @param {string} colors
* @param {number[]} neededTime
* @return {number}
*/
var minCost = function(colors, neededTime) {
}; | Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon.
Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope.
Return the minimum time Bob needs to make the rope colorful.
Example 1:
Input: colors = "abaac", neededTime = [1,2,3,4,5]
Output: 3
Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.
Bob can remove the blue balloon at index 2. This takes 3 seconds.
There are no longer two consecutive balloons of the same color. Total time = 3.
Example 2:
Input: colors = "abc", neededTime = [1,2,3]
Output: 0
Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.
Example 3:
Input: colors = "aabaa", neededTime = [1,2,3,4,1]
Output: 2
Explanation: Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.
There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.
Constraints:
n == colors.length == neededTime.length
1 <= n <= 105
1 <= neededTime[i] <= 104
colors contains only lowercase English letters.
| Medium | [
"array",
"string",
"dynamic-programming",
"greedy"
] | [
"const minCost = function (s, cost) {\n let stackPointer = 0\n let minVal = 0\n for (let i = 1; i < s.length; i++) {\n if (s[i - 1] === s[i]) {\n if (cost[stackPointer] < cost[i]) {\n minVal += cost[stackPointer]\n stackPointer = i\n } else {\n minVal += cost[i]\n }\n } else {\n stackPointer = i\n }\n }\n return minVal\n}"
] |
|
1,579 | remove-max-number-of-edges-to-keep-graph-fully-traversable | [
"Build the network instead of removing extra edges.",
"Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there?",
"Use disjoint set union data structure for both Alice and Bob.",
"Always use Type 3 edges first, and connect the still isolated ones using other edges."
] | /**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/
var maxNumEdgesToRemove = function(n, edges) {
}; | Alice and Bob have an undirected graph of n nodes and three types of edges:
Type 1: Can be traversed by Alice only.
Type 2: Can be traversed by Bob only.
Type 3: Can be traversed by both Alice and Bob.
Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.
Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph.
Example 1:
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
Output: 2
Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.
Example 2:
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]
Output: 0
Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.
Example 3:
Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]
Output: -1
Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.
Constraints:
1 <= n <= 105
1 <= edges.length <= min(105, 3 * n * (n - 1) / 2)
edges[i].length == 3
1 <= typei <= 3
1 <= ui < vi <= n
All tuples (typei, ui, vi) are distinct.
| Hard | [
"union-find",
"graph"
] | [
"const maxNumEdgesToRemove = function (n, edges) {\n edges.sort((a, b) => b[0] - a[0])\n let edgesAdded = 0\n const bob = new UnionFind(n)\n const alice = new UnionFind(n)\n for (let edge of edges) {\n let type = edge[0],\n one = edge[1],\n two = edge[2]\n switch (type) {\n case 3:\n edgesAdded += bob.unite(one, two) | alice.unite(one, two)\n break\n case 2:\n edgesAdded += bob.unite(one, two)\n break\n case 1:\n edgesAdded += alice.unite(one, two)\n break\n }\n }\n return bob.united() && alice.united() ? edges.length - edgesAdded : -1\n}\nclass UnionFind {\n constructor(n) {\n this.component = []\n this.distinctComponents = n\n for (let i = 0; i <= n; i++) this.component.push(i)\n }\n unite(a, b) {\n const ar = this.find(a)\n if (ar !== this.find(b)) {\n this.component[ar] = b\n this.distinctComponents--\n return true\n }\n return false\n }\n find(a) {\n if (this.component[a] != a) {\n this.component[a] = this.find(this.component[a])\n }\n return this.component[a]\n }\n united() {\n return this.distinctComponents === 1\n }\n}"
] |
|
1,582 | special-positions-in-a-binary-matrix | [
"Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1."
] | /**
* @param {number[][]} mat
* @return {number}
*/
var numSpecial = function(mat) {
}; | Given an m x n binary matrix mat, return the number of special positions in mat.
A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).
Example 1:
Input: mat = [[1,0,0],[0,0,1],[1,0,0]]
Output: 1
Explanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.
Example 2:
Input: mat = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
Explanation: (0, 0), (1, 1) and (2, 2) are special positions.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
mat[i][j] is either 0 or 1.
| Easy | [
"array",
"matrix"
] | null | [] |
1,583 | count-unhappy-friends | [
"Create a matrix “rank” where rank[i][j] holds how highly friend ‘i' views ‘j’. This allows for O(1) comparisons between people"
] | /**
* @param {number} n
* @param {number[][]} preferences
* @param {number[][]} pairs
* @return {number}
*/
var unhappyFriends = function(n, preferences, pairs) {
}; | You are given a list of preferences for n friends, where n is always even.
For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.
All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.
However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:
x prefers u over y, and
u prefers x over v.
Return the number of unhappy friends.
Example 1:
Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Output: 2
Explanation:
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
Example 2:
Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
Output: 0
Explanation: Both friends 0 and 1 are happy.
Example 3:
Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
Output: 4
Constraints:
2 <= n <= 500
n is even.
preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i] does not contain i.
All values in preferences[i] are unique.
pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
Each person is contained in exactly one pair.
| Medium | [
"array",
"simulation"
] | null | [] |
1,584 | min-cost-to-connect-all-points | [
"Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points.",
"The problem is now the cost of minimum spanning tree in graph with above edges."
] | /**
* @param {number[][]} points
* @return {number}
*/
var minCostConnectPoints = function(points) {
}; | You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].
The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
Example 1:
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Explanation:
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
Example 2:
Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
Constraints:
1 <= points.length <= 1000
-106 <= xi, yi <= 106
All pairs (xi, yi) are distinct.
| Medium | [
"array",
"union-find",
"graph",
"minimum-spanning-tree"
] | [
"const minCostConnectPoints = function(points) {\n let minIndex,minDistance=Number.MAX_SAFE_INTEGER,sum=0;\n let distanceMap={};\n let prevouslyTakenIndex = 0,taken=1,takenMap={};\n for(let i=1;i<points.length;i++){\n distanceMap[i]=Number.MAX_SAFE_INTEGER;\n }\n takenMap[prevouslyTakenIndex]=true;\n while(taken<points.length){\n minDistance=Number.MAX_SAFE_INTEGER;\n for(let i=1;i<points.length;i++){\n if(takenMap[i]!==undefined){\n continue;\n }\n let d = getDistance(prevouslyTakenIndex,i);\n distanceMap[i]=Math.min(distanceMap[i],d);\n if(distanceMap[i]<minDistance){\n minDistance = distanceMap[i];\n minIndex = i;\n }\n }\n sum+=minDistance;\n prevouslyTakenIndex = minIndex;\n takenMap[prevouslyTakenIndex]=true;\n taken++;\n }\n return sum;\n \n function getDistance(i,j){\n return Math.abs(points[i][0]-points[j][0])+Math.abs(points[i][1]-points[j][1])\n }\n};"
] |
|
1,585 | check-if-string-is-transformable-with-substring-sort-operations | [
"Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there?",
"Consider swapping adjacent characters to maintain relative ordering."
] | /**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isTransformable = function(s, t) {
}; | Given two strings s and t, transform string s into string t using the following operation any number of times:
Choose a non-empty substring in s and sort it in place so the characters are in ascending order.
For example, applying the operation on the underlined substring in "14234" results in "12344".
Return true if it is possible to transform s into t. Otherwise, return false.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "84532", t = "34852"
Output: true
Explanation: You can transform s into t using the following sort operations:
"84532" (from index 2 to 3) -> "84352"
"84352" (from index 0 to 2) -> "34852"
Example 2:
Input: s = "34521", t = "23415"
Output: true
Explanation: You can transform s into t using the following sort operations:
"34521" -> "23451"
"23451" -> "23415"
Example 3:
Input: s = "12345", t = "12435"
Output: false
Constraints:
s.length == t.length
1 <= s.length <= 105
s and t consist of only digits.
| Hard | [
"string",
"greedy",
"sorting"
] | [
"const isTransformable = function (s, t) {\n const offset = '0'.charCodeAt(0)\n const indices = Array.from({ length: 10 }, () => [])\n for (let i = s.length - 1; i >= 0; --i) {\n indices[s.charCodeAt(i) - offset].push(i)\n }\n for (const char of t) {\n const digit = char.charCodeAt(0) - offset\n if (indices[digit].length === 0) return false\n const pos = indices[digit][indices[digit].length - 1]\n for (let d = 0; d < digit; ++d) {\n if (indices[d].length && indices[d][indices[d].length - 1] < pos) {\n return false\n }\n }\n indices[digit].pop()\n }\n return true\n}"
] |
|
1,588 | sum-of-all-odd-length-subarrays | [
"You can brute force – try every (i,j) pair, and if the length is odd, go through and add the sum to the answer."
] | /**
* @param {number[]} arr
* @return {number}
*/
var sumOddLengthSubarrays = function(arr) {
}; | Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
Example 2:
Input: arr = [1,2]
Output: 3
Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.
Example 3:
Input: arr = [10,11,12]
Output: 66
Constraints:
1 <= arr.length <= 100
1 <= arr[i] <= 1000
Follow up:
Could you solve this problem in O(n) time complexity?
| Easy | [
"array",
"math",
"prefix-sum"
] | [
"const sumOddLengthSubarrays = function(arr) {\n const n = arr.length, pre = Array(n + 1).fill(0)\n for(let i = 0; i < n; i++) pre[i + 1] = pre[i] + arr[i]\n \n let res = 0\n let len = 1\n while(len <= n) {\n for(let i = 0; i <= n - len; i++) {\n res += pre[i + len] - pre[i] // len === 1: 1 - 0, 2 - 1\n // len === 3: 3 - 0, 6 - 3\n }\n \n len += 2\n }\n \n return res\n \n};"
] |
|
1,589 | maximum-sum-obtained-of-any-permutation | [
"Indexes with higher frequencies should be bound with larger values"
] | /**
* @param {number[]} nums
* @param {number[][]} requests
* @return {number}
*/
var maxSumRangeQuery = function(nums, requests) {
}; | We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed.
Return the maximum total sum of all requests among all permutations of nums.
Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]
Output: 19
Explanation: One permutation of nums is [2,1,3,4,5] with the following result:
requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8
requests[1] -> nums[0] + nums[1] = 2 + 1 = 3
Total sum: 8 + 3 = 11.
A permutation with a higher total sum is [3,5,4,2,1] with the following result:
requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11
requests[1] -> nums[0] + nums[1] = 3 + 5 = 8
Total sum: 11 + 8 = 19, which is the best that you can do.
Example 2:
Input: nums = [1,2,3,4,5,6], requests = [[0,1]]
Output: 11
Explanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].
Example 3:
Input: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]
Output: 47
Explanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].
Constraints:
n == nums.length
1 <= n <= 105
0 <= nums[i] <= 105
1 <= requests.length <= 105
requests[i].length == 2
0 <= starti <= endi < n
| Medium | [
"array",
"greedy",
"sorting",
"prefix-sum"
] | [
"const maxSumRangeQuery = function (nums, requests) {\n let res = 0\n const mod = 10 ** 9 + 7,\n n = nums.length\n const count = Array(n).fill(0)\n for (let r of requests) {\n count[r[0]] += 1\n if (r[1] + 1 < n) count[r[1] + 1] -= 1\n }\n for (let i = 1; i < n; i++) count[i] += count[i - 1]\n nums.sort((a, b) => a - b)\n count.sort((a, b) => a - b)\n for (let i = 0; i < n; ++i) res = (res + nums[i] * count[i]) % mod\n return res\n}",
"const maxSumRangeQuery = function (nums, requests) {\n const n = nums.length, arr = Array(n + 1).fill(0)\n for(let [s, e] of requests) {\n arr[s] += 1\n arr[e + 1] -= 1\n }\n for(let i = 0, cur = 0; i < n; i++) {\n cur += arr[i]\n arr[i] = cur\n }\n nums.sort((a, b) => b - a)\n arr.sort((a, b) => b - a)\n const mod = 1e9 + 7\n let res = 0\n for(let i = 0; i < n; i++) {\n if (arr[i] <= 0) break\n res = (res + nums[i] * arr[i]) % mod\n }\n return res\n}",
"const maxSumRangeQuery = function (nums, requests) {\n const n = nums.length\n\n const arr = Array(n + 1).fill(0) \n for(const [s, e] of requests) {\n arr[s] += 1\n arr[e + 1] -= 1\n }\n for(let i = 1; i <= n; i++) {\n arr[i] += arr[i - 1] \n }\n arr.sort((a, b) => b - a)\n nums.sort((a, b) => b - a)\n let res = 0\n const mod = 1e9 + 7\n \n for (let i = 0; i < n; i++) {\n if(arr[i] <= 0) break\n res = (res + nums[i] * arr[i]) % mod\n }\n \n return res\n}"
] |
|
1,590 | make-sum-divisible-by-p | [
"Use prefix sums to calculate the subarray sums.",
"Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k?",
"Use a map to keep track of the rightmost index for every prefix sum % p."
] | /**
* @param {number[]} nums
* @param {number} p
* @return {number}
*/
var minSubarray = function(nums, p) {
}; | Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.
Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.
A subarray is defined as a contiguous block of elements in the array.
Example 1:
Input: nums = [3,1,4,2], p = 6
Output: 1
Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.
Example 2:
Input: nums = [6,3,5,2], p = 9
Output: 2
Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.
Example 3:
Input: nums = [1,2,3], p = 3
Output: 0
Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= p <= 109
| Medium | [
"array",
"hash-table",
"prefix-sum"
] | [
"const minSubarray = function(nums, p) {\n const remain = nums.reduce((ac, e) => ac + e, 0) % p\n const n = nums.length, hash = {0: -1}\n let res = n\n if(remain === 0) return 0\n for(let i = 0, sum = 0; i < n; i++) {\n const cur = nums[i]\n sum += cur\n const target = (sum % p - remain + p) % p\n if(hash[target] != null) {\n res = Math.min(res, i - hash[target])\n }\n\n hash[sum % p] = i\n }\n// console.log(hash)\n \n return res === n ? -1 : res\n};",
"const minSubarray = function(nums, p) {\n const diff = nums.reduce((a, b) => a + b, 0) % p;\n let res = diff === 0 ? 0 : nums.length;\n \n for (let i = 0, sum = 0, map = {0: -1}; i < nums.length; i++) {\n sum += nums[i];\n const target = (sum % p - diff + p) % p;\n if (map[target] !== undefined) {\n res = Math.min(res, i - map[target]);\n }\n map[sum % p] = i;\n }\n \n return res === nums.length ? -1 : res;\n};"
] |
|
1,591 | strange-printer-ii | [
"Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?"
] | /**
* @param {number[][]} targetGrid
* @return {boolean}
*/
var isPrintable = function(targetGrid) {
}; | There is a strange printer with the following two special requirements:
On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
Once the printer has used a color for the above operation, the same color cannot be used again.
You are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position (row, col) of the grid.
Return true if it is possible to print the matrix targetGrid, otherwise, return false.
Example 1:
Input: targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]
Output: true
Example 2:
Input: targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]
Output: true
Example 3:
Input: targetGrid = [[1,2,1],[2,1,2],[1,2,1]]
Output: false
Explanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns.
Constraints:
m == targetGrid.length
n == targetGrid[i].length
1 <= m, n <= 60
1 <= targetGrid[row][col] <= 60
| Hard | [
"array",
"graph",
"topological-sort",
"matrix"
] | [
"const isPrintable = function (targetGrid) {\n const posMin = Array.from({ length: 61 }, () => Array(2).fill(61))\n const posMax = Array.from({ length: 61 }, () => Array(2).fill(0))\n const m = targetGrid.length\n const n = targetGrid[0].length\n let colorSet = new Set()\n\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n let c = targetGrid[i][j]\n colorSet.add(c)\n posMin[c][0] = Math.min(posMin[c][0], i) //Up\n posMin[c][1] = Math.min(posMin[c][1], j) //Left\n posMax[c][0] = Math.max(posMax[c][0], i) //Down\n posMax[c][1] = Math.max(posMax[c][1], j) //Right\n }\n }\n while (colorSet.size) {\n const tmp = new Set()\n for (let color of colorSet) {\n if (!isRect(targetGrid, color)) {\n tmp.add(color)\n }\n }\n\n if (tmp.size === colorSet.size) return false\n colorSet = tmp\n }\n\n return true\n\n function isRect(A, c) {\n for (let i = posMin[c][0]; i <= posMax[c][0]; i++) {\n for (let j = posMin[c][1]; j <= posMax[c][1]; j++) {\n if (A[i][j] > 0 && A[i][j] !== c) return false\n }\n }\n\n for (let i = posMin[c][0]; i <= posMax[c][0]; i++) {\n for (let j = posMin[c][1]; j <= posMax[c][1]; j++) {\n A[i][j] = 0\n }\n }\n\n return true\n }\n}",
"const isPrintable = function (targetGrid) {\n \n\n const dependencies = {}\n\n \n const extents = {}\n\n for (let i = 0; i < targetGrid.length; i++) {\n for (let j = 0; j < targetGrid[i].length; j++) {\n const n = targetGrid[i][j]\n let inf = Infinity\n extents[n] = extents[n] || {\n n,\n mini: inf,\n minj: inf,\n maxi: -inf,\n maxj: -inf,\n }\n extents[n].mini = Math.min(i, extents[n].mini)\n extents[n].minj = Math.min(j, extents[n].minj)\n extents[n].maxi = Math.max(i, extents[n].maxi)\n extents[n].maxj = Math.max(j, extents[n].maxj)\n }\n }\n\n function canRemove(obj) {\n for (let i = obj.mini; i <= obj.maxi; i++) {\n for (let j = obj.minj; j <= obj.maxj; j++) {\n const val = targetGrid[i][j]\n if (val !== null && val !== obj.n) return false\n }\n }\n return true\n }\n\n function remove(obj) {\n for (let i = obj.mini; i <= obj.maxi; i++) {\n for (let j = obj.minj; j <= obj.maxj; j++) {\n targetGrid[i][j] = null\n }\n }\n delete extents[obj.n]\n }\n\n while (Object.keys(extents).length > 0) {\n let found = false\n for (const n in extents) {\n const obj = extents[n]\n if (canRemove(obj)) {\n remove(obj)\n found = true\n break\n }\n }\n if (!found) {\n return false\n }\n }\n return true\n}"
] |
|
1,592 | rearrange-spaces-between-words | [
"Count the total number of spaces and words. Then use the integer division to determine the numbers of spaces to add between each word and at the end."
] | /**
* @param {string} text
* @return {string}
*/
var reorderSpaces = function(text) {
}; | You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.
Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.
Return the string after rearranging the spaces.
Example 1:
Input: text = " this is a sentence "
Output: "this is a sentence"
Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.
Example 2:
Input: text = " practice makes perfect"
Output: "practice makes perfect "
Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.
Constraints:
1 <= text.length <= 100
text consists of lowercase English letters and ' '.
text contains at least one word.
| Easy | [
"string"
] | [
"const reorderSpaces = function(text) {\n let sc = 0\n for(let i = 0, len = text.length; i < len; i++) {\n if(text[i] === ' ') sc++\n }\n const arr = text.split(' ').filter(e => e!= '')\n const num = arr.length - 1\n const remain = num === 0 ? sc : sc % num\n const split = num === 0 ? 0 : Array( (sc / num) >> 0 ).fill(0).reduce((ac, el) => ac + ' ', '')\n let res = ''\n res = arr.join(split) + helper(remain)\n return res\n};\n\nfunction helper(n) {\n let res = ''\n for(let i = 0; i < n; i++) res += ' '\n return res\n}"
] |
|
1,593 | split-a-string-into-the-max-number-of-unique-substrings | [
"Use a set to keep track of which substrings have been used already",
"Try each possible substring at every position and backtrack if a complete split is not possible"
] | /**
* @param {string} s
* @return {number}
*/
var maxUniqueSplit = function(s) {
}; | Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
| Medium | [
"hash-table",
"string",
"backtracking"
] | [
"const maxUniqueSplit = function(s) {\n return bt(s, '', 0, new Set())\n};\n\nfunction bt(str, cur, idx, useds) {\n if(idx === str.length) return useds.size\n cur += str[idx]\n if(useds.has(cur)) return bt(str, cur, idx +1, useds)\n else {\n let ans = 0\n useds.add(cur)\n ans = Math.max(ans, bt(str, '', idx+1, useds))\n useds.delete(cur)\n ans = Math.max(ans, bt(str, cur, idx+1, useds))\n return ans\n }\n}",
"const maxUniqueSplit = function (s) {\n const N = s.length\n let ans = -1\n let curr = new Set()\n const backtrack = (pos) => {\n if (pos === N) {\n ans = Math.max(ans, curr.size)\n return\n }\n if (curr.size + (N - pos) <= ans) return\n for (let i = pos + 1; i <= N; i++) {\n const a = s.slice(pos, i)\n if (curr.has(a)) continue\n curr.add(a)\n backtrack(i)\n curr.delete(a)\n }\n }\n\n backtrack(0)\n return ans\n}"
] |
|
1,594 | maximum-non-negative-product-in-a-matrix | [
"Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var maxProductPath = function(grid) {
}; | You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix.
Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path.
Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1.
Notice that the modulo is performed after getting the maximum product.
Example 1:
Input: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]
Output: -1
Explanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.
Example 2:
Input: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]
Output: 8
Explanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).
Example 3:
Input: grid = [[1,3],[0,-4]]
Output: 0
Explanation: Maximum non-negative product is shown (1 * 0 * -4 = 0).
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 15
-4 <= grid[i][j] <= 4
| Medium | [
"array",
"dynamic-programming",
"matrix"
] | [
"const maxProductPath = function (grid) {\n const m = grid.length,\n n = grid[0].length,\n MOD = 1e9 + 7;\n const mx = Array.from({ length: m }, () => Array(n).fill(0));\n const mn = Array.from({ length: m }, () => Array(n).fill(0));\n mx[0][0] = mn[0][0] = grid[0][0];\n\n // initialize the top and left sides\n for (let i = 1; i < m; i++) {\n mn[i][0] = mx[i][0] = mx[i - 1][0] * grid[i][0];\n }\n for (let j = 1; j < n; j++) {\n mn[0][j] = mx[0][j] = mx[0][j - 1] * grid[0][j];\n }\n\n for (let i = 1; i < m; i++) {\n for (let j = 1; j < n; j++) {\n if (grid[i][j] < 0) {\n // smallest negative * negative number = largest\n mx[i][j] = Math.min(mn[i - 1][j], mn[i][j - 1]) * grid[i][j];\n mn[i][j] = Math.max(mx[i - 1][j], mx[i][j - 1]) * grid[i][j];\n } else {\n // largest product * positive number = largest\n mx[i][j] = Math.max(mx[i - 1][j], mx[i][j - 1]) * grid[i][j];\n mn[i][j] = Math.min(mn[i - 1][j], mn[i][j - 1]) * grid[i][j];\n }\n }\n }\n\n let ans = mx[m - 1][n - 1] % MOD;\n return ans < 0 ? -1 : ans;\n};"
] |
|
1,595 | minimum-cost-to-connect-two-groups-of-points | [
"Each point on the left would either be connected to exactly point already connected to some left node, or a subset of the nodes on the right which are not connected to any node",
"Use dynamic programming with bitmasking, where the state will be (number of points assigned in first group, bitmask of points assigned in second group)."
] | /**
* @param {number[][]} cost
* @return {number}
*/
var connectTwoGroups = function(cost) {
}; | You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2.
The cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.
Return the minimum cost it takes to connect the two groups.
Example 1:
Input: cost = [[15, 96], [36, 2]]
Output: 17
Explanation: The optimal way of connecting the groups is:
1--A
2--B
This results in a total cost of 17.
Example 2:
Input: cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]
Output: 4
Explanation: The optimal way of connecting the groups is:
1--A
2--B
2--C
3--A
This results in a total cost of 4.
Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.
Example 3:
Input: cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]
Output: 10
Constraints:
size1 == cost.length
size2 == cost[i].length
1 <= size1, size2 <= 12
size1 >= size2
0 <= cost[i][j] <= 100
| Hard | [
"array",
"dynamic-programming",
"bit-manipulation",
"matrix",
"bitmask"
] | [
"const connectTwoGroups = function(cost) {\n const m = cost.length, n = cost[0].length, { min } = Math\n const limit = 1 << n\n const dp = Array.from({ length: m + 1 }, () => Array(limit).fill(Infinity))\n const subCost = Array.from({ length: m + 1 }, () => Array(limit).fill(Infinity))\n \n for(let i = 0; i < m; i++) {\n for(let mask = 0; mask < limit; mask++) {\n let sum = 0\n for(let j = 0; j < n; j++) {\n if((mask >> j) & 1) {\n sum += cost[i][j]\n }\n }\n \n subCost[i][mask] = sum\n }\n }\n \n dp[0][0] = 0\n for(let i = 1; i <= m; i++) {\n for(let mask = 0; mask < limit; mask++) {\n for(let sub = mask; sub; sub = (sub - 1) & mask) {\n dp[i][mask] = min(\n dp[i][mask],\n dp[i - 1][mask - sub] + subCost[i - 1][sub]\n )\n }\n let tmp = Infinity\n for(let j = 0; j < n; j++) {\n tmp = min(tmp, cost[i - 1][j])\n }\n \n dp[i][mask] = min(dp[i][mask], dp[i - 1][mask] + tmp)\n }\n }\n // console.log(dp)\n return dp[m][limit - 1]\n};",
"const connectTwoGroups = function (cost) {\n const min = Array(cost[0].length).fill(Infinity)\n for (let j = 0; j < min.length; j++) {\n for (let i = 0; i < cost.length; i++) {\n min[j] = Math.min(min[j], cost[i][j])\n }\n }\n const dp = Array.from({ length: 13 }, () => Array(4096).fill(-1))\n return dfs(cost, min, 0, 0, dp)\n}\n\nfunction dfs(cost, min, i, mask, dp) {\n if (dp[i][mask] !== -1) return dp[i][mask]\n let res = i >= cost.length ? 0 : Infinity\n if (i >= cost.length) {\n for (let j = 0; j < cost[0].length; j++) {\n if ((mask & (1 << j)) === 0) res += min[j]\n }\n } else {\n for (let j = 0; j < cost[0].length; j++) {\n res = Math.min(\n res,\n cost[i][j] + dfs(cost, min, i + 1, mask | (1 << j), dp)\n )\n }\n }\n dp[i][mask] = res\n return res\n}",
"const connectTwoGroups = function (cost) {\n const n = cost.length\n const m = cost[0].length\n const con = 1 << m\n const dp = Array(n + 1)\n .fill(null)\n .map(() => Array(con).fill(0))\n const min = Array(m).fill(Infinity)\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n min[j] = Math.min(min[j], cost[i][j])\n }\n }\n function dfs(i, mask) {\n let res\n if (dp[i][mask]) {\n return dp[i][mask]\n } else if (i >= n) {\n res = 0\n for (let j = 0; j < m; j++) {\n const binaryJ = 1 << j\n if ((mask & binaryJ) === 0) res += min[j]\n }\n } else {\n res = Infinity\n for (let j = 0; j < m; j++) {\n const binaryJ = 1 << j\n res = Math.min(res, cost[i][j] + dfs(i + 1, mask | binaryJ))\n }\n }\n dp[i][mask] = res\n return res\n }\n return dfs(0, 0)\n}"
] |
|
1,598 | crawler-log-folder | [
"Simulate the process but don’t move the pointer beyond the main folder.",
"Simulate the process but don’t move the pointer beyond the main folder."
] | /**
* @param {string[]} logs
* @return {number}
*/
var minOperations = function(logs) {
}; | The Leetcode file system keeps a log each time some user performs a change folder operation.
The operations are described below:
"../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder).
"./" : Remain in the same folder.
"x/" : Move to the child folder named x (This folder is guaranteed to always exist).
You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.
The file system starts in the main folder, then the operations in logs are performed.
Return the minimum number of operations needed to go back to the main folder after the change folder operations.
Example 1:
Input: logs = ["d1/","d2/","../","d21/","./"]
Output: 2
Explanation: Use this change folder operation "../" 2 times and go back to the main folder.
Example 2:
Input: logs = ["d1/","d2/","./","d3/","../","d31/"]
Output: 3
Example 3:
Input: logs = ["d1/","../","../","../"]
Output: 0
Constraints:
1 <= logs.length <= 103
2 <= logs[i].length <= 10
logs[i] contains lowercase English letters, digits, '.', and '/'.
logs[i] follows the format described in the statement.
Folder names consist of lowercase English letters and digits.
| Easy | [
"array",
"string",
"stack"
] | [
"const minOperations = function(logs) {\n const stack = []\n for(let i = 0, len = logs.length; i < len; i++) {\n const e= logs[i]\n if(e === '../') {\n stack.pop()\n } else if (e === './') {\n \n } else {\n stack.push(e)\n }\n }\n return stack.length\n};"
] |
|
1,599 | maximum-profit-of-operating-a-centennial-wheel | [
"Think simulation",
"Note that the number of turns will never be more than 50 / 4 * n"
] | /**
* @param {number[]} customers
* @param {number} boardingCost
* @param {number} runningCost
* @return {number}
*/
var minOperationsMaxProfit = function(customers, boardingCost, runningCost) {
}; | You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost dollars.
You are given an array customers of length n where customers[i] is the number of new customers arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again.
You can stop the wheel at any time, including before serving all customers. If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation.
Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1.
Example 1:
Input: customers = [8,3], boardingCost = 5, runningCost = 6
Output: 3
Explanation: The numbers written on the gondolas are the number of people currently there.
1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.
2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.
3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.
The highest profit was $37 after rotating the wheel 3 times.
Example 2:
Input: customers = [10,9,6], boardingCost = 6, runningCost = 4
Output: 7
Explanation:
1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.
2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.
3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.
4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.
5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.
6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.
7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.
The highest profit was $122 after rotating the wheel 7 times.
Example 3:
Input: customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92
Output: -1
Explanation:
1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.
2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.
3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.
4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.
5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.
The profit was never positive, so return -1.
Constraints:
n == customers.length
1 <= n <= 105
0 <= customers[i] <= 50
1 <= boardingCost, runningCost <= 100
| Medium | [
"array",
"simulation"
] | [
"const minOperationsMaxProfit = function(customers, boardingCost, runningCost) {\n let remain = 0\n let profit = 0\n let cost = 0\n let max = -Infinity\n let maxNum = 0\n for(let i = 0, len = customers.length; i < len; i++) {\n const e = customers[i]\n remain += e\n const cur = (remain >= 4 ? 4 : remain)\n remain -= cur\n profit += cur * boardingCost - runningCost\n if(profit > max) maxNum++\n max = Math.max(max, profit)\n }\n if(remain) {\n const r = Math.floor(remain / 4)\n const single = 4 * boardingCost - runningCost\n remain = remain % 4\n // profit += (single * r + (remain > 0 ? (remain * boardingCost - runningCost) : 0))\n profit += single * r\n if(single > 0) maxNum += r\n max = Math.max(max, profit)\n if (remain < 4) {\n const tmp = remain * boardingCost - runningCost\n profit += tmp\n remain = 0\n if(profit > max) maxNum++\n max = Math.max(max, profit)\n }\n }\n if (max <=0 )return -1\n return maxNum\n};"
] |
|
1,600 | throne-inheritance | [
"Create a tree structure of the family.",
"Without deaths, the order of inheritance is simply a pre-order traversal of the tree.",
"Mark the dead family members tree nodes and don't include them in the final order."
] | /**
* @param {string} kingName
*/
var ThroneInheritance = function(kingName) {
};
/**
* @param {string} parentName
* @param {string} childName
* @return {void}
*/
ThroneInheritance.prototype.birth = function(parentName, childName) {
};
/**
* @param {string} name
* @return {void}
*/
ThroneInheritance.prototype.death = function(name) {
};
/**
* @return {string[]}
*/
ThroneInheritance.prototype.getInheritanceOrder = function() {
};
/**
* Your ThroneInheritance object will be instantiated and called as such:
* var obj = new ThroneInheritance(kingName)
* obj.birth(parentName,childName)
* obj.death(name)
* var param_3 = obj.getInheritanceOrder()
*/ | A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.
The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance.
Successor(x, curOrder):
if x has no children or all of x's children are in curOrder:
if x is the king return null
else return Successor(x's parent, curOrder)
else return x's oldest child who's not in curOrder
For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.
In the beginning, curOrder will be ["king"].
Calling Successor(king, curOrder) will return Alice, so we append to curOrder to get ["king", "Alice"].
Calling Successor(Alice, curOrder) will return Jack, so we append to curOrder to get ["king", "Alice", "Jack"].
Calling Successor(Jack, curOrder) will return Bob, so we append to curOrder to get ["king", "Alice", "Jack", "Bob"].
Calling Successor(Bob, curOrder) will return null. Thus the order of inheritance will be ["king", "Alice", "Jack", "Bob"].
Using the above function, we can always obtain a unique order of inheritance.
Implement the ThroneInheritance class:
ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.
void birth(string parentName, string childName) Indicates that parentName gave birth to childName.
void death(string name) Indicates the death of name. The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.
string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people.
Example 1:
Input
["ThroneInheritance", "birth", "birth", "birth", "birth", "birth", "birth", "getInheritanceOrder", "death", "getInheritanceOrder"]
[["king"], ["king", "andy"], ["king", "bob"], ["king", "catherine"], ["andy", "matthew"], ["bob", "alex"], ["bob", "asha"], [null], ["bob"], [null]]
Output
[null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]]
Explanation
ThroneInheritance t= new ThroneInheritance("king"); // order: king
t.birth("king", "andy"); // order: king > andy
t.birth("king", "bob"); // order: king > andy > bob
t.birth("king", "catherine"); // order: king > andy > bob > catherine
t.birth("andy", "matthew"); // order: king > andy > matthew > bob > catherine
t.birth("bob", "alex"); // order: king > andy > matthew > bob > alex > catherine
t.birth("bob", "asha"); // order: king > andy > matthew > bob > alex > asha > catherine
t.getInheritanceOrder(); // return ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"]
t.death("bob"); // order: king > andy > matthew > bob > alex > asha > catherine
t.getInheritanceOrder(); // return ["king", "andy", "matthew", "alex", "asha", "catherine"]
Constraints:
1 <= kingName.length, parentName.length, childName.length, name.length <= 15
kingName, parentName, childName, and name consist of lowercase English letters only.
All arguments childName and kingName are distinct.
All name arguments of death will be passed to either the constructor or as childName to birth first.
For each call to birth(parentName, childName), it is guaranteed that parentName is alive.
At most 105 calls will be made to birth and death.
At most 10 calls will be made to getInheritanceOrder.
| Medium | [
"hash-table",
"tree",
"depth-first-search",
"design"
] | [
"const ThroneInheritance = function(kingName) {\n this.king = kingName\n this.m = {}\n this.dead = {}\n};\n\n\nThroneInheritance.prototype.birth = function(parentName, childName) {\n if(!this.m[parentName]) this.m[parentName] = []\n this.m[parentName].push(childName)\n};\n\n\nThroneInheritance.prototype.death = function(name) {\n this.dead[name] = 1\n};\n\n\nThroneInheritance.prototype.getInheritanceOrder = function() {\n const res = []\n this.dfs(res, this.king)\n return res\n};\nThroneInheritance.prototype.dfs = function(ans, root) {\n if (!this.dead[root]) {\n ans.push(root);\n }\n if(!this.m[root]) return\n for (let child of this.m[root]) {\n this.dfs(ans, child);\n }\n};"
] |
|
1,601 | maximum-number-of-achievable-transfer-requests | [
"Think brute force",
"When is a subset of requests okay?"
] | /**
* @param {number} n
* @param {number[][]} requests
* @return {number}
*/
var maximumRequests = function(n, requests) {
}; | We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.
You are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi.
All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2.
Return the maximum number of achievable requests.
Example 1:
Input: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]
Output: 5
Explantion: Let's see the requests:
From building 0 we have employees x and y and both want to move to building 1.
From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.
From building 2 we have employee z and they want to move to building 0.
From building 3 we have employee c and they want to move to building 4.
From building 4 we don't have any requests.
We can achieve the requests of users x and b by swapping their places.
We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.
Example 2:
Input: n = 3, requests = [[0,0],[1,2],[2,1]]
Output: 3
Explantion: Let's see the requests:
From building 0 we have employee x and they want to stay in the same building 0.
From building 1 we have employee y and they want to move to building 2.
From building 2 we have employee z and they want to move to building 1.
We can achieve all the requests.
Example 3:
Input: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]
Output: 4
Constraints:
1 <= n <= 20
1 <= requests.length <= 16
requests[i].length == 2
0 <= fromi, toi < n
| Hard | [
"array",
"backtracking",
"bit-manipulation",
"enumeration"
] | [
"// O(n * 2 ^ r) \n// r: number of requests\n\nconst maximumRequests = function(n, requests) {\n const arr = Array(n).fill(0)\n let res = 0\n bt(requests, 0, arr, 0)\n return res\n function bt(r, idx, arr, num) {\n if(idx === r.length) {\n for(let i = 0; i < n; i++) {\n if(arr[i] !== 0) return\n }\n res = Math.max(res, num)\n return\n }\n const [from, to] = r[idx]\n arr[from]++\n arr[to]--\n bt(r, idx + 1, arr, num + 1)\n arr[from]--\n arr[to]++\n \n bt(r, idx + 1, arr, num)\n }\n};",
"const maximumRequests = function (n, requests) {\n let max = 0\n helper(requests, 0, Array(n).fill(0), 0)\n return max\n\n function helper(requests, index, count, num) {\n // Traverse all n buildings to see if they are all 0. (means balanced)\n if (index === requests.length) {\n for (let i of count) {\n if (0 !== i) {\n return\n }\n }\n max = Math.max(max, num)\n return\n }\n // Choose this request\n count[requests[index][0]]++\n count[requests[index][1]]--\n helper(requests, index + 1, count, num + 1)\n count[requests[index][0]]--\n count[requests[index][1]]++\n\n // Not Choose the request\n helper(requests, index + 1, count, num)\n }\n}"
] |
|
1,603 | design-parking-system | [
"Record number of parking slots still available for each car type."
] | /**
* @param {number} big
* @param {number} medium
* @param {number} small
*/
var ParkingSystem = function(big, medium, small) {
};
/**
* @param {number} carType
* @return {boolean}
*/
ParkingSystem.prototype.addCar = function(carType) {
};
/**
* Your ParkingSystem object will be instantiated and called as such:
* var obj = new ParkingSystem(big, medium, small)
* var param_1 = obj.addCar(carType)
*/ | Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the ParkingSystem class:
ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.
bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its carType. If there is no space available, return false, else park the car in that size space and return true.
Example 1:
Input
["ParkingSystem", "addCar", "addCar", "addCar", "addCar"]
[[1, 1, 0], [1], [2], [3], [1]]
Output
[null, true, true, false, false]
Explanation
ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
parkingSystem.addCar(1); // return true because there is 1 available slot for a big car
parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car
parkingSystem.addCar(3); // return false because there is no available slot for a small car
parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.
Constraints:
0 <= big, medium, small <= 1000
carType is 1, 2, or 3
At most 1000 calls will be made to addCar
| Easy | [
"design",
"simulation",
"counting"
] | [
"const ParkingSystem = function(big, medium, small) {\n this['3'] = small\n this['2'] = medium\n this['1'] = big\n};\n\n\nParkingSystem.prototype.addCar = function(carType) {\n this[carType]--\n if(this[carType] < 0) {\n this[carType] = 0\n return false\n }\n return true\n};"
] |
|
1,604 | alert-using-same-key-card-three-or-more-times-in-a-one-hour-period | [
"Group the times by the name of the card user, then sort each group"
] | /**
* @param {string[]} keyName
* @param {string[]} keyTime
* @return {string[]}
*/
var alertNames = function(keyName, keyTime) {
}; | LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period.
You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day.
Access times are given in the 24-hour time format "HH:MM", such as "23:51" and "09:49".
Return a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically.
Notice that "10:00" - "11:00" is considered to be within a one-hour period, while "22:51" - "23:52" is not considered to be within a one-hour period.
Example 1:
Input: keyName = ["daniel","daniel","daniel","luis","luis","luis","luis"], keyTime = ["10:00","10:40","11:00","09:00","11:00","13:00","15:00"]
Output: ["daniel"]
Explanation: "daniel" used the keycard 3 times in a one-hour period ("10:00","10:40", "11:00").
Example 2:
Input: keyName = ["alice","alice","alice","bob","bob","bob","bob"], keyTime = ["12:01","12:00","18:00","21:00","21:20","21:30","23:00"]
Output: ["bob"]
Explanation: "bob" used the keycard 3 times in a one-hour period ("21:00","21:20", "21:30").
Constraints:
1 <= keyName.length, keyTime.length <= 105
keyName.length == keyTime.length
keyTime[i] is in the format "HH:MM".
[keyName[i], keyTime[i]] is unique.
1 <= keyName[i].length <= 10
keyName[i] contains only lowercase English letters.
| Medium | [
"array",
"hash-table",
"string",
"sorting"
] | null | [] |
1,605 | find-valid-matrix-given-row-and-column-sums | [
"Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied."
] | /**
* @param {number[]} rowSum
* @param {number[]} colSum
* @return {number[][]}
*/
var restoreMatrix = function(rowSum, colSum) {
}; | You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.
Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements.
Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists.
Example 1:
Input: rowSum = [3,8], colSum = [4,7]
Output: [[3,0],
[1,7]]
Explanation:
0th row: 3 + 0 = 3 == rowSum[0]
1st row: 1 + 7 = 8 == rowSum[1]
0th column: 3 + 1 = 4 == colSum[0]
1st column: 0 + 7 = 7 == colSum[1]
The row and column sums match, and all matrix elements are non-negative.
Another possible matrix is: [[1,2],
[3,5]]
Example 2:
Input: rowSum = [5,7,10], colSum = [8,6,8]
Output: [[0,5,0],
[6,1,0],
[2,0,8]]
Constraints:
1 <= rowSum.length, colSum.length <= 500
0 <= rowSum[i], colSum[i] <= 108
sum(rowSum) == sum(colSum)
| Medium | [
"array",
"greedy",
"matrix"
] | [
"const restoreMatrix = function(rowSum, colSum) {\n const m = rowSum.length, n = colSum.length;\n const res = Array.from({ length: m }, () => Array(n).fill(0));\n for (let i = 0; i < m; ++i) {\n for (let j = 0 ; j < n; ++j) {\n res[i][j] = Math.min(rowSum[i], colSum[j]);\n rowSum[i] -= res[i][j];\n colSum[j] -= res[i][j];\n }\n }\n return res;\n};",
"const restoreMatrix = function(rowSum, colSum) {\n const m = rowSum.length, n = colSum.length\n const res = Array.from({ length: m }, () => Array(n).fill(0))\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n res[i][j] = Math.min(rowSum[i], colSum[j])\n rowSum[i] -= res[i][j]\n colSum[j] -= res[i][j]\n }\n }\n return res\n};"
] |
|
1,606 | find-servers-that-handled-most-number-of-requests | [
"To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set.",
"To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add."
] | /**
* @param {number} k
* @param {number[]} arrival
* @param {number[]} load
* @return {number[]}
*/
var busiestServers = function(k, arrival, load) {
}; | You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm:
The ith (0-indexed) request arrives.
If all servers are busy, the request is dropped (not handled at all).
If the (i % k)th server is available, assign the request to that server.
Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the ith server is busy, try to assign the request to the (i+1)th server, then the (i+2)th server, and so on.
You are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the ith request, and another array load, where load[i] represents the load of the ith request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers.
Return a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.
Example 1:
Input: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3]
Output: [1]
Explanation:
All of the servers start out available.
The first 3 requests are handled by the first 3 servers in order.
Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.
Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped.
Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.
Example 2:
Input: k = 3, arrival = [1,2,3,4], load = [1,2,1,2]
Output: [0]
Explanation:
The first 3 requests are handled by first 3 servers.
Request 3 comes in. It is handled by server 0 since the server is available.
Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.
Example 3:
Input: k = 3, arrival = [1,2,3], load = [10,12,11]
Output: [0,1,2]
Explanation: Each server handles a single request, so they are all considered the busiest.
Constraints:
1 <= k <= 105
1 <= arrival.length, load.length <= 105
arrival.length == load.length
1 <= arrival[i], load[i] <= 109
arrival is strictly increasing.
| Hard | [
"array",
"greedy",
"heap-priority-queue",
"ordered-set"
] | [
"const busiestServers = function (k, arrival, load) {\n const ark = []\n const map = new Map()\n let max = 0\n for (let i = 0; i < arrival.length; i++) {\n if (i < k) {\n ark[i] = arrival[i] + load[i]\n map.set(i, 1)\n max = Math.max(max, map.get(i))\n } else {\n let server = i % k\n const curr = server\n while (server < k) {\n if (ark[server] <= arrival[i]) {\n ark[server] = arrival[i] + load[i]\n map.set(server, map.has(server) ? map.get(server) + 1 : 1)\n max = Math.max(max, map.get(server))\n break\n }\n server++\n }\n if (server === k) {\n let l = 0\n while (l < curr) {\n if (ark[l] <= arrival[i]) {\n ark[l] = arrival[i] + load[i]\n map.set(l, map.has(l) ? map.get(l) + 1 : 1)\n max = Math.max(max, map.get(l))\n break\n }\n l++\n }\n }\n }\n }\n\n const result = []\n const entries = map[Symbol.iterator]()\n for (let en of entries) {\n if (en[1] === max) {\n result.push(en[0])\n }\n }\n return result\n}"
] |
|
1,608 | special-array-with-x-elements-greater-than-or-equal-x | [
"Count the number of elements greater than or equal to x for each x in the range [0, nums.length].",
"If for any x, the condition satisfies, return that x. Otherwise, there is no answer."
] | /**
* @param {number[]} nums
* @return {number}
*/
var specialArray = function(nums) {
}; | You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.
Notice that x does not have to be an element in nums.
Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.
Example 1:
Input: nums = [3,5]
Output: 2
Explanation: There are 2 values (3 and 5) that are greater than or equal to 2.
Example 2:
Input: nums = [0,0]
Output: -1
Explanation: No numbers fit the criteria for x.
If x = 0, there should be 0 numbers >= x, but there are 2.
If x = 1, there should be 1 number >= x, but there are 0.
If x = 2, there should be 2 numbers >= x, but there are 0.
x cannot be greater since there are only 2 numbers in nums.
Example 3:
Input: nums = [0,4,3,0,4]
Output: 3
Explanation: There are 3 values that are greater than or equal to 3.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 1000
| Easy | [
"array",
"binary-search",
"sorting"
] | [
"const specialArray = function(nums) {\n let l = -1, r = 1001\n while(l <= r) {\n const mid = r - Math.floor((r - l) / 2)\n const tmp = valid(mid)\n if(tmp === mid) return mid\n else if(tmp > mid) l = mid + 1\n else r = mid - 1\n }\n return -1\n \n function valid(mid) {\n let res = 0\n for(let e of nums) {\n if(e >= mid) res++\n }\n return res\n }\n};",
"const specialArray = function (nums) {\n nums.sort((a, b) => b - a)\n let i = 0\n while(i < nums.length && nums[i] >= i) {\n i++\n }\n if(nums[i - 1] < i) return -1\n return i\n};",
"const specialArray = function(nums) {\n nums.sort((a, b) => b - a)\n let left = 0, right = nums.length\n while(left <= right) {\n const mid = left + ((right - left) >> 1)\n if(mid < nums[mid]) left = mid + 1\n else right = mid - 1\n }\n // if we found i == nums[i], there will be i + 1 items\n // larger or equal to i, which makes array not special.\n return left < nums.length && left === nums[left] ? -1 : left\n};",
"const specialArray = function(nums) {\n const n = nums.length\n nums.sort((a, b) => b - a)\n let l = 0, r = n\n while(l < r) {\n const mid = l + ((r - l) >> 1)\n if(nums[mid] > mid) l = mid + 1\n else r = mid\n }\n return l < n && l === nums[l] ? -1 : l\n}"
] |
|
1,609 | even-odd-tree | [
"Use the breadth-first search to go through all nodes layer by layer."
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isEvenOddTree = function(root) {
}; | A binary tree is named Even-Odd if it meets the following conditions:
The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).
For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).
Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.
Example 1:
Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
Output: true
Explanation: The node values on each level are:
Level 0: [1]
Level 1: [10,4]
Level 2: [3,7,9]
Level 3: [12,8,6,2]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
Example 2:
Input: root = [5,4,2,3,3,7]
Output: false
Explanation: The node values on each level are:
Level 0: [5]
Level 1: [4,2]
Level 2: [3,3,7]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.
Example 3:
Input: root = [5,9,1,3,5,7]
Output: false
Explanation: Node values in the level 1 should be even integers.
Constraints:
The number of nodes in the tree is in the range [1, 105].
1 <= Node.val <= 106
| Medium | [
"tree",
"breadth-first-search",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const isEvenOddTree = function(root) {\n const q = [root]\n const v = []\n let l = 0\n while(q.length) {\n const size = q.length\n const row = []\n for(let i = 0; i < size; i++) {\n const cur = q.shift()\n row.push(cur.val)\n if(l % 2 === 0 && cur.val % 2 === 0) return false\n if(l % 2 === 1 && cur.val % 2 === 1) return false\n if(row.length > 1) {\n if(l % 2 === 0 && row[row.length - 1] <= row[row.length - 2]) return false\n if(l % 2 === 1 && row[row.length - 1] >= row[row.length - 2]) return false\n }\n if(cur.left) q.push(cur.left)\n if(cur.right) q.push(cur.right)\n }\n l++\n }\n return true\n};"
] |
1,610 | maximum-number-of-visible-points | [
"Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate.",
"We can use two pointers to keep track of visible points for each start point",
"For handling the cyclic condition, it’d be helpful to append the point list to itself after sorting."
] | /**
* @param {number[][]} points
* @param {number} angle
* @param {number[]} location
* @return {number}
*/
var visiblePoints = function(points, angle, location) {
}; | You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane.
Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2].
Your browser does not support the video tag or this video format.
You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view.
There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.
Return the maximum number of points you can see.
Example 1:
Input: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]
Output: 3
Explanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.
Example 2:
Input: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]
Output: 4
Explanation: All points can be made visible in your field of view, including the one at your location.
Example 3:
Input: points = [[1,0],[2,1]], angle = 13, location = [1,1]
Output: 1
Explanation: You can only see one of the two points, as shown above.
Constraints:
1 <= points.length <= 105
points[i].length == 2
location.length == 2
0 <= angle < 360
0 <= posx, posy, xi, yi <= 100
| Hard | [
"array",
"math",
"geometry",
"sliding-window",
"sorting"
] | [
"const visiblePoints = function (points, angle, location) {\n const angles = [];\n let count = 0;\n for (let p of points) {\n let dx = p[0] - location[0];\n let dy = p[1] - location[1];\n if (dx == 0 && dy == 0) {\n // edge case of same point\n count++;\n continue;\n }\n angles.push(Math.atan2(dy, dx) * (180 / Math.PI));\n }\n angles.sort();\n const tmp = angles.slice();\n for (let d of angles) tmp.push(d + 360); // concatenate to handle edge case\n let res = count;\n for (let i = 0, j = 0; i < tmp.length; i++) {\n while (tmp[i] - tmp[j] > angle) {\n j++;\n }\n res = Math.max(res, count + i - j + 1);\n }\n return res;\n};"
] |
|
1,611 | minimum-one-bit-operations-to-make-integers-zero | [
"The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit.",
"consider n=2^k case first, then solve for all n."
] | /**
* @param {number} n
* @return {number}
*/
var minimumOneBitOperations = function(n) {
}; | Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.
Example 2:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.
Constraints:
0 <= n <= 109
| Hard | [
"dynamic-programming",
"bit-manipulation",
"memoization"
] | [
"const minimumOneBitOperations = function (n) {\n let sign = 1,\n res = 0;\n while (n) {\n res += n ^ ((n - 1) * sign);\n n &= n - 1;\n sign = -sign;\n }\n return Math.abs(res);\n};",
"const minimumOneBitOperations = function(n) {\n let mask = n;\n while (mask) {\n mask >>= 1;\n n ^= mask;\n }\n return n;\n};",
"const minimumOneBitOperations = function(n) {\n n ^= n >> 16\n n ^= n >> 8\n n ^= n >> 4\n n ^= n >> 2\n n ^= n >> 1\n return n\n};"
] |
|
1,614 | maximum-nesting-depth-of-the-parentheses | [
"The depth of any character in the VPS is the ( number of left brackets before it ) - ( number of right brackets before it )"
] | /**
* @param {string} s
* @return {number}
*/
var maxDepth = function(s) {
}; | A string is a valid parentheses string (denoted VPS) if it meets one of the following:
It is an empty string "", or a single character not equal to "(" or ")",
It can be written as AB (A concatenated with B), where A and B are VPS's, or
It can be written as (A), where A is a VPS.
We can similarly define the nesting depth depth(S) of any VPS S as follows:
depth("") = 0
depth(C) = 0, where C is a string with a single character not equal to "(" or ")".
depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's.
depth("(" + A + ")") = 1 + depth(A), where A is a VPS.
For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.
Given a VPS represented as string s, return the nesting depth of s.
Example 1:
Input: s = "(1+(2*3)+((8)/4))+1"
Output: 3
Explanation: Digit 8 is inside of 3 nested parentheses in the string.
Example 2:
Input: s = "(1)+((2))+(((3)))"
Output: 3
Constraints:
1 <= s.length <= 100
s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.
It is guaranteed that parentheses expression s is a VPS.
| Easy | [
"string",
"stack"
] | [
"const maxDepth = function(s) {\n const stack = []\n let res = 0\n for(let i = 0, len = s.length; i < len; i++) {\n if(s[i] === '(') {\n stack.push('(')\n res = Math.max(res, stack.length)\n } else if(s[i] === ')') {\n stack.pop()\n }\n }\n \n return res\n};"
] |
|
1,615 | maximal-network-rank | [
"Try every pair of different cities and calculate its network rank.",
"The network rank of two vertices is <i>almost</i> the sum of their degrees.",
"How can you efficiently check if there is a road connecting two different cities?"
] | /**
* @param {number} n
* @param {number[][]} roads
* @return {number}
*/
var maximalNetworkRank = function(n, roads) {
}; | There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.
The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.
The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.
Given the integer n and the array roads, return the maximal network rank of the entire infrastructure.
Example 1:
Input: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]
Output: 4
Explanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.
Example 2:
Input: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]
Output: 5
Explanation: There are 5 roads that are connected to cities 1 or 2.
Example 3:
Input: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]
Output: 5
Explanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.
Constraints:
2 <= n <= 100
0 <= roads.length <= n * (n - 1) / 2
roads[i].length == 2
0 <= ai, bi <= n-1
ai != bi
Each pair of cities has at most one road connecting them.
| Medium | [
"graph"
] | [
"const maximalNetworkRank = function (n, roads) {\n const edgeCount = new Array(n).fill(0);\n const m = roads.length;\n const map = new Map();\n for (let i = 0; i < m; i++) {\n edgeCount[roads[i][0]]++;\n edgeCount[roads[i][1]]++;\n if (!map.has(roads[i][0])) {\n map.set(roads[i][0], new Set());\n }\n if (!map.has(roads[i][1])) {\n map.set(roads[i][1], new Set());\n }\n const A = map.get(roads[i][0]);\n A.add(roads[i][1]);\n const B = map.get(roads[i][1]);\n B.add(roads[i][0]);\n }\n\n let maxRank = 0;\n for (let i = 0; i < m; i++) {\n let rank = edgeCount[roads[i][0]] + edgeCount[roads[i][1]] - 1;\n if (rank > maxRank) {\n maxRank = rank;\n }\n }\n const keys = [];\n for (let k of map.keys()) keys.push(k);\n // console.log(keys, map)\n for (let i = 0, len = keys.length; i < m - 1; i++) {\n const tmp = map.get(keys[i]);\n for (let j = i + 1; j < m; j++) {\n // console.log(tmp, i, j, tmp.has(keys[j]))\n if (tmp && !tmp.has(keys[j])) {\n let rank = edgeCount[keys[i]] + edgeCount[keys[j]];\n if (rank > maxRank) {\n maxRank = rank;\n }\n }\n }\n }\n \n\n return maxRank;\n};"
] |
|
1,616 | split-two-strings-to-make-palindrome | [
"Try finding the largest prefix form a that matches a suffix in b",
"Try string matching"
] | /**
* @param {string} a
* @param {string} b
* @return {boolean}
*/
var checkPalindromeFormation = function(a, b) {
}; | You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome.
When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are valid splits.
Return true if it is possible to form a palindrome string, otherwise return false.
Notice that x + y denotes the concatenation of strings x and y.
Example 1:
Input: a = "x", b = "y"
Output: true
Explaination: If either a or b are palindromes the answer is true since you can split in the following way:
aprefix = "", asuffix = "x"
bprefix = "", bsuffix = "y"
Then, aprefix + bsuffix = "" + "y" = "y", which is a palindrome.
Example 2:
Input: a = "xbdef", b = "xecab"
Output: false
Example 3:
Input: a = "ulacfd", b = "jizalu"
Output: true
Explaination: Split them at index 3:
aprefix = "ula", asuffix = "cfd"
bprefix = "jiz", bsuffix = "alu"
Then, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome.
Constraints:
1 <= a.length, b.length <= 105
a.length == b.length
a and b consist of lowercase English letters
| Medium | [
"two-pointers",
"string"
] | [
"const checkPalindromeFormation = function (a, b) {\n return check(a, b) || check(b, a)\n}\n\nfunction isPalindrome(s, i, j) {\n for (; i < j; ++i, --j) {\n if (s[i] != s[j]) return false\n }\n return true\n}\n\nfunction check(a, b) {\n for (let i = 0, j = a.length - 1; i < j; ++i, --j) {\n if (a[i] !== b[j]) return isPalindrome(a, i, j) || isPalindrome(b, i, j)\n }\n return true\n}"
] |
|
1,617 | count-subtrees-with-max-distance-between-cities | [
"Iterate through every possible subtree by doing a bitmask on which vertices to include. How can you determine if a subtree is valid (all vertices are connected)?",
"To determine connectivity, count the number of reachable vertices starting from any included vertex and only traveling on edges connecting 2 vertices in the subtree. The count should be the same as the number of 1s in the bitmask.",
"The diameter is basically the maximum distance between any two nodes. Root the tree at a vertex. The answer is the max of the heights of the two largest subtrees or the longest diameter in any of the subtrees."
] | /**
* @param {number} n
* @param {number[][]} edges
* @return {number[]}
*/
var countSubgraphsForEachDiameter = function(n, edges) {
}; | There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree.
A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other.
For each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d.
Return an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d.
Notice that the distance between the two cities is the number of edges in the path between them.
Example 1:
Input: n = 4, edges = [[1,2],[2,3],[2,4]]
Output: [3,4,0]
Explanation:
The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.
The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.
No subtree has two nodes where the max distance between them is 3.
Example 2:
Input: n = 2, edges = [[1,2]]
Output: [1]
Example 3:
Input: n = 3, edges = [[1,2],[2,3]]
Output: [2,1]
Constraints:
2 <= n <= 15
edges.length == n-1
edges[i].length == 2
1 <= ui, vi <= n
All pairs (ui, vi) are distinct.
| Hard | [
"dynamic-programming",
"bit-manipulation",
"tree",
"enumeration",
"bitmask"
] | [
"const countSubgraphsForEachDiameter = function (n, edges) {\n const graph = {};\n for (let [u, v] of edges) {\n if (!graph[u - 1]) graph[u - 1] = [];\n if (!graph[v - 1]) graph[v - 1] = [];\n graph[u - 1].push(v - 1);\n graph[v - 1].push(u - 1);\n }\n let ans = Array(n - 1).fill(0);\n for (let i = 1, len = 2 ** n; i < len; i++) {\n const d = maxDistance(i);\n if (d > 0) ans[d - 1] += 1;\n }\n return ans;\n function bfs(src, cities) {\n const visited = new Set();\n visited.add(src);\n const q = [[src, 0]]; // Pair of (vertex, distance)\n let farthestDist = 0; // Farthest distance from src to other nodes\n while (q.length > 0) {\n const [u, d] = q.shift();\n farthestDist = d;\n for (let v of graph[u]) {\n if (!visited.has(v) && cities.has(v)) {\n visited.add(v);\n q.push([v, d + 1]);\n }\n }\n }\n return [farthestDist, visited];\n }\n function maxDistance(state) {\n // return: maximum distance between any two cities in our subset. O(n^2)\n const cities = new Set();\n for (let i = 0; i < n; i++) {\n if ((state >> i) & (1 === 1)) cities.add(i);\n }\n let ans = 0;\n for (let i of cities) {\n const [farthestDist, visited] = bfs(i, cities);\n if (visited.size < cities.size) return 0; // Can't visit all nodes of the tree -> Invalid tree\n ans = Math.max(ans, farthestDist);\n }\n return ans;\n }\n};",
"const countSubgraphsForEachDiameter = function(n, edges) {\n const graph = {}\n for(const [u, v] of edges) {\n if(graph[u - 1] == null) graph[u - 1] = []\n if(graph[v - 1] == null) graph[v - 1] = []\n graph[u - 1].push(v - 1)\n graph[v - 1].push(u - 1)\n }\n const res = Array(n - 1).fill(0)\n \n for(let i = 0, len = 2 ** n; i < len; i++) {\n const dis = maxDistance(i)\n if(dis > 0) res[dis - 1]++\n }\n \n return res\n \n function bfs(src, cities) {\n const visited = new Set([src])\n let q = [[src, 0]]\n let maxDist = 0\n while(q.length) {\n const tmp = []\n const size = q.length\n for(let i = 0; i < size; i++) {\n const [u, d] = q[i]\n maxDist = d\n for(const v of (graph[u] || [])) {\n if(cities.has(v) && !visited.has(v)) {\n visited.add(v)\n tmp.push([v, d + 1])\n }\n }\n }\n \n q = tmp\n }\n \n return [maxDist, visited]\n }\n \n function maxDistance(state) {\n const cities = new Set()\n for(let i = 0; i < n; i++) {\n if(state & (1 << i)) cities.add(i)\n }\n \n let res = 0\n for(const e of cities) {\n const [maxDist, visited] = bfs(e, cities)\n if(visited.size < cities.size) return 0\n res = Math.max(res, maxDist) \n }\n \n return res\n }\n}; "
] |
|
1,619 | mean-of-array-after-removing-some-elements | [
"Sort the given array.",
"Remove the first and last 5% of the sorted array."
] | /**
* @param {number[]} arr
* @return {number}
*/
var trimMean = function(arr) {
}; | Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.
Answers within 10-5 of the actual answer will be considered accepted.
Example 1:
Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]
Output: 2.00000
Explanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
Example 2:
Input: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]
Output: 4.00000
Example 3:
Input: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]
Output: 4.77778
Constraints:
20 <= arr.length <= 1000
arr.length is a multiple of 20.
0 <= arr[i] <= 105
| Easy | [
"array",
"sorting"
] | [
"const trimMean = function(arr) {\n const n = arr.length\n arr.sort((a, b) => a - b)\n const idx = n / 20\n let tmp = arr.slice(idx, n - idx)\n const sum = tmp.reduce((ac, cur) => ac + cur, 0)\n return sum / (n -idx * 2)\n};"
] |
|
1,620 | coordinate-with-maximum-network-quality | [
"The constraints are small enough to consider every possible coordinate and calculate its quality."
] | /**
* @param {number[][]} towers
* @param {number} radius
* @return {number[]}
*/
var bestCoordinate = function(towers, radius) {
}; | You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance.
You are also given an integer radius where a tower is reachable if the distance is less than or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not reachable.
The signal quality of the ith tower at a coordinate (x, y) is calculated with the formula ⌊qi / (1 + d)⌋, where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers.
Return the array [cx, cy] representing the integral coordinate (cx, cy) where the network quality is maximum. If there are multiple coordinates with the same network quality, return the lexicographically minimum non-negative coordinate.
Note:
A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either:
x1 < x2, or
x1 == x2 and y1 < y2.
⌊val⌋ is the greatest integer less than or equal to val (the floor function).
Example 1:
Input: towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2
Output: [2,1]
Explanation: At coordinate (2, 1) the total quality is 13.
- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7
- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2
- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4
No other coordinate has a higher network quality.
Example 2:
Input: towers = [[23,11,21]], radius = 9
Output: [23,11]
Explanation: Since there is only one tower, the network quality is highest right at the tower's location.
Example 3:
Input: towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2
Output: [1,2]
Explanation: Coordinate (1, 2) has the highest network quality.
Constraints:
1 <= towers.length <= 50
towers[i].length == 3
0 <= xi, yi, qi <= 50
1 <= radius <= 50
| Medium | [
"array",
"enumeration"
] | null | [] |
1,621 | number-of-sets-of-k-non-overlapping-line-segments | [
"Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state.",
"To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint)."
] | /**
* @param {number} n
* @param {number} k
* @return {number}
*/
var numberOfSets = function(n, k) {
}; | Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints.
Return the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7.
Example 1:
Input: n = 4, k = 2
Output: 5
Explanation: The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
Example 2:
Input: n = 3, k = 1
Output: 3
Explanation: The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
Example 3:
Input: n = 30, k = 7
Output: 796297179
Explanation: The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.
Constraints:
2 <= n <= 1000
1 <= k <= n-1
| Medium | [
"math",
"dynamic-programming"
] | [
"const numberOfSets = function (n, k) {\n let res = BigInt(1)\n const mod = BigInt(10 ** 9 + 7)\n for (let i = 1; i < k * 2 + 1; i++) {\n res = res * BigInt(n + k - i)\n res = res / BigInt(i)\n }\n res = res % mod\n return res\n}",
"const numberOfSets = function (n, k) {\n // dp[i][k] as: the number of ways to generate\n // k non-overlapping segments you can make using [0 ~ i].\n const dp = Array.from({ length: n }, () => Array(k + 1).fill(0))\n const MOD = 10 ** 9 + 7\n dp[1][1] = 1\n for (let i = 2; i < n; i++) dp[i][1] = ((i + 1) * i) / 2\n // sum[i][j] as: the number of ways to generate\n // j - 1 segments from i - 1 points.\n const sum = Array.from({ length: n }, () => Array(k + 1).fill(0))\n for (let i = 2; i < n; i++) {\n for (let j = 2; j <= k; j++) {\n if (j <= i) sum[i][j] = (sum[i - 1][j] + dp[i - 1][j - 1]) % MOD\n dp[i][j] = (sum[i][j] + dp[i - 1][j]) % MOD\n }\n }\n return dp[n - 1][k]\n}"
] |
|
1,622 | fancy-sequence | [
"Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier.",
"The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value."
] |
var Fancy = function() {
};
/**
* @param {number} val
* @return {void}
*/
Fancy.prototype.append = function(val) {
};
/**
* @param {number} inc
* @return {void}
*/
Fancy.prototype.addAll = function(inc) {
};
/**
* @param {number} m
* @return {void}
*/
Fancy.prototype.multAll = function(m) {
};
/**
* @param {number} idx
* @return {number}
*/
Fancy.prototype.getIndex = function(idx) {
};
/**
* Your Fancy object will be instantiated and called as such:
* var obj = new Fancy()
* obj.append(val)
* obj.addAll(inc)
* obj.multAll(m)
* var param_4 = obj.getIndex(idx)
*/ | Write an API that generates fancy sequences using the append, addAll, and multAll operations.
Implement the Fancy class:
Fancy() Initializes the object with an empty sequence.
void append(val) Appends an integer val to the end of the sequence.
void addAll(inc) Increments all existing values in the sequence by an integer inc.
void multAll(m) Multiplies all existing values in the sequence by an integer m.
int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 109 + 7. If the index is greater or equal than the length of the sequence, return -1.
Example 1:
Input
["Fancy", "append", "addAll", "append", "multAll", "getIndex", "addAll", "append", "multAll", "getIndex", "getIndex", "getIndex"]
[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]
Output
[null, null, null, null, null, 10, null, null, null, 26, 34, 20]
Explanation
Fancy fancy = new Fancy();
fancy.append(2); // fancy sequence: [2]
fancy.addAll(3); // fancy sequence: [2+3] -> [5]
fancy.append(7); // fancy sequence: [5, 7]
fancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]
fancy.getIndex(0); // return 10
fancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]
fancy.append(10); // fancy sequence: [13, 17, 10]
fancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]
fancy.getIndex(0); // return 26
fancy.getIndex(1); // return 34
fancy.getIndex(2); // return 20
Constraints:
1 <= val, inc, m <= 100
0 <= idx <= 105
At most 105 calls total will be made to append, addAll, multAll, and getIndex.
| Hard | [
"math",
"design",
"segment-tree"
] | [
"const mod = 10 ** 9 + 7;\nconst Fancy = function () {\n this.seq = [];\n this.mods = [];\n};\nFancy.prototype.append = function (val) {\n this.seq.push(val);\n};\nFancy.prototype.addAll = function (inc) {\n this.mods.push([\"p\", inc, this.seq.length]);\n};\nFancy.prototype.multAll = function (m) {\n this.mods.push([\"m\", m, this.seq.length]);\n};\nFancy.prototype.getIndex = function (idx) {\n if (idx >= this.seq.length) return -1;\n let x = this.seq[idx];\n\n for (let i = 0; i < this.mods.length; i++) {\n if (this.mods[i][2] > idx) {\n if (\"m\" === this.mods[i][0]) {\n x = (x * this.mods[i][1]) % mod;\n } else {\n x = (x + this.mods[i][1]) % mod;\n }\n }\n }\n return x;\n};"
] |
|
1,624 | largest-substring-between-two-equal-characters | [
"Try saving the first and last position of each character",
"Try finding every pair of indexes with equal characters"
] | /**
* @param {string} s
* @return {number}
*/
var maxLengthBetweenEqualCharacters = function(s) {
}; | Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "aa"
Output: 0
Explanation: The optimal substring here is an empty substring between the two 'a's.
Example 2:
Input: s = "abca"
Output: 2
Explanation: The optimal substring here is "bc".
Example 3:
Input: s = "cbzxy"
Output: -1
Explanation: There are no characters that appear twice in s.
Constraints:
1 <= s.length <= 300
s contains only lowercase English letters.
| Easy | [
"hash-table",
"string"
] | [
"const maxLengthBetweenEqualCharacters = function(s) {\n const m = {}\n if(s ==null || s.length <= 1) return -1\n let res = -1\n for(let i = 0, len = s.length; i< len;i++) {\n if(m[s[i]] != null) {\n res = Math.max(res, i - m[s[i]] - 1)\n } else {\n m[s[i]] = i\n }\n \n }\n return res\n};"
] |
|
1,625 | lexicographically-smallest-string-after-applying-operations | [
"Since the length of s is even, the total number of possible sequences is at most 10 * 10 * s.length.",
"You can generate all possible sequences and take their minimum.",
"Keep track of already generated sequences so they are not processed again."
] | /**
* @param {string} s
* @param {number} a
* @param {number} b
* @return {string}
*/
var findLexSmallestString = function(s, a, b) {
}; | You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b.
You can apply either of the following two operations any number of times and in any order on s:
Add a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, if s = "3456" and a = 5, s becomes "3951".
Rotate s to the right by b positions. For example, if s = "3456" and b = 1, s becomes "6345".
Return the lexicographically smallest string you can obtain by applying the above operations any number of times on s.
A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, "0158" is lexicographically smaller than "0190" because the first position they differ is at the third letter, and '5' comes before '9'.
Example 1:
Input: s = "5525", a = 9, b = 2
Output: "2050"
Explanation: We can apply the following operations:
Start: "5525"
Rotate: "2555"
Add: "2454"
Add: "2353"
Rotate: "5323"
Add: "5222"
Add: "5121"
Rotate: "2151"
Add: "2050"
There is no way to obtain a string that is lexicographically smaller than "2050".
Example 2:
Input: s = "74", a = 5, b = 1
Output: "24"
Explanation: We can apply the following operations:
Start: "74"
Rotate: "47"
Add: "42"
Rotate: "24"
There is no way to obtain a string that is lexicographically smaller than "24".
Example 3:
Input: s = "0011", a = 4, b = 2
Output: "0011"
Explanation: There are no sequence of operations that will give us a lexicographically smaller string than "0011".
Constraints:
2 <= s.length <= 100
s.length is even.
s consists of digits from 0 to 9 only.
1 <= a <= 9
1 <= b <= s.length - 1
| Medium | [
"string",
"breadth-first-search"
] | [
" \nconst findLexSmallestString = function(s, a, b) {\n let res = s\n const visited = new Set()\n dfs(s)\n return res\n \n function dfs(str) {\n if(isVisited(str)) return\n visit(str)\n dfs(add(str))\n dfs(rotate(str))\n }\n \n function isVisited(str) {\n return visited.has(str)\n }\n \n function visit(str) {\n if(str < res) res = str\n visited.add(str)\n }\n \n function add(str) {\n const arr = str.split('').map(e => +e)\n for(let i = 1; i < str.length; i += 2) {\n arr[i] = (arr[i] + a) % 10\n }\n return arr.join('')\n }\n \n function rotate(str) {\n const arr = str.split('')\n arr.reverse()\n let l = 0, r = b - 1\n while(l < r) {\n swap(arr, l++, r--)\n }\n l = b\n r = s.length - 1\n while(l < r) {\n swap(arr, l++, r--)\n }\n return arr.join('')\n }\n \n function swap(arr, i, j) {\n ;[arr[i], arr[j]] = [arr[j], arr[i]]\n }\n};",
"const findLexSmallestString = function(s, a, b) {\n let res = s\n const set = new Set()\n const q = [s]\n set.add(res)\n while(q.length) {\n const len = q.length\n for(let i = 0; i < len; i++) {\n const tmp = q.shift()\n const t1 = podd(tmp, a)\n const t2 = rotate(tmp, b)\n if(!set.has(t1)) {\n set.add(t1)\n q.push(t1)\n }\n if(!set.has(t2)) {\n set.add(t2)\n q.push(t2)\n }\n if(t1 < res) res = t1\n if(t2 < res) res = t2\n }\n }\n return res\n};\n\nfunction podd(s, num) {\n const arr = s.split('')\n for(let i = 1, len = s.length; i < len; i += 2) {\n const tmp = (+s[i] + num) % 10\n arr[i] = tmp\n }\n return arr.join('')\n}\n\nfunction rotate(s, num) {\n const len = s.length\n num = num % len\n const idx = len - num\n return s.slice(idx) + s.slice(0, idx)\n}"
] |
|
1,626 | best-team-with-no-conflicts | [
"First, sort players by age and break ties by their score. You can now consider the players from left to right.",
"If you choose to include a player, you must only choose players with at least that score later on."
] | /**
* @param {number[]} scores
* @param {number[]} ages
* @return {number}
*/
var bestTeamScore = function(scores, ages) {
}; | You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.
However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.
Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams.
Example 1:
Input: scores = [1,3,5,10,15], ages = [1,2,3,4,5]
Output: 34
Explanation: You can choose all the players.
Example 2:
Input: scores = [4,5,6,5], ages = [2,1,2,1]
Output: 16
Explanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.
Example 3:
Input: scores = [1,2,3,5], ages = [8,9,10,1]
Output: 6
Explanation: It is best to choose the first 3 players.
Constraints:
1 <= scores.length, ages.length <= 1000
scores.length == ages.length
1 <= scores[i] <= 106
1 <= ages[i] <= 1000
| Medium | [
"array",
"dynamic-programming",
"sorting"
] | [
"const bestTeamScore = function(scores, ages) {\n const len = ages.length\n const arr = Array(len)\n for(let i = 0; i < len; i++) {\n arr[i] = [scores[i], ages[i]] \n }\n arr.sort((a, b) => {\n if(a[1] > b[1]) return 1\n else if(a[1] === b[1]) return a[0] - b[0]\n else return -1\n })\n const dp = Array(len)\n let res = 0\n for(let i = 0; i < len; i++) {\n dp[i] = arr[i][0]\n for(let j = i - 1; j >= 0; j--) {\n if(arr[j][0] > arr[i][0] && arr[j][1] < arr[i][1]) {\n continue\n }\n dp[i] = Math.max(dp[i], dp[j] + arr[i][0])\n }\n res = Math.max(res, dp[i])\n }\n return res\n};"
] |
|
1,627 | graph-connectivity-with-threshold | [
"How to build the graph of the cities?",
"Connect city i with all its multiples 2*i, 3*i, ...",
"Answer the queries using union-find data structure."
] | /**
* @param {number} n
* @param {number} threshold
* @param {number[][]} queries
* @return {boolean[]}
*/
var areConnected = function(n, threshold, queries) {
}; | We have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold. More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true:
x % z == 0,
y % z == 0, and
z > threshold.
Given the two integers, n and threshold, and an array of queries, you must determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly. (i.e. there is some path between them).
Return an array answer, where answer.length == queries.length and answer[i] is true if for the ith query, there is a path between ai and bi, or answer[i] is false if there is no path.
Example 1:
Input: n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]
Output: [false,false,true]
Explanation: The divisors for each number:
1: 1
2: 1, 2
3: 1, 3
4: 1, 2, 4
5: 1, 5
6: 1, 2, 3, 6
Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the
only ones directly connected. The result of each query:
[1,4] 1 is not connected to 4
[2,5] 2 is not connected to 5
[3,6] 3 is connected to 6 through path 3--6
Example 2:
Input: n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]
Output: [true,true,true,true,true]
Explanation: The divisors for each number are the same as the previous example. However, since the threshold is 0,
all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.
Example 3:
Input: n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]
Output: [false,false,false,false,false]
Explanation: Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.
Please notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].
Constraints:
2 <= n <= 104
0 <= threshold <= n
1 <= queries.length <= 105
queries[i].length == 2
1 <= ai, bi <= cities
ai != bi
| Hard | [
"array",
"math",
"union-find",
"number-theory"
] | [
"const areConnected = function(n, threshold, queries) {\n const arr = []\n const uf = new UF(n)\n setup(n, threshold, uf)\n for(let i = 0, len = queries.length; i < len;i++) {\n arr.push(uf.check(queries[i][0], queries[i][1]))\n }\n return arr\n};\n\nfunction setup(n, t, uf) {\n for (let i = t + 1; i <= n; i++) {\n let m = 1;\n while (i * m <= n) {\n uf.union(i, i * m);\n m += 1;\n }\n }\n}\n\n\nclass UF {\n constructor(n) {\n this.root = Array(n).fill(null).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 check(x, y) {\n return this.find(x) === this.find(y)\n }\n}",
"const areConnected = function (n, threshold, queries) {\n const arr = []\n const uf = new UnionFind(n)\n setup(n, threshold, uf)\n for (let i = 0, len = queries.length; i < len; i++) {\n arr.push(uf.check(queries[i][0], queries[i][1]))\n }\n return arr\n}\n\nfunction setup(n, t, uf) {\n t++\n for (let i = t; i <= n; i++) {\n let m = 1\n while (i * m <= n) {\n uf.union(i, i * m)\n m += 1\n }\n }\n}\nclass UnionFind {\n constructor(n) {\n this.parents = Array(n + 1)\n .fill(0)\n .map((e, i) => i)\n this.ranks = Array(n + 1).fill(0)\n }\n root(x) {\n while (x !== this.parents[x]) {\n this.parents[x] = this.parents[this.parents[x]]\n x = this.parents[x]\n }\n return x\n }\n find(x) {\n return this.root(x)\n }\n check(x, y) {\n return this.root(x) === this.root(y)\n }\n union(x, y) {\n const [rx, ry] = [this.find(x), this.find(y)]\n if (this.ranks[rx] >= this.ranks[ry]) {\n this.parents[ry] = rx\n this.ranks[rx] += this.ranks[ry]\n } else if (this.ranks[ry] > this.ranks[rx]) {\n this.parents[rx] = ry\n this.ranks[ry] += this.ranks[rx]\n }\n }\n}"
] |
|
1,629 | slowest-key | [
"Get for each press its key and amount of time taken.",
"Iterate on the presses, maintaining the answer so far.",
"The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer."
] | /**
* @param {number[]} releaseTimes
* @param {string} keysPressed
* @return {character}
*/
var slowestKey = function(releaseTimes, keysPressed) {
}; | A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.
You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released.
The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0].
Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration.
Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.
Example 1:
Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"
Output: "c"
Explanation: The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.
Example 2:
Input: releaseTimes = [12,23,36,46,62], keysPressed = "spuda"
Output: "a"
Explanation: The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.
Constraints:
releaseTimes.length == n
keysPressed.length == n
2 <= n <= 1000
1 <= releaseTimes[i] <= 109
releaseTimes[i] < releaseTimes[i+1]
keysPressed contains only lowercase English letters.
| Easy | [
"array",
"string"
] | [
"const slowestKey = function(releaseTimes, keysPressed) {\n const m = {}\n const n = keysPressed.length\n const set = new Set()\n set.add(keysPressed[0])\n m[releaseTimes[0]] = set\n for(let i = 1; i < n; i++) {\n const k = releaseTimes[i] - releaseTimes[i - 1]\n if(m[k] == null) m[k] = new Set()\n m[k].add(keysPressed[i])\n }\n const keys = Object.keys(m).sort((a, b) => a - b)\n const last = keys[keys.length - 1]\n const arr = Array.from(m[last])\n arr.sort()\n return arr[arr.length - 1]\n};"
] |
|
1,630 | arithmetic-subarrays | [
"To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same.",
"If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arithmetic.",
"For each query, get the corresponding set of numbers which will be the sub-array represented by the query, sort it, and check if the result sequence is arithmetic."
] | /**
* @param {number[]} nums
* @param {number[]} l
* @param {number[]} r
* @return {boolean[]}
*/
var checkArithmeticSubarrays = function(nums, l, r) {
}; | A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i.
For example, these are arithmetic sequences:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not arithmetic:
1, 1, 2, 5, 7
You are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed.
Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise.
Example 1:
Input: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]
Output: [true,false,true]
Explanation:
In the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.
In the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.
In the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence.
Example 2:
Input: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]
Output: [false,true,false,false,true,true]
Constraints:
n == nums.length
m == l.length
m == r.length
2 <= n <= 500
1 <= m <= 500
0 <= l[i] < r[i] < n
-105 <= nums[i] <= 105
| Medium | [
"array",
"sorting"
] | [
"const checkArithmeticSubarrays = function(nums, l, r) {\n const len = l.length\n const res = []\n for(let i = 0; i < len; i++) {\n res.push(chk(nums.slice(l[i], r[i] + 1)))\n }\n return res\n};\n\nfunction chk(arr) {\n if(arr.length === 0 || arr.length === 1 || arr.length === 2) return true\n arr.sort((a, b) => a - b)\n const diff = arr[1] - arr[0]\n for(let i = 2, len = arr.length; i < len; i++) {\n if(arr[i] - arr[i - 1] !== diff) return false\n }\n return true\n}"
] |
|
1,631 | path-with-minimum-effort | [
"Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells.",
"If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost.",
"Binary search the k value."
] | /**
* @param {number[][]} heights
* @return {number}
*/
var minimumEffortPath = function(heights) {
}; | You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.
A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.
Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
Example 1:
Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.
Example 2:
Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].
Example 3:
Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
Output: 0
Explanation: This route does not require any effort.
Constraints:
rows == heights.length
columns == heights[i].length
1 <= rows, columns <= 100
1 <= heights[i][j] <= 106
| Medium | [
"array",
"binary-search",
"depth-first-search",
"breadth-first-search",
"union-find",
"heap-priority-queue",
"matrix"
] | [
"const minimumEffortPath = function(heights) {\n const m = heights.length, n = heights[0].length\n const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n let l = 0, r = 1e6 - 1\n \n while(l < r) {\n const mid = ~~((l + r) / 2)\n // console.log(l, r, mid)\n if(valid(mid)) {\n r = mid\n } else {\n l = mid + 1\n }\n }\n \n return l\n \n function valid(limit) {\n const visited = Array.from({ length: m }, () => Array(n).fill(false))\n return dfs(0, 0, limit, visited)\n }\n \n function dfs(i, j, limit, visited) {\n if(i === m - 1 && j === n - 1) return true\n visited[i][j] = true\n for(const [dx, dy] of dirs) {\n const nx = i + dx, ny = j + dy\n if(nx < 0 || nx >= m || ny < 0 || ny >= n) continue\n if(visited[nx][ny]) continue\n if(Math.abs(heights[i][j] - heights[nx][ny]) > limit) continue\n if(dfs(nx, ny, limit, visited)) return true\n }\n // return false\n }\n\n};",
"const minimumEffortPath = function(heights) {\n const m = heights.length, n = heights[0].length\n const pq = new PriorityQueue()\n const dist = Array.from({ length: m }, () => Array(n).fill(Infinity))\n pq.push([0, 0, 0])\n dist[0][0] = 0\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n while(!pq.isEmpty()) {\n const [v, i, j] = pq.pop()\n if(i === m - 1 && j === n - 1) return v\n for(const [dx, dy] of dirs) {\n const nx = i + dx, ny = j + dy\n if(nx < 0 || nx >= m || ny < 0 || ny >= n) continue\n const diff = Math.max(v, Math.abs(heights[nx][ny] - heights[i][j]))\n if(dist[nx][ny] > diff) {\n dist[nx][ny] = diff\n pq.push([diff, nx, ny])\n }\n }\n }\n return -1\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a[0] < b[0]) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}",
"const minimumEffortPath = function (heights) {\n const d = [0, 1, 0, -1, 0]\n let lo = 0,\n hi = 10 ** 6 + 1\n while (lo < hi) {\n let effort = lo + ((hi - lo) >> 1)\n if (isPath(heights, effort)) {\n hi = effort\n } else {\n lo = effort + 1\n }\n }\n return lo\n function isPath(h, effort) {\n const m = h.length,\n n = h[0].length\n const q = []\n q.push([0, 0])\n const seen = new Set()\n seen.add(0)\n while (q.length) {\n const cur = q.shift()\n const x = cur[0],\n y = cur[1]\n if (x === m - 1 && y === n - 1) {\n return true\n }\n for (let k = 0; k < 4; k++) {\n const r = x + d[k],\n c = y + d[k + 1]\n if(seen.has(r * n + c)) continue\n if (\n 0 <= r &&\n r < m &&\n 0 <= c &&\n c < n &&\n effort >= Math.abs(h[r][c] - h[x][y])\n ) {\n seen.add(r * n + c)\n q.push([r, c])\n }\n }\n }\n return false\n }\n}",
"const minimumEffortPath = function(heights) {\n const rows = heights.length\n const cols = heights[0].length\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n const dist = Array.from({ length: rows }, () => Array(cols).fill(Infinity))\n const pq = new PriorityQueue()\n pq.push([0, 0, 0])\n dist[0][0] = 0\n while(pq.size) {\n const cur = pq.pop()\n if(cur[1] === rows - 1 && cur[2] === cols - 1) return cur[0]\n for(let dir of dirs) {\n const nr = cur[1] + dir[0]\n const nc = cur[2] + dir[1]\n if(nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue\n const diff = Math.max(cur[0], Math.abs(heights[nr][nc] - heights[cur[1]][cur[2]]))\n if(dist[nr][nc] > diff) {\n dist[nr][nc] = diff\n pq.push([diff, nr, nc])\n }\n }\n }\n return 0\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a[0] < b[0]) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}"
] |
|
1,632 | rank-transform-of-a-matrix | [
"Sort the cells by value and process them in increasing order.",
"The rank of a cell is the maximum rank in its row and column plus one.",
"Handle the equal cells by treating them as components using a union-find data structure."
] | /**
* @param {number[][]} matrix
* @return {number[][]}
*/
var matrixRankTransform = function(matrix) {
}; | Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col].
The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:
The rank is an integer starting from 1.
If two elements p and q are in the same row or column, then:
If p < q then rank(p) < rank(q)
If p == q then rank(p) == rank(q)
If p > q then rank(p) > rank(q)
The rank should be as small as possible.
The test cases are generated so that answer is unique under the given rules.
Example 1:
Input: matrix = [[1,2],[3,4]]
Output: [[1,2],[2,3]]
Explanation:
The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.
The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.
The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.
The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.
Example 2:
Input: matrix = [[7,7],[7,7]]
Output: [[1,1],[1,1]]
Example 3:
Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]
Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 500
-109 <= matrix[row][col] <= 109
| Hard | [
"array",
"greedy",
"union-find",
"graph",
"topological-sort",
"matrix"
] | [
"const matrixRankTransform = function (matrix) {\n function find(UF, x) {\n if (x !== UF.get(x)) UF.set(x, find(UF, UF.get(x)))\n return UF.get(x)\n }\n function union(UF, x, y) {\n if (!UF.has(x)) UF.set(x, x)\n if (!UF.has(y)) UF.set(y, y)\n UF.set(find(UF, x), find(UF, y))\n }\n const m = matrix.length\n const n = matrix[0].length\n const UFs = new Map()\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n const v = matrix[i][j]\n if (!UFs.has(v)) UFs.set(v, new Map())\n union(UFs.get(v), i, ~j)\n }\n }\n const value2index = {}\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n let v = matrix[i][j]\n if (!value2index.hasOwnProperty(v)) value2index[v] = new Map()\n const indexes = value2index[v]\n let f = find(UFs.get(v), i)\n if (!indexes.has(f)) indexes.set(f, [])\n indexes.get(f).push([i, j])\n }\n }\n const answer = Array.from({ length: m }, () => Array(n).fill(0))\n const rowMax = Array(m).fill(0), colMax = Array(n).fill(0)\n const keys = Object.keys(value2index)\n keys.sort((a, b) => a - b)\n for (let v of keys) {\n for (let points of value2index[v].values()) {\n let rank = 1\n for (let point of points) {\n rank = Math.max(rank, Math.max(rowMax[point[0]], colMax[point[1]]) + 1)\n }\n for (let point of points) {\n answer[point[0]][point[1]] = rank\n rowMax[point[0]] = Math.max(rowMax[point[0]], rank)\n colMax[point[1]] = Math.max(colMax[point[1]], rank)\n }\n }\n }\n return answer\n}",
"const matrixRankTransform = function (matrix) {\n const m = matrix.length\n const n = matrix[0].length\n const rowIndex = Array.from({ length: m }, () => Array(n).fill(0))\n const colIndex = Array.from({ length: m }, () => Array(n).fill(0))\n for (let i = 0; i < m; i++) {\n let row = []\n for (let j = 0; j < n; j++) {\n row.push([matrix[i][j], j])\n }\n\n row.sort((a, b) => a[0] - b[0])\n for (let j = 0; j < n; j++) {\n rowIndex[i][j] = row[j][1]\n }\n }\n for (let i = 0; i < n; i++) {\n const col = []\n for (let j = 0; j < m; j++) {\n col.push([matrix[j][i], j])\n }\n col.sort((a, b) => a[0] - b[0])\n for (let j = 0; j < m; j++) {\n colIndex[j][i] = col[j][1]\n }\n }\n const result = Array.from({ length: m }, () => Array(n).fill(0))\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n result[i][j] = 1\n }\n }\n let changed = true\n while (changed) {\n changed = shakeRow(matrix, rowIndex, result)\n changed = shakeCol(matrix, colIndex, result) || changed\n }\n return result\n}\n\nfunction shakeCol(matrix, colIndex, result) {\n let changed = false\n for (let i = 0; i < matrix[0].length; i++) {\n for (let j = 1; j < matrix.length; j++) {\n if (matrix[colIndex[j][i]][i] == matrix[colIndex[j - 1][i]][i]) {\n if (result[colIndex[j][i]][i] != result[colIndex[j - 1][i]][i])\n changed = true\n result[colIndex[j][i]][i] = Math.max(\n result[colIndex[j][i]][i],\n result[colIndex[j - 1][i]][i]\n )\n result[colIndex[j - 1][i]][i] = Math.max(\n result[colIndex[j][i]][i],\n result[colIndex[j - 1][i]][i]\n )\n } else {\n if (result[colIndex[j][i]][i] < result[colIndex[j - 1][i]][i] + 1) {\n changed = true\n result[colIndex[j][i]][i] = result[colIndex[j - 1][i]][i] + 1\n }\n }\n }\n }\n return changed\n}\n\nfunction shakeRow(matrix, rowIndex, result) {\n let changed = false\n for (let i = 0; i < matrix.length; i++) {\n let rowInd = rowIndex[i]\n let resu = result[i]\n for (let j = 1; j < matrix[0].length; j++) {\n if (matrix[i][rowInd[j]] == matrix[i][rowInd[j - 1]]) {\n if (resu[rowInd[j]] != resu[rowInd[j - 1]]) changed = true\n resu[rowInd[j]] = Math.max(resu[rowInd[j - 1]], resu[rowInd[j]])\n resu[rowInd[j - 1]] = Math.max(resu[rowInd[j - 1]], resu[rowInd[j]])\n } else {\n if (resu[rowInd[j]] < resu[rowInd[j - 1]] + 1) {\n changed = true\n resu[rowInd[j]] = resu[rowInd[j - 1]] + 1\n }\n }\n }\n }\n return changed\n}",
"const matrixRankTransform = function (matrix) {\n const r = matrix.length,\n c = matrix[0].length;\n const t = r * c;\n const arr = Array(t);\n const root = Array(t + 1);\n const rk = Array(t + 1).fill(0);\n const find = (a) => {\n let ra = root[a];\n if (ra == a) return a;\n return (root[a] = find(ra));\n };\n const union = (a, b) => {\n let ra = find(a);\n let rb = find(b);\n if (ra !== rb) {\n if (rk[ra] > rk[rb]) root[rb] = ra;\n else root[ra] = rb;\n }\n };\n let k = 0;\n const ans = Array(r)\n .fill(0)\n .map(() => Array(c));\n for (let i = 0; i < r; ++i) {\n for (let j = 0; j < c; ++j) {\n arr[k] = [matrix[i][j], i, j];\n root[k] = k;\n ++k;\n }\n }\n root[k] = k;\n arr.sort((a, b) => a[0] - b[0]);\n const X = Array(r)\n .fill(0)\n .map(() => [-Infinity, t]);\n const Y = Array(c)\n .fill(0)\n .map(() => [-Infinity, t]);\n for (let i = 0; i < t; ++i) {\n const [v, x, y] = arr[i];\n const id = x * c + y;\n const [xv, rx] = X[x],\n [yv, ry] = Y[y];\n if (v > xv) rk[id] = rk[find(rx)] + 1;\n else root[id] = rx;\n if (v > yv) rk[find(id)] = Math.max(rk[find(id)], rk[find(ry)] + 1);\n else union(id, ry);\n X[x] = [v, id];\n Y[y] = [v, id];\n }\n for (let i = 0; i < r; ++i) {\n for (let j = 0; j < c; ++j) {\n ans[i][j] = rk[find(i * c + j)];\n }\n }\n return ans;\n};"
] |
|
1,636 | sort-array-by-increasing-frequency | [
"Count the frequency of each value.",
"Use a custom comparator to compare values by their frequency. If two values have the same frequency, compare their values."
] | /**
* @param {number[]} nums
* @return {number[]}
*/
var frequencySort = function(nums) {
}; | Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.
Return the sorted array.
Example 1:
Input: nums = [1,1,2,2,2,3]
Output: [3,1,1,2,2,2]
Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.
Example 2:
Input: nums = [2,3,1,3,2]
Output: [1,3,3,2,2]
Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.
Example 3:
Input: nums = [-1,1,-6,4,5,-6,1,4,1]
Output: [5,-1,4,4,-6,-6,1,1,1]
Constraints:
1 <= nums.length <= 100
-100 <= nums[i] <= 100
| Easy | [
"array",
"hash-table",
"sorting"
] | [
"const frequencySort = function(nums) {\n const hash = {}\n for(let e of nums) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n nums.sort((a, b) => hash[a] === hash[b] ? b - a : hash[a] - hash[b])\n return nums\n};"
] |
|
1,637 | widest-vertical-area-between-two-points-containing-no-points | [
"Try sorting the points",
"Think is the y-axis of a point relevant"
] | /**
* @param {number[][]} points
* @return {number}
*/
var maxWidthOfVerticalArea = function(points) {
}; | Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area.
A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.
Note that points on the edge of a vertical area are not considered included in the area.
Example 1:
Input: points = [[8,7],[9,9],[7,4],[9,7]]
Output: 1
Explanation: Both the red and the blue area are optimal.
Example 2:
Input: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]
Output: 3
Constraints:
n == points.length
2 <= n <= 105
points[i].length == 2
0 <= xi, yi <= 109
| Medium | [
"array",
"sorting"
] | [
"const maxWidthOfVerticalArea = function(points) {\n const arr = points.map(e => e[0])\n arr.sort((a, b) => a - b)\n let res = -Infinity\n for(let i = 1, len = arr.length; i < len; i++) {\n if(arr[i] - arr[i - 1] > res) res = arr[i] - arr[i - 1]\n }\n return res\n};"
] |
|
1,638 | count-substrings-that-differ-by-one-character | [
"Take every substring of s, change a character, and see how many substrings of t match that substring.",
"Use a Trie to store all substrings of t as a dictionary."
] | /**
* @param {string} s
* @param {string} t
* @return {number}
*/
var countSubstrings = function(s, t) {
}; | Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character.
For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way.
Return the number of substrings that satisfy the condition above.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "aba", t = "baba"
Output: 6
Explanation: The following are the pairs of substrings from s and t that differ by exactly 1 character:
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
The underlined portions are the substrings that are chosen from s and t.
Example 2:
Input: s = "ab", t = "bb"
Output: 3
Explanation: The following are the pairs of substrings from s and t that differ by 1 character:
("ab", "bb")
("ab", "bb")
("ab", "bb")
The underlined portions are the substrings that are chosen from s and t.
Constraints:
1 <= s.length, t.length <= 100
s and t consist of lowercase English letters only.
| Medium | [
"hash-table",
"string",
"dynamic-programming"
] | [
"const countSubstrings = function (s, t) {\n const m = s.length\n const n = t.length\n const matrix = (m, n, v) => Array.from({ length: m }, () => Array(n).fill(v))\n // number of exact same substrings ending at s[i] and t[j].\n const same = matrix(m + 1, n + 1, 0)\n // number of substrings having 1 different character ending at s[i] and t[j].\n const one = matrix(m + 1, n + 1, 0)\n let result = 0\n for (let i = 1; i <= m; ++i) {\n for (let j = 1; j <= n; ++j) {\n if (s[i - 1] == t[j - 1]) {\n same[i][j] = same[i - 1][j - 1] + 1\n one[i][j] = one[i - 1][j - 1]\n } else {\n one[i][j] = same[i - 1][j - 1] + 1\n }\n result += one[i][j]\n }\n }\n return result\n}",
"const countSubstrings = function(s, t) {\n let res = 0 ;\n for (let i = 0; i < s.length; ++i) res += helper(s, t, i, 0);\n for (let j = 1; j < t.length; ++j) res += helper(s, t, 0, j);\n return res;\n};\n\nfunction helper(s, t, i, j) {\n let res = 0, pre = 0, cur = 0;\n for (let n = s.length, m = t.length; i < n && j < m; ++i, ++j) {\n cur++;\n if (s.charAt(i) !== t.charAt(j)) {\n pre = cur;\n cur = 0;\n }\n res += pre;\n }\n return res;\n}"
] |
|
1,639 | number-of-ways-to-form-a-target-string-given-a-dictionary | [
"For each index i, store the frequency of each character in the ith row.",
"Use dynamic programing to calculate the number of ways to get the target string using the frequency array,"
] | /**
* @param {string[]} words
* @param {string} target
* @return {number}
*/
var numWays = function(words, target) {
}; | You are given a list of strings of the same length words and a string target.
Your task is to form target using the given words under the following rules:
target should be formed from left to right.
To form the ith character (0-indexed) of target, you can choose the kth character of the jth string in words if target[i] = words[j][k].
Once you use the kth character of the jth string of words, you can no longer use the xth character of any string in words where x <= k. In other words, all characters to the left of or at index k become unusuable for every string.
Repeat the process until you form the string target.
Notice that you can use multiple characters from the same string in words provided the conditions above are met.
Return the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: words = ["acca","bbbb","caca"], target = "aba"
Output: 6
Explanation: There are 6 ways to form target.
"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("caca")
"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("caca")
"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("acca")
"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("acca")
"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("acca")
"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("caca")
Example 2:
Input: words = ["abba","baab"], target = "bab"
Output: 4
Explanation: There are 4 ways to form target.
"bab" -> index 0 ("baab"), index 1 ("baab"), index 2 ("abba")
"bab" -> index 0 ("baab"), index 1 ("baab"), index 3 ("baab")
"bab" -> index 0 ("baab"), index 2 ("baab"), index 3 ("baab")
"bab" -> index 1 ("abba"), index 2 ("baab"), index 3 ("baab")
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 1000
All strings in words have the same length.
1 <= target.length <= 1000
words[i] and target contain only lowercase English letters.
| Hard | [
"array",
"string",
"dynamic-programming"
] | [
"const numWays = function (words, target) {\n const m = words[0].length, len = words.length\n const n = target.length, a = 'a'.charCodeAt(0)\n const mod = 10 ** 9 + 7\n const dp = Array(n).fill(0)\n for(let i = 0; i < m; i++) {\n const freq = Array(26).fill(0)\n for(let j = 0; j < len; j++) {\n freq[words[j].charCodeAt(i) - a]++\n }\n for(let j = Math.min(i, n - 1); j >= 0; j--) {\n const code = target[j].charCodeAt(0) - a\n if(freq[code] > 0) {\n dp[j] += (j === 0 ? freq[code] : dp[j - 1] * freq[code])\n dp[j] %= mod\n }\n }\n }\n return dp[n - 1]\n}",
"const numWays = function (words, target) {\n const m = words[0].length\n const n = target.length\n const memo = Array.from({ length: m }, () => Array(n))\n const charAtIndexCnt = Array.from({ length: 128 }, () => Array(m).fill(0))\n const mod = 10 ** 9 + 7\n for (let word of words) {\n for (let i = 0; i < m; i++) {\n charAtIndexCnt[word.charCodeAt(i)][i] += 1\n }\n }\n\n return dp(0, 0)\n function dp(k, i) {\n // found one\n if (i == n) return 1\n // not found\n if (k == m) return 0\n if (memo[k][i] != null) return memo[k][i]\n const c = target.charCodeAt(i)\n // skip k_th char\n let ans = dp(k + 1, i)\n if (charAtIndexCnt[c][k] > 0) {\n ans += dp(k + 1, i + 1) * charAtIndexCnt[c][k]\n ans %= mod\n }\n return (memo[k][i] = ans)\n }\n}"
] |
|
1,640 | check-array-formation-through-concatenation | [
"Note that the distinct part means that every position in the array belongs to only one piece",
"Note that you can get the piece every position belongs to naively"
] | /**
* @param {number[]} arr
* @param {number[][]} pieces
* @return {boolean}
*/
var canFormArray = function(arr, pieces) {
}; | You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i].
Return true if it is possible to form the array arr from pieces. Otherwise, return false.
Example 1:
Input: arr = [15,88], pieces = [[88],[15]]
Output: true
Explanation: Concatenate [15] then [88]
Example 2:
Input: arr = [49,18,16], pieces = [[16,18,49]]
Output: false
Explanation: Even though the numbers match, we cannot reorder pieces[0].
Example 3:
Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]
Output: true
Explanation: Concatenate [91] then [4,64] then [78]
Constraints:
1 <= pieces.length <= arr.length <= 100
sum(pieces[i].length) == arr.length
1 <= pieces[i].length <= arr.length
1 <= arr[i], pieces[i][j] <= 100
The integers in arr are distinct.
The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
| Easy | [
"array",
"hash-table"
] | [
"const canFormArray = function(arr, pieces) {\n const m = new Map()\n for(let i = 0, len = arr.length; i < len; i++) {\n m.set(arr[i], i)\n }\n for(let p of pieces) {\n let idx = m.get(p[0])\n if(idx == null) return false\n for(let i = 1, len = p.length; i < len; i++) {\n console.log(m.has(p[i]))\n if(!m.has(p[i]) || arr[++idx] !== p[i]) return false\n }\n }\n return true\n};"
] |
|
1,641 | count-sorted-vowel-strings | [
"For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it.",
"Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character.",
"In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c)."
] | /**
* @param {number} n
* @return {number}
*/
var countVowelStrings = function(n) {
}; | Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.
A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet.
Example 1:
Input: n = 1
Output: 5
Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"].
Example 2:
Input: n = 2
Output: 15
Explanation: The 15 sorted strings that consist of vowels only are
["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"].
Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet.
Example 3:
Input: n = 33
Output: 66045
Constraints:
1 <= n <= 50
| Medium | [
"math",
"dynamic-programming",
"combinatorics"
] | [
"const countVowelStrings = function (n) {\n return (n + 4) * (n + 3) * (n + 2) * (n + 1) / 24\n};",
"const countVowelStrings = function (n) {\n let mem = [1, 1, 1, 1, 1];\n for (let i = 1; i < n; ++i) {\n const next = [0, 0, 0, 0, 0];\n let tmp = 0;\n for (let j = 4; j >= 0; --j) {\n tmp += mem[j];\n next[j] = tmp;\n }\n mem = next;\n }\n let sum = 0;\n for (let i of mem) {\n sum += i;\n }\n return sum;\n};",
"const countVowelStrings = function (n) {\n const dp = Array.from({ length: n + 1 }, () => Array(5))\n recur(n, 0)\n return dp[n][0]\n function recur(r, i) {\n if(r === 0) return 1\n if(i === 5) return 0\n if(dp[r][i] != null) return dp[r][i]\n let res = recur(r, i + 1)\n res += recur(r - 1, i)\n return dp[r][i] = res\n }\n};"
] |
|
1,642 | furthest-building-you-can-reach | [
"Assume the problem is to check whether you can reach the last building or not.",
"You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps.",
"Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b."
] | /**
* @param {number[]} heights
* @param {number} bricks
* @param {number} ladders
* @return {number}
*/
var furthestBuilding = function(heights, bricks, ladders) {
}; | You are given an integer array heights representing the heights of buildings, some bricks, and some ladders.
You start your journey from building 0 and move to the next building by possibly using bricks or ladders.
While moving from building i to building i+1 (0-indexed),
If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.
If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks.
Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.
Example 1:
Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
Output: 4
Explanation: Starting at building 0, you can follow these steps:
- Go to building 1 without using ladders nor bricks since 4 >= 2.
- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.
- Go to building 3 without using ladders nor bricks since 7 >= 6.
- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.
It is impossible to go beyond building 4 because you do not have any more bricks or ladders.
Example 2:
Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
Output: 7
Example 3:
Input: heights = [14,3,19,3], bricks = 17, ladders = 0
Output: 3
Constraints:
1 <= heights.length <= 105
1 <= heights[i] <= 106
0 <= bricks <= 109
0 <= ladders <= heights.length
| Medium | [
"array",
"greedy",
"heap-priority-queue"
] | [
"const furthestBuilding = function(heights, bricks, ladders) {\n const pq = new PriorityQueue((a, b) => a < b)\n const len = heights.length\n for(let i = 0; i < len - 1; i++) {\n const diff = heights[i + 1] - heights[i]\n if(diff > 0) pq.push(diff)\n if(pq.size() > ladders) {\n bricks -= pq.pop()\n }\n if(bricks < 0) return i\n }\n return len - 1\n};\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}"
] |
|
1,643 | kth-smallest-instructions | [
"There are nCr(row + column, row) possible instructions to reach (row, column).",
"Try building the instructions one step at a time. How many instructions start with \"H\", and how does this compare with k?"
] | /**
* @param {number[]} destination
* @param {number} k
* @return {string}
*/
var kthSmallestPath = function(destination, k) {
}; | Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination.
The instructions are represented as a string, where each character is either:
'H', meaning move horizontally (go right), or
'V', meaning move vertically (go down).
Multiple instructions will lead Bob to destination. For example, if destination is (2, 3), both "HHHVV" and "HVHVH" are valid instructions.
However, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed.
Given an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take Bob to destination.
Example 1:
Input: destination = [2,3], k = 1
Output: "HHHVV"
Explanation: All the instructions that reach (2, 3) in lexicographic order are as follows:
["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH", "HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"].
Example 2:
Input: destination = [2,3], k = 2
Output: "HHVHV"
Example 3:
Input: destination = [2,3], k = 3
Output: "HHVVH"
Constraints:
destination.length == 2
1 <= row, column <= 15
1 <= k <= nCr(row + column, row), where nCr(a, b) denotes a choose b.
| Hard | [
"array",
"math",
"dynamic-programming",
"combinatorics"
] | [
"const kthSmallestPath = function (destination, k) {\n let v = destination[0],\n h = destination[1]\n const mu = (c, n) => {\n let res = ''\n for (let i = 0; i < n; i++) {\n res += c\n }\n return res\n }\n\n let res = ''\n while (h > 0 && v > 0) {\n let pre = comb(h + v - 1, v)\n if (k <= pre) {\n res += 'H'\n h -= 1\n } else {\n res += 'V'\n v -= 1\n k -= pre\n }\n }\n if (h == 0) res += mu('V', v)\n if (v == 0) res += mu('H', h)\n return res\n}\n\nfunction product(a, b) {\n let prd = a,\n i = a\n\n while (i++ < b) {\n prd *= i\n }\n return prd\n}\n\nfunction comb(n, r) {\n if (n == r) {\n return 1\n } else {\n r = r < n - r ? n - r : r\n return product(r + 1, n) / product(1, n - r)\n }\n}",
"const kthSmallestPath = function (destination, k) {\n const [r, c] = destination;\n const ret = [];\n let remDown = r;\n for (let i = 0; i < r + c; i++) {\n const remSteps = r + c - (i + 1);\n const com = comb(remSteps, remDown);\n if (com >= k) ret.push(\"H\");\n else {\n remDown -= 1;\n k -= com;\n ret.push(\"V\");\n }\n }\n return ret.join(\"\");\n};\n\nfunction comb(n, r) {\n if (n < r) return 0;\n let res = 1;\n if (n - r < r) r = n - r;\n for (let i = n, j = 1; i >= 1 && j <= r; --i, ++j) {\n res = res * i;\n }\n for (let i = r; i >= 2; --i) {\n res = res / i;\n }\n return res;\n}"
] |
|
1,646 | get-maximum-in-generated-array | [
"Try generating the array.",
"Make sure not to fall in the base case of 0."
] | /**
* @param {number} n
* @return {number}
*/
var getMaximumGenerated = function(n) {
}; | You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way:
nums[0] = 0
nums[1] = 1
nums[2 * i] = nums[i] when 2 <= 2 * i <= n
nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n
Return the maximum integer in the array nums.
Example 1:
Input: n = 7
Output: 3
Explanation: According to the given rules:
nums[0] = 0
nums[1] = 1
nums[(1 * 2) = 2] = nums[1] = 1
nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2
nums[(2 * 2) = 4] = nums[2] = 1
nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3
nums[(3 * 2) = 6] = nums[3] = 2
nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3
Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3.
Example 2:
Input: n = 2
Output: 1
Explanation: According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1.
Example 3:
Input: n = 3
Output: 2
Explanation: According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2.
Constraints:
0 <= n <= 100
| Easy | [
"array",
"dynamic-programming",
"simulation"
] | [
"const arr = [0, 1, 1]\n\nconst getMaximumGenerated = function(n) {\n if(arr[n] != null) return Math.max(...arr.slice(0, n + 1))\n const oddOrEven = num => num % 2 === 0 ? 'even' : 'odd'\n const hi = arr.length - 1\n for(let i = hi + 1; i <= n; i++) {\n let tmp, chk = oddOrEven(i)\n if(chk === 'odd') tmp = arr[Math.floor(i / 2)] + arr[Math.floor(i / 2) + 1]\n else tmp = arr[Math.floor(i / 2)]\n arr[i] = tmp\n }\n return Math.max(...arr.slice(0, n + 1))\n};"
] |
|
1,647 | minimum-deletions-to-make-character-frequencies-unique | [
"As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one.",
"Sort the alphabet characters by their frequencies non-increasingly.",
"Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before."
] | /**
* @param {string} s
* @return {number}
*/
var minDeletions = function(s) {
}; | A string s is called good if there are no two different characters in s that have the same frequency.
Given a string s, return the minimum number of characters you need to delete to make s good.
The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1.
Example 1:
Input: s = "aab"
Output: 0
Explanation: s is already good.
Example 2:
Input: s = "aaabbbcc"
Output: 2
Explanation: You can delete two 'b's resulting in the good string "aaabcc".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".
Example 3:
Input: s = "ceabaacb"
Output: 2
Explanation: You can delete both 'c's resulting in the good string "eabaab".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
Constraints:
1 <= s.length <= 105
s contains only lowercase English letters.
| Medium | [
"hash-table",
"string",
"greedy",
"sorting"
] | [
"const minDeletions = function(s) {\n if (s == null || s.length <= 1) {\n return 0;\n }\n\n const map = new Map();\n for (let ch of s) {\n map.set(ch, (map.get(ch) || 0) + 1);\n }\n\n\n const frequencies = new Set();\n let minDeletions = 0;\n \n const vals = map.values()\n for (let frequency of vals) {\n if (!frequencies.has(frequency)) {\n frequencies.add(frequency);\n continue;\n }\n\n let curr = frequency;\n while (curr > 0 && frequencies.has(curr)) {\n curr--;\n minDeletions++;\n }\n\n if (curr > 0) {\n frequencies.add(curr);\n }\n }\n\n return minDeletions;\n};"
] |
|
1,648 | sell-diminishing-valued-colored-balls | [
"Greedily sell the most expensive ball.",
"There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold.",
"Use binary search to find this value k, and use maths to find the total sum."
] | /**
* @param {number[]} inventory
* @param {number} orders
* @return {number}
*/
var maxProfit = function(inventory, orders) {
}; | You have an inventory of different colored balls, and there is a customer that wants orders balls of any color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer).
You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order.
Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: inventory = [2,5], orders = 4
Output: 14
Explanation: Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).
The maximum total value is 2 + 5 + 4 + 3 = 14.
Example 2:
Input: inventory = [3,5], orders = 6
Output: 19
Explanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).
The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.
Constraints:
1 <= inventory.length <= 105
1 <= inventory[i] <= 109
1 <= orders <= min(sum(inventory[i]), 109)
| Medium | [
"array",
"math",
"binary-search",
"greedy",
"sorting",
"heap-priority-queue"
] | [
"const maxProfit = function(inventory, orders) {\n const bigIntMax = (...args) => args.reduce((m, e) => e > m ? e : m);\n inventory = inventory.map(e => BigInt(e))\n orders = BigInt(orders)\n let l = 0n, r = bigIntMax(...inventory)\n while(l < r) {\n const mid = l + (r - l) / 2n\n if(valid(mid)) l = mid + 1n\n else r = mid\n }\n \n // console.log(l)\n const mod = BigInt(1e9 + 7)\n let t = l, res = 0n, cnt = 0n\n for(const e of inventory) {\n if(e <= t) continue\n cnt += e - t\n res = (res + (t + 1n + e) * (e - t) / 2n) % mod\n }\n \n res = (res + (orders - cnt) * t) % mod\n \n return res\n \n function valid(mid) {\n let res = 0n\n for(const e of inventory) {\n if(e > mid) res += e - mid\n }\n return res > orders\n }\n};",
"function maxProfit(inventory, orders) {\n inventory.sort((a, b) => a - b)\n inventory = inventory.map(e => BigInt(e))\n let ans = 0n, n = inventory.length - 1, count = 1n\n const mod = BigInt(10 ** 9 + 7)\n orders = BigInt(orders)\n while(orders > 0n) {\n if(n > 0 && inventory[n] > inventory[n - 1] && orders >= count * (inventory[n] - inventory[n - 1])) {\n ans += count * sum(inventory[n - 1], inventory[n])\n orders -= count * (inventory[n] - inventory[n - 1])\n } else if(n === 0 || inventory[n] > inventory[n - 1]) {\n const num = orders / count\n ans += count * sum(inventory[n] - num, inventory[n])\n const remain = orders % count\n ans += remain * (inventory[n] - num)\n orders = 0n\n }\n ans %= mod\n n--\n count++\n }\n return ans\n}\n\nfunction sum(lo, hi) {\n return (hi - lo) * (lo + hi + 1n) / 2n\n}",
"const maxProfit = function (inventory, orders) {\n let Max = 1e9 + 7,\n Min = 0\n let mod = BigInt(1e9 + 7)\n while (Max > Min + 1) {\n let tot = 0\n let mid = ((Max + Min) >> 1)\n for (let it of inventory) {\n if (it > mid) tot += it - mid\n }\n if (tot > orders) Min = mid\n else Max = mid\n }\n let sum = BigInt(0)\n Max = BigInt(Max)\n orders = BigInt(orders)\n for (let it of inventory) {\n it = BigInt(it)\n if (it > Max) {\n sum += ((it + Max + BigInt(1)) * (it - Max)) / BigInt(2)\n orders -= it - Max\n }\n }\n sum += orders * Max\n \n return sum % mod\n}",
"var maxProfit = function(inventory, orders) {\n inventory.sort((a, b) => b - a)\n const mod = BigInt(1e9 + 7), n = BigInt(inventory.length)\n inventory = inventory.map(e => BigInt(e))\n orders = BigInt(orders)\n let cur = BigInt(inventory[0]), res = 0n, i = 0n\n const min = (a, b) => a > b ? b : a\n while(orders) {\n while(i < n && inventory[i] === cur) i++\n let next = i === n ? 0n : inventory[i]\n let h = cur - next, r = 0n, cnt = min(orders, i * h)\n if (orders < i * h) {\n h = orders / i\n r = orders % i\n }\n let val = cur - h\n res = (res + (cur + val + 1n) * h / 2n * i + val * r) % mod\n orders -= cnt\n cur = next\n }\n\n return res\n};",
"const maxProfit = function (inventory, orders) {\n inventory.sort((a, b) => b - a)\n const mod = BigInt(1e9 + 7),\n n = BigInt(inventory.length)\n inventory = inventory.map((e) => BigInt(e))\n orders = BigInt(orders)\n let cur = BigInt(inventory[0]),\n res = 0n,\n i = 0n\n const min = (a, b) => (a > b ? b : a)\n while (orders) {\n while (i < n && inventory[i] === cur) i++\n let next = i === n ? 0n : inventory[i]\n let h = cur - next,\n r = 0n,\n cnt = min(orders, i * h)\n if (orders < i * h) {\n h = orders / i\n r = orders % i\n }\n let val = cur - h\n res = (res + (((cur + val + 1n) * h) / 2n) * i + val * r) % mod\n orders -= cnt\n cur = next\n }\n\n return res\n}"
] |
|
1,649 | create-sorted-array-through-instructions | [
"This problem is closely related to finding the number of inversions in an array",
"if i know the position in which i will insert the i-th element in I can find the minimum cost to insert it"
] | /**
* @param {number[]} instructions
* @return {number}
*/
var createSortedArray = function(instructions) {
}; | Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following:
The number of elements currently in nums that are strictly less than instructions[i].
The number of elements currently in nums that are strictly greater than instructions[i].
For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5].
Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 109 + 7
Example 1:
Input: instructions = [1,5,6,2]
Output: 1
Explanation: Begin with nums = [].
Insert 1 with cost min(0, 0) = 0, now nums = [1].
Insert 5 with cost min(1, 0) = 0, now nums = [1,5].
Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6].
Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].
The total cost is 0 + 0 + 0 + 1 = 1.
Example 2:
Input: instructions = [1,2,3,6,5,4]
Output: 3
Explanation: Begin with nums = [].
Insert 1 with cost min(0, 0) = 0, now nums = [1].
Insert 2 with cost min(1, 0) = 0, now nums = [1,2].
Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3].
Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].
Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].
Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].
The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.
Example 3:
Input: instructions = [1,3,3,3,2,4,2,1,2]
Output: 4
Explanation: Begin with nums = [].
Insert 1 with cost min(0, 0) = 0, now nums = [1].
Insert 3 with cost min(1, 0) = 0, now nums = [1,3].
Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3].
Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].
Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].
Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].
Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].
Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].
Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].
The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.
Constraints:
1 <= instructions.length <= 105
1 <= instructions[i] <= 105
| Hard | [
"array",
"binary-search",
"divide-and-conquer",
"binary-indexed-tree",
"segment-tree",
"merge-sort",
"ordered-set"
] | [
"const lowBit = (x) => x & -x\nclass FenwickTree {\n constructor(n) {\n if (n < 1) return\n this.sum = Array(n + 1).fill(0)\n }\n update(i, delta) {\n if (i < 1) return\n while (i < this.sum.length) {\n this.sum[i] += delta\n i += lowBit(i)\n }\n }\n query(i) {\n if (i < 1) return 0\n let sum = 0\n while (i > 0) {\n sum += this.sum[i]\n i -= lowBit(i)\n }\n return sum\n }\n}\n\nconst createSortedArray = function(instructions) {\n let res = 0, n = instructions.length, mod = 10 ** 9 + 7\n const bit = new FenwickTree(10 ** 5)\n for(let i = 0; i < n; i++) {\n res = (res + Math.min(bit.query(instructions[i] - 1), i - bit.query(instructions[i]))) % mod\n bit.update(instructions[i], 1)\n }\n return res\n};",
"const createSortedArray = function (instructions) {\n const ins = instructions, n = ins.length\n let res = 0\n const mod = 1e9 + 7, { min } = Math\n const bit = new BIT(1e5)\n for(let i = 0; i < n; i++) {\n const cur = ins[i]\n res = (res + min(bit.query(cur - 1), i - bit.query(cur))) % mod\n bit.update(cur, 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}"
] |
|
1,652 | defuse-the-bomb | [
"As the array is circular, use modulo to find the correct index.",
"The constraints are low enough for a brute-force solution."
] | /**
* @param {number[]} code
* @param {number} k
* @return {number[]}
*/
var decrypt = function(code, k) {
}; | You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k.
To decrypt the code, you must replace every number. All the numbers are replaced simultaneously.
If k > 0, replace the ith number with the sum of the next k numbers.
If k < 0, replace the ith number with the sum of the previous k numbers.
If k == 0, replace the ith number with 0.
As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1].
Given the circular array code and an integer key k, return the decrypted code to defuse the bomb!
Example 1:
Input: code = [5,7,1,4], k = 3
Output: [12,10,16,13]
Explanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.
Example 2:
Input: code = [1,2,3,4], k = 0
Output: [0,0,0,0]
Explanation: When k is zero, the numbers are replaced by 0.
Example 3:
Input: code = [2,4,9,3], k = -2
Output: [12,5,6,13]
Explanation: The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previous numbers.
Constraints:
n == code.length
1 <= n <= 100
1 <= code[i] <= 100
-(n - 1) <= k <= n - 1
| Easy | [
"array"
] | [
"const decrypt = function(code, k) {\n const res = new Array(code.length).fill(0);\n if (k === 0) return res;\n let start = 1, end = k, sum = 0;\n if (k < 0) {\n k = -k;\n start = code.length - k;\n end = code.length - 1;\n }\n for (let i = start; i <= end; i++) sum += code[i];\n for (let i = 0; i < code.length; i++) {\n res[i] = sum;\n sum -= code[(start++) % code.length];\n sum += code[(++end) % code.length];\n }\n return res;\n};"
] |
|
1,653 | minimum-deletions-to-make-string-balanced | [
"You need to find for every index the number of Bs before it and the number of A's after it",
"You can speed up the finding of A's and B's in suffix and prefix using preprocessing"
] | /**
* @param {string} s
* @return {number}
*/
var minimumDeletions = function(s) {
}; | You are given a string s consisting only of characters 'a' and 'b'.
You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'.
Return the minimum number of deletions needed to make s balanced.
Example 1:
Input: s = "aababbab"
Output: 2
Explanation: You can either:
Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or
Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").
Example 2:
Input: s = "bbaaaaabb"
Output: 2
Explanation: The only solution is to delete the first two characters.
Constraints:
1 <= s.length <= 105
s[i] is 'a' or 'b'.
| Medium | [
"string",
"dynamic-programming",
"stack"
] | [
"const minimumDeletions = function(s) {\n let res = 0, b = 0\n for(const e of s) {\n if(e === 'b') b++\n else if(b > 0) {\n res++\n b--\n }\n }\n \n return res\n};",
"const minimumDeletions = function(s) {\n let res = 0\n let cnt = 0\n for(let c of s) {\n if(c === 'a' && cnt > 0) {\n res++\n cnt--\n } else if(c === 'b') {\n cnt++\n }\n }\n \n return res\n};",
"const minimumDeletions = function(s) {\n const len = s.length\n const dp = Array(len + 1).fill(0)\n let bcount = 0\n for(let i = 1; i <= len; i++) {\n if(s[i - 1] === 'a') {\n dp[i] = Math.min(dp[i - 1] + 1, bcount)\n } else {\n dp[i] = dp[i - 1]\n bcount++\n }\n }\n \n return dp[len]\n};",
"const minimumDeletions = function(s) {\n const len = s.length\n const stack = []\n let res = 0\n for(let i = 0; i < len; i++) {\n if(stack.length && stack[stack.length - 1] > s[i]) {\n res++\n stack.pop()\n } else {\n stack.push(s[i])\n }\n }\n return res\n};"
] |
|
1,654 | minimum-jumps-to-reach-home | [
"Think of the line as a graph",
"to handle the no double back jumps condition you can handle it by holding the state of your previous jump"
] | /**
* @param {number[]} forbidden
* @param {number} a
* @param {number} b
* @param {number} x
* @return {number}
*/
var minimumJumps = function(forbidden, a, b, x) {
}; | A certain bug's home is on the x-axis at position x. Help them get there from position 0.
The bug jumps according to the following rules:
It can jump exactly a positions forward (to the right).
It can jump exactly b positions backward (to the left).
It cannot jump backward twice in a row.
It cannot jump to any forbidden positions.
The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers.
Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1.
Example 1:
Input: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9
Output: 3
Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.
Example 2:
Input: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11
Output: -1
Example 3:
Input: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7
Output: 2
Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.
Constraints:
1 <= forbidden.length <= 1000
1 <= a, b, forbidden[i] <= 2000
0 <= x <= 2000
All the elements in forbidden are distinct.
Position x is not forbidden.
| Medium | [
"array",
"dynamic-programming",
"breadth-first-search"
] | [
"const minimumJumps = function (forbidden, a, b, x) {\n const bad = new Set()\n const set = new Set()\n for (let i of forbidden) {\n bad.add(i)\n }\n let q = []\n q.push([0, 0, 0])\n set.add('0,0')\n while (q.length) {\n const tmp = []\n const size = q.length\n for(let i = 0; i < size; i++) {\n const [pos, level, state] = q[i]\n\n if (pos === x) return level\n if (state >= 0) {\n if (pos <= 4000 && !set.has(pos + a + ',0') && !bad.has(pos + a)) {\n set.add(pos + a + ',0')\n tmp.push([pos + a, level + 1, 0])\n }\n if (!set.has(pos - b + ',-1') && !bad.has(pos - b) && pos - b >= 0) {\n set.add(pos - b + ',-1')\n tmp.push([pos - b, level + 1, -1])\n }\n } else if (state < 0) {\n if (pos <= 4000 && !set.has(pos + a + ',0') && !bad.has(pos + a)) {\n set.add(pos + a + ',0')\n tmp.push([pos + a, level + 1, 0])\n }\n } \n }\n\n q = tmp\n }\n return -1\n}",
"const minimumJumps = function (forbidden, a, b, x) {\n const bad = new Set()\n const set = new Set()\n for (let i of forbidden) {\n bad.add(i)\n }\n const q = []\n q.push([0, 0, 0])\n set.add('0,0')\n while (q.length) {\n const pair = q.shift()\n let pos = pair[0],\n level = pair[1],\n state = pair[2]\n if (pos == x) return level\n if (state >= 0) {\n if (pos <= 4000 && !set.has(pos + a + ',0') && !bad.has(pos + a)) {\n set.add(pos + a + ',0')\n q.push([pos + a, level + 1, 0])\n }\n if (!set.has(pos - b + ',-1') && !bad.has(pos - b) && pos - b >= 0) {\n set.add(pos - b + ',-1')\n q.push([pos - b, level + 1, -1])\n }\n } else if (state < 0) {\n if (pos <= 4000 && !set.has(pos + a + ',0') && !bad.has(pos + a)) {\n set.add(pos + a + ',0')\n q.push([pos + a, level + 1, 0])\n }\n }\n }\n return -1\n}"
] |
|
1,655 | distribute-repeating-integers | [
"Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3].",
"Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number.",
"Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to be assigned to this number."
] | /**
* @param {number[]} nums
* @param {number[]} quantity
* @return {boolean}
*/
var canDistribute = function(nums, quantity) {
}; | You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that:
The ith customer gets exactly quantity[i] integers,
The integers the ith customer gets are all equal, and
Every customer is satisfied.
Return true if it is possible to distribute nums according to the above conditions.
Example 1:
Input: nums = [1,2,3,4], quantity = [2]
Output: false
Explanation: The 0th customer cannot be given two different integers.
Example 2:
Input: nums = [1,2,3,3], quantity = [2]
Output: true
Explanation: The 0th customer is given [3,3]. The integers [1,2] are not used.
Example 3:
Input: nums = [1,1,2,2], quantity = [2,2]
Output: true
Explanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].
Constraints:
n == nums.length
1 <= n <= 105
1 <= nums[i] <= 1000
m == quantity.length
1 <= m <= 10
1 <= quantity[i] <= 105
There are at most 50 unique values in nums.
| Hard | [
"array",
"dynamic-programming",
"backtracking",
"bit-manipulation",
"bitmask"
] | [
"const canDistribute = function(nums, quantity) {\n const freq = new Map()\n for(const e of nums) {\n freq.set(e, (freq.get(e) || 0) + 1)\n }\n const cntArr = [...freq.values()]\n const n = cntArr.length, m = quantity.length, limit = 1 << m\n const dp = Array.from({ length: n + 1 }, () => Array(limit).fill(false))\n for(let i = 0; i < n; i++) {\n dp[i][0] = true\n }\n cntArr.unshift(0)\n const allMask = limit - 1\n \n for(let i = 1; i <= n; i++) {\n for(let mask = 1; mask <= allMask; mask++) {\n if(dp[i - 1][mask]) {\n dp[i][mask] = true\n continue\n }\n for(let subset = mask; subset > 0; subset = (subset - 1) & mask) {\n if(dp[i - 1][mask - subset] === false) continue\n if(canSatisfySubset(cntArr[i], subset)) {\n dp[i][mask] = true\n break\n }\n }\n }\n }\n \n return dp[n][allMask]\n \n function canSatisfySubset(cnt, subset) {\n let sum = 0\n for (let i = 0; i < m; i++) {\n if(subset & (1 << i)) {\n sum += quantity[i]\n }\n }\n return cnt >= sum\n }\n};",
"const canDistribute = function (nums, quantity) {\n const mp = {}\n for (let x of nums) {\n mp[x] = (mp[x] || 0) + 1\n }\n const values = Object.values(mp)\n quantity.sort((a, b) => b - a)\n let res = false\n dfs(0)\n return res\n\n function dfs(idx) {\n if(idx === quantity.length || res) {\n res = true\n return\n }\n for(let i = 0, len = values.length; i < len; i++) {\n if(values[i] >= quantity[idx]) {\n values[i] -= quantity[idx]\n dfs(idx + 1)\n values[i] += quantity[idx]\n }\n }\n }\n}",
"const canDistribute = function (nums, quantity) {\n const mp = {}\n for (let x of nums) {\n mp[x] = (mp[x] || 0) + 1\n }\n const a = []\n for (let p in mp) a.push(mp[p])\n const b = quantity\n const m = quantity.length\n const n = a.length\n const dp = Array.from({ length: n }, () => Array(1 << m).fill(-1))\n return solve(0, 0)\n\n function solve(idx, mask) {\n if (mask === (1 << m) - 1) return 1\n if (idx === n) return 0\n if (dp[idx][mask] !== -1) return dp[idx][mask]\n let ans = solve(idx + 1, mask)\n for (let i = 0, up = 1 << m; i < up; i++) {\n if (mask !== (mask & i)) continue\n let nm = mask\n let sum = 0\n for (let j = 0; j < m; j++) {\n if (mask & (1 << j)) continue\n if (i & (1 << j)) {\n sum += b[j]\n nm |= 1 << j\n }\n }\n if (sum <= a[idx]) ans |= solve(idx + 1, nm)\n }\n return (dp[idx][mask] = ans)\n }\n}",
"const canDistribute = function(nums, quantity) {\n const freq = {}\n for(let e of nums) freq[e] = (freq[e] || 0) + 1\n const fArr = Object.values(freq)\n\n const m = quantity.length, n = fArr.length\n const dp = Array.from({ length: n }, () => Array(1 << m).fill(-1))\n \n return solve(0, 0)\n \n function solve(idx, mask) {\n if(mask === (1 << m) - 1) return 1\n if(idx === n) return 0\n if(dp[idx][mask] !== -1) return dp[idx][mask]\n \n let res = solve(idx + 1, mask)\n for(let i = 0; i < (1 << m); i++) {\n if(mask !== (mask & i)) continue\n let tmp = mask\n let sum = 0\n for(let j = 0; j < m; j++) {\n if(mask & (1 << j)) continue\n if(i & (1 << j)) {\n sum += quantity[j]\n tmp |= (1 << j)\n }\n }\n if(sum <= fArr[idx]) res |= solve(idx + 1, tmp)\n }\n \n return dp[idx][mask] = res\n }\n};",
"const canDistribute = function (nums, quantity) {\n const hash = {}\n for(const e of nums) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n const cnts = Object.values(hash), m = quantity.length, n = cnts.length\n const dp = Array.from({ length: n }, () => Array(1 << m).fill(null))\n \n return helper(0, 0)\n\n function helper(idx, mask) {\n // mask are already selected candidates\n if(mask == (1 << m) - 1) {\n return true;\n }\n if(idx == n) {\n return false;\n }\n if(dp[idx][mask] != null) {\n return dp[idx][mask];\n }\n let ans = helper(idx + 1, mask);\n \n for(let i = 1; i < (1 << m); ++i) {\n // i are potential candidates in addition to already selected ones (from mask)\n // if i == mask, we can skip as the candidate is selected already\n // if mask != (mask & i) means that this candidate does not include selected ones e.g\n // mask = 3 (i.e 2 elements 1,2 in binary) and i = 4 (the third element in binary as 4 does not include 1 & 2), there we skip\n if(mask == i || mask != (mask & i)) continue;\n let sum = 0;\n for(let j = 0; j < m; ++j) {\n // mask << ~j is just a fancy way to do: if(mask & (1 << j)) that i've learned from @Uwi and this way you don't have to use \"(\", \")\"\n // what it does is simply pushing the jth bit to the 2^31 bit which is negative\n // thus if the jth bit is 1 then the value is less than zero and if its 0 then its greater or equal to zero\n if(mask << ~j >= 0 && i << ~j < 0) { // check that mask does not contain the new candidate and that the candidate is part of the potential candidate i\n sum += quantity[j];\n }\n }\n if(sum <= cnts[idx]) {\n ans |= helper(idx + 1, i);\n }\n if(ans) break; // if ans is true, then a solution exists and no further computation is required\n }\n dp[idx][mask] = ans;\n return ans;\n }\n}"
] |
|
1,656 | design-an-ordered-stream | [
"Maintain the next id that should be outputted.",
"Maintain the ids that were inserted in the stream.",
"Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break."
] | /**
* @param {number} n
*/
var OrderedStream = function(n) {
};
/**
* @param {number} idKey
* @param {string} value
* @return {string[]}
*/
OrderedStream.prototype.insert = function(idKey, value) {
};
/**
* Your OrderedStream object will be instantiated and called as such:
* var obj = new OrderedStream(n)
* var param_1 = obj.insert(idKey,value)
*/ | There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id.
Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values.
Implement the OrderedStream class:
OrderedStream(int n) Constructs the stream to take n values.
String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, then returns the largest possible chunk of currently inserted values that appear next in the order.
Example:
Input
["OrderedStream", "insert", "insert", "insert", "insert", "insert"]
[[5], [3, "ccccc"], [1, "aaaaa"], [2, "bbbbb"], [5, "eeeee"], [4, "ddddd"]]
Output
[null, [], ["aaaaa"], ["bbbbb", "ccccc"], [], ["ddddd", "eeeee"]]
Explanation
// Note that the values ordered by ID is ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"].
OrderedStream os = new OrderedStream(5);
os.insert(3, "ccccc"); // Inserts (3, "ccccc"), returns [].
os.insert(1, "aaaaa"); // Inserts (1, "aaaaa"), returns ["aaaaa"].
os.insert(2, "bbbbb"); // Inserts (2, "bbbbb"), returns ["bbbbb", "ccccc"].
os.insert(5, "eeeee"); // Inserts (5, "eeeee"), returns [].
os.insert(4, "ddddd"); // Inserts (4, "ddddd"), returns ["ddddd", "eeeee"].
// Concatentating all the chunks returned:
// [] + ["aaaaa"] + ["bbbbb", "ccccc"] + [] + ["ddddd", "eeeee"] = ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"]
// The resulting order is the same as the order above.
Constraints:
1 <= n <= 1000
1 <= id <= n
value.length == 5
value consists only of lowercase letters.
Each call to insert will have a unique id.
Exactly n calls will be made to insert.
| Easy | [
"array",
"hash-table",
"design",
"data-stream"
] | [
"const OrderedStream = function(n) {\n this.arr = Array(n + 1)\n this.ptr = 1\n};\n\n\nOrderedStream.prototype.insert = function(id, value) {\n \n this.arr[id] = value\n const res = []\n let i\n for(i = this.ptr, len = this.arr.length; i < len; i++) {\n if (this.arr[i] != null) res.push(this.arr[i])\n else {\n break\n }\n }\n this.ptr = i\n \n return res\n};"
] |
|
1,657 | determine-if-two-strings-are-close | [
"Operation 1 allows you to freely reorder the string.",
"Operation 2 allows you to freely reassign the letters' frequencies."
] | /**
* @param {string} word1
* @param {string} word2
* @return {boolean}
*/
var closeStrings = function(word1, word2) {
}; | Two strings are considered close if you can attain one from the other using the following operations:
Operation 1: Swap any two existing characters.
For example, abcde -> aecdb
Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)
You can use the operations on either string as many times as necessary.
Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.
Example 1:
Input: word1 = "abc", word2 = "bca"
Output: true
Explanation: You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc" -> "acb"
Apply Operation 1: "acb" -> "bca"
Example 2:
Input: word1 = "a", word2 = "aa"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
Example 3:
Input: word1 = "cabbba", word2 = "abbccc"
Output: true
Explanation: You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba" -> "caabbb"
Apply Operation 2: "caabbb" -> "baaccc"
Apply Operation 2: "baaccc" -> "abbccc"
Constraints:
1 <= word1.length, word2.length <= 105
word1 and word2 contain only lowercase English letters.
| Medium | [
"hash-table",
"string",
"sorting"
] | [
"const closeStrings = function(word1, word2) {\n const len1 = word1.length, len2 = word2.length\n if(len1 !== len2) return false\n const a = ('a').charCodeAt(0)\n const arr1 = Array(26).fill(0)\n const arr2 = Array(26).fill(0)\n for(let i = 0; i < len1; i++) {\n arr1[word1.charCodeAt(i) - a]++\n arr2[word2.charCodeAt(i) - a]++\n }\n return chk1(arr1, arr2)\n function chk1(a1, a2) {\n const a11 = a1.slice(0)\n a11.sort()\n const a22 = a2.slice(0)\n a22.sort()\n for(let i = 0, len = a1.length; i < len; i++) {\n if((a1[i] !== 0 && a2[i] === 0) || (a1[i] === 0 && a2[i] !== 0) ) return false\n }\n for(let i = 0, len = a1.length; i < len; i++) {\n if(a11[i] !== a22[i]) return false\n }\n return true\n }\n};"
] |
|
1,658 | minimum-operations-to-reduce-x-to-zero | [
"Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray.",
"Finding the maximum subarray is standard and can be done greedily."
] | /**
* @param {number[]} nums
* @param {number} x
* @return {number}
*/
var minOperations = function(nums, x) {
}; | You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.
Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1.
Example 1:
Input: nums = [1,1,4,2,3], x = 5
Output: 2
Explanation: The optimal solution is to remove the last two elements to reduce x to zero.
Example 2:
Input: nums = [5,6,7,8,9], x = 4
Output: -1
Example 3:
Input: nums = [3,2,20,1,1,3], x = 10
Output: 5
Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 104
1 <= x <= 109
| Medium | [
"array",
"hash-table",
"binary-search",
"sliding-window",
"prefix-sum"
] | [
"const minOperations = function(nums, x) {\n const sum = nums.reduce((ac, e) => ac + e, 0)\n const subArrSum = sum - x\n if(subArrSum === 0) return nums.length\n const n = nums.length, hash = {0: -1}\n let ac = 0, res = -1\n for(let i = 0; i < n; i++) {\n const cur = nums[i]\n ac += cur\n if(hash[ac - subArrSum] != null) {\n res = Math.max(res, i - hash[ac - subArrSum])\n }\n hash[ac] = i\n }\n \n return res === -1 ? -1 : n - res\n};",
"const minOperations = function (nums, x) {\n let l = 0,\n r = nums.length - 1;\n while (x >= 0 && r >= l) {\n x -= nums[r];\n r -= 1;\n }\n if (r < 0 && x > 0) {\n return -1;\n } else if (r < 0 && x == 0) {\n return nums.length;\n }\n\n let ans = Number.MAX_VALUE;\n while (r < nums.length) {\n while (x <= 0 && r + 1 < nums.length) {\n if (x == 0) ans = Math.min(ans, nums.length - (r - l + 1));\n x += nums[r + 1];\n r += 1;\n }\n if (r + 1 >= nums.length) {\n if (x == 0) ans = Math.min(ans, nums.length - (r - l + 1));\n break;\n }\n while (x >= 0) {\n if (x == 0) ans = Math.min(ans, nums.length - (r - l + 1));\n x -= nums[l];\n l += 1;\n }\n }\n return ans != Number.MAX_VALUE ? ans : -1;\n};"
] |
|
1,659 | maximize-grid-happiness | [
"For each cell, it has 3 options, either it is empty, or contains an introvert, or an extrovert.",
"You can do DP where you maintain the state of the previous row, the number of remaining introverts and extroverts, the current row and column, and try the 3 options for each cell.",
"Assume that the previous columns in the current row already belong to the previous row."
] | /**
* @param {number} m
* @param {number} n
* @param {number} introvertsCount
* @param {number} extrovertsCount
* @return {number}
*/
var getMaxGridHappiness = function(m, n, introvertsCount, extrovertsCount) {
}; | You are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts.
You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid.
The happiness of each person is calculated as follows:
Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert).
Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert).
Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell.
The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness.
Example 1:
Input: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2
Output: 240
Explanation: Assume the grid is 1-indexed with coordinates (row, column).
We can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).
- Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120
- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60
- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60
The grid happiness is 120 + 60 + 60 = 240.
The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.
Example 2:
Input: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1
Output: 260
Explanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).
- Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90
- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80
- Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90
The grid happiness is 90 + 80 + 90 = 260.
Example 3:
Input: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0
Output: 240
Constraints:
1 <= m, n <= 5
0 <= introvertsCount, extrovertsCount <= min(m * n, 6)
| Hard | [
"dynamic-programming",
"bit-manipulation",
"memoization",
"bitmask"
] | [
"const getMaxGridHappiness = (m, n, introvertsCount, extrovertsCount) => {\n const state = '0'.repeat(n)\n const memo = new Map()\n return helper(state, 0, n, m, introvertsCount, extrovertsCount, memo)\n}\nfunction helper(state, idx, n, m, inCount, exCount, memo) {\n if ((inCount === 0 && exCount === 0) || idx === m * n) return 0\n let key = idx + state + inCount + exCount\n if (memo.has(key)) return memo.get(key)\n const r = (idx / n) >> 0,\n c = idx % n\n let best = 0\n if (inCount !== 0) {\n let score = 120\n if (r > 0) score = calc(state.charAt(0) - '0', 1, score)\n if (c !== 0) score = calc(state.charAt(state.length - 1) - '0', 1, score)\n best =\n score +\n helper(state.slice(1) + '1', idx + 1, n, m, inCount - 1, exCount, memo)\n }\n if (exCount !== 0) {\n let score = 40\n if (r > 0) score = calc(state.charAt(0) - '0', 2, score)\n if (c !== 0) score = calc(state.charAt(state.length - 1) - '0', 2, score)\n best = Math.max(\n best,\n score +\n helper(state.slice(1) + '2', idx + 1, n, m, inCount, exCount - 1, memo)\n )\n }\n best = Math.max(\n best,\n helper(state.slice(1) + '0', idx + 1, n, m, inCount, exCount, memo)\n )\n memo.set(key, best)\n return best\n}\n\nfunction calc(p1, p2, score) {\n if (p1 === 1 && p2 === 1) return score - 60\n else if (p1 === 2 && p2 === 2) return score + 40\n else if (p1 === 1 && p2 === 2) return score - 10\n else if (p1 === 2 && p2 === 1) return score - 10\n return score\n}"
] |
|
1,662 | check-if-two-string-arrays-are-equivalent | [
"Concatenate all strings in the first array into a single string in the given order, the same for the second array.",
"Both arrays represent the same string if and only if the generated strings are the same."
] | /**
* @param {string[]} word1
* @param {string[]} word2
* @return {boolean}
*/
var arrayStringsAreEqual = function(word1, word2) {
}; | Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.
A string is represented by an array if the array elements concatenated in order forms the string.
Example 1:
Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
Output: true
Explanation:
word1 represents string "ab" + "c" -> "abc"
word2 represents string "a" + "bc" -> "abc"
The strings are the same, so return true.
Example 2:
Input: word1 = ["a", "cb"], word2 = ["ab", "c"]
Output: false
Example 3:
Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]
Output: true
Constraints:
1 <= word1.length, word2.length <= 103
1 <= word1[i].length, word2[i].length <= 103
1 <= sum(word1[i].length), sum(word2[i].length) <= 103
word1[i] and word2[i] consist of lowercase letters.
| Easy | [
"array",
"string"
] | [
"const arrayStringsAreEqual = function(word1, word2) {\n return word1.join('') === word2.join('')\n};"
] |
|
1,663 | smallest-string-with-a-given-numeric-value | [
"Think greedily.",
"If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index."
] | /**
* @param {number} n
* @param {number} k
* @return {string}
*/
var getSmallestString = function(n, k) {
}; | The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.
The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8.
You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k.
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: n = 3, k = 27
Output: "aay"
Explanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.
Example 2:
Input: n = 5, k = 73
Output: "aaszz"
Constraints:
1 <= n <= 105
n <= k <= 26 * n
| Medium | [
"string",
"greedy"
] | [
"const getSmallestString = function(n, k) {\n let arr = Array(n).fill(1)\n k -= n \n for(let i = n - 1; i >= 0; i--) {\n if(k > 0) {\n const delta = 26 - arr[i]\n if(k >= delta) {\n k -= delta\n arr[i] = arr[i] + delta\n } else {\n arr[i] = arr[i] + k\n k = 0\n }\n } else break\n }\n const str = 'abcdefghijklmnopqrstuvwxyz'\n const m = {}\n for(let i = 0; i < 26; i++) {\n m[i + 1] = str[i]\n }\n const res = []\n for(let i = 0; i < n; i++) {\n res[i] = m[arr[i]]\n }\n return res.join('')\n};"
] |
|
1,664 | ways-to-make-a-fair-array | [
"The parity of the indices after the removed element changes.",
"Calculate prefix sums for even and odd indices separately to calculate for each index in O(1)."
] | /**
* @param {number[]} nums
* @return {number}
*/
var waysToMakeFair = function(nums) {
}; | You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.
For example, if nums = [6,1,7,4,1]:
Choosing to remove index 1 results in nums = [6,7,4,1].
Choosing to remove index 2 results in nums = [6,1,4,1].
Choosing to remove index 4 results in nums = [6,1,7,4].
An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.
Return the number of indices that you could choose such that after the removal, nums is fair.
Example 1:
Input: nums = [2,1,6,4]
Output: 1
Explanation:
Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.
Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.
Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.
Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.
There is 1 index that you can remove to make nums fair.
Example 2:
Input: nums = [1,1,1]
Output: 3
Explanation: You can remove any index and the remaining array is fair.
Example 3:
Input: nums = [1,2,3]
Output: 0
Explanation: You cannot make a fair array after removing any index.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 104
| Medium | [
"array",
"dynamic-programming"
] | [
"const waysToMakeFair = function(nums) {\n const n = nums.length, right = Array(2).fill(0), left = Array(2).fill(0)\n let res = 0\n for(let i = 0; i < n; i++) right[i % 2] += nums[i]\n for(let i = 0; i < n; i++) {\n right[i % 2] -= nums[i]\n if(left[0] + right[1] === left[1] + right[0]) res++\n left[i % 2] += nums[i]\n }\n return res\n};",
"const waysToMakeFair = function (nums) {\n const n = nums.length\n const preOddSum = new Array(n + 1).fill(0)\n const preEvenSum = new Array(n + 1).fill(0)\n for (let i = 0; i < n; i++) {\n if (i % 2 === 0) {\n preEvenSum[i + 1] = nums[i] + preEvenSum[i]\n preOddSum[i + 1] = preOddSum[i]\n } else {\n preOddSum[i + 1] = nums[i] + preOddSum[i]\n preEvenSum[i + 1] = preEvenSum[i]\n }\n }\n let ret = 0\n for (let i = 0; i < n; i++) {\n if (\n preEvenSum[i] + preOddSum[n] - preOddSum[i + 1] ===\n preOddSum[i] + preEvenSum[n] - preEvenSum[i + 1]\n )\n ret++\n }\n return ret\n}"
] |
|
1,665 | minimum-initial-energy-to-finish-tasks | [
"We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable",
"Figure a sorting pattern"
] | /**
* @param {number[][]} tasks
* @return {number}
*/
var minimumEffort = function(tasks) {
}; | You are given an array tasks where tasks[i] = [actuali, minimumi]:
actuali is the actual amount of energy you spend to finish the ith task.
minimumi is the minimum amount of energy you require to begin the ith task.
For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it.
You can finish the tasks in any order you like.
Return the minimum initial amount of energy you will need to finish all the tasks.
Example 1:
Input: tasks = [[1,2],[2,4],[4,8]]
Output: 8
Explanation:
Starting with 8 energy, we finish the tasks in the following order:
- 3rd task. Now energy = 8 - 4 = 4.
- 2nd task. Now energy = 4 - 2 = 2.
- 1st task. Now energy = 2 - 1 = 1.
Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.
Example 2:
Input: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]
Output: 32
Explanation:
Starting with 32 energy, we finish the tasks in the following order:
- 1st task. Now energy = 32 - 1 = 31.
- 2nd task. Now energy = 31 - 2 = 29.
- 3rd task. Now energy = 29 - 10 = 19.
- 4th task. Now energy = 19 - 10 = 9.
- 5th task. Now energy = 9 - 8 = 1.
Example 3:
Input: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]
Output: 27
Explanation:
Starting with 27 energy, we finish the tasks in the following order:
- 5th task. Now energy = 27 - 5 = 22.
- 2nd task. Now energy = 22 - 2 = 20.
- 3rd task. Now energy = 20 - 3 = 17.
- 1st task. Now energy = 17 - 1 = 16.
- 4th task. Now energy = 16 - 4 = 12.
- 6th task. Now energy = 12 - 6 = 6.
Constraints:
1 <= tasks.length <= 105
1 <= actuali <= minimumi <= 104
| Hard | [
"array",
"greedy",
"sorting"
] | [
"const minimumEffort = function (tasks) {\n tasks.sort((a, b) => a[1] - a[0] > b[1] - b[0] ? 1 : -1)\n let res = 0\n for(let e of tasks) {\n res = Math.max(res + e[0], e[1])\n }\n return res\n}",
"const minimumEffort = function (a) {\n let low = 0,\n high = 1e9\n for (let x of a) low = Math.max(low, x[1])\n a.sort((lhs, rhs) => (lhs[1] - lhs[0] > rhs[1] - rhs[0] ? -1 : 1))\n let n = a.length\n while (low != high) {\n let mid = low + ((high - low) >> 1)\n let found = false\n let rem = mid\n for (let i = 0; i < n; ++i) {\n if (rem < a[i][1]) {\n found = true\n break\n }\n rem -= a[i][0]\n }\n if (found) {\n low = mid + 1\n } else {\n high = mid\n }\n }\n return high\n}"
] |
|
1,668 | maximum-repeating-substring | [
"The constraints are low enough for a brute force approach.",
"Try every k value from 0 upwards until word is no longer k-repeating."
] | /**
* @param {string} sequence
* @param {string} word
* @return {number}
*/
var maxRepeating = function(sequence, word) {
}; | For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0.
Given strings sequence and word, return the maximum k-repeating value of word in sequence.
Example 1:
Input: sequence = "ababc", word = "ab"
Output: 2
Explanation: "abab" is a substring in "ababc".
Example 2:
Input: sequence = "ababc", word = "ba"
Output: 1
Explanation: "ba" is a substring in "ababc". "baba" is not a substring in "ababc".
Example 3:
Input: sequence = "ababc", word = "ac"
Output: 0
Explanation: "ac" is not a substring in "ababc".
Constraints:
1 <= sequence.length <= 100
1 <= word.length <= 100
sequence and word contains only lowercase English letters.
| Easy | [
"string",
"string-matching"
] | [
"const maxRepeating = function(sequence, word) {\n let count = 1;\n while (sequence.includes(word.repeat(count))) count += 1\n return count - 1;\n};",
"const maxRepeating = function(sequence, word) {\n const s = sequence.length, w = word.length\n const max_repeat = (s / w) >> 0\n const failure = Array(w * max_repeat + 1).fill(0)\n const repeat_words = word.repeat(max_repeat) + '$'\n let result = 0, j = 0\n \n for(let i = 1, hi = repeat_words.length; i < hi; i++) {\n while(j > 0 && repeat_words[j] !== repeat_words[i]) j = failure[j - 1]\n j += (repeat_words[j] === repeat_words[i] ? 1 : 0)\n failure[i] = j\n }\n\n j = 0\n for(let i = 0, len = sequence.length; i < len; i++) {\n while(j > 0 && repeat_words[j] !== sequence[i]) j = failure[j - 1]\n j += (repeat_words[j] === sequence[i] ? 1 : 0)\n result = Math.max(result, (j / w) >> 0)\n }\n return result\n};"
] |
|
1,669 | merge-in-between-linked-lists | [
"Check which edges need to be changed.",
"Let the next node of the (a-1)th node of list1 be the 0-th node in list 2.",
"Let the next node of the last node of list2 be the (b+1)-th node in list 1."
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {number} a
* @param {number} b
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeInBetween = function(list1, a, b, list2) {
}; | You are given two linked lists: list1 and list2 of sizes n and m respectively.
Remove list1's nodes from the ath node to the bth node, and put list2 in their place.
The blue edges and nodes in the following figure indicate the result:
Build the result list and return its head.
Example 1:
Input: list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
Output: [0,1,2,1000000,1000001,1000002,5]
Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.
Example 2:
Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
Output: [0,1,1000000,1000001,1000002,1000003,1000004,6]
Explanation: The blue edges and nodes in the above figure indicate the result.
Constraints:
3 <= list1.length <= 104
1 <= a <= b < list1.length - 1
1 <= list2.length <= 104
| Medium | [
"linked-list"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const mergeInBetween = function(list1, a, b, list2) {\n const dummy = new ListNode()\n dummy.next = list1\n let cur = dummy\n let tail\n let idx = -1\n while(cur) {\n if(cur.next && idx + 1 === a) {\n tail = cur\n const tmp = cur.next\n cur.next = null\n cur = tmp\n idx++\n break\n }\n cur = cur.next\n idx++\n }\n let head\n // console.log(idx)\n while(cur) {\n if(idx === b) {\n head = cur.next\n cur.next = null\n break\n }\n cur = cur.next\n idx++\n }\n \n tail.next = list2\n cur = list2\n while(cur) {\n if(cur.next == null) {\n cur.next = head\n break\n }\n cur = cur.next\n }\n \n \n return dummy.next\n};"
] |
1,670 | design-front-middle-back-queue | [
"The constraints are low enough for a brute force, single array approach.",
"For an O(1) per method approach, use 2 double-ended queues: one for the first half and one for the second half."
] |
var FrontMiddleBackQueue = function() {
};
/**
* @param {number} val
* @return {void}
*/
FrontMiddleBackQueue.prototype.pushFront = function(val) {
};
/**
* @param {number} val
* @return {void}
*/
FrontMiddleBackQueue.prototype.pushMiddle = function(val) {
};
/**
* @param {number} val
* @return {void}
*/
FrontMiddleBackQueue.prototype.pushBack = function(val) {
};
/**
* @return {number}
*/
FrontMiddleBackQueue.prototype.popFront = function() {
};
/**
* @return {number}
*/
FrontMiddleBackQueue.prototype.popMiddle = function() {
};
/**
* @return {number}
*/
FrontMiddleBackQueue.prototype.popBack = function() {
};
/**
* Your FrontMiddleBackQueue object will be instantiated and called as such:
* var obj = new FrontMiddleBackQueue()
* obj.pushFront(val)
* obj.pushMiddle(val)
* obj.pushBack(val)
* var param_4 = obj.popFront()
* var param_5 = obj.popMiddle()
* var param_6 = obj.popBack()
*/ | Design a queue that supports push and pop operations in the front, middle, and back.
Implement the FrontMiddleBack class:
FrontMiddleBack() Initializes the queue.
void pushFront(int val) Adds val to the front of the queue.
void pushMiddle(int val) Adds val to the middle of the queue.
void pushBack(int val) Adds val to the back of the queue.
int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1.
int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1.
int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1.
Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example:
Pushing 6 into the middle of [1, 2, 3, 4, 5] results in [1, 2, 6, 3, 4, 5].
Popping the middle from [1, 2, 3, 4, 5, 6] returns 3 and results in [1, 2, 4, 5, 6].
Example 1:
Input:
["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"]
[[], [1], [2], [3], [4], [], [], [], [], []]
Output:
[null, null, null, null, null, 1, 3, 4, 2, -1]
Explanation:
FrontMiddleBackQueue q = new FrontMiddleBackQueue();
q.pushFront(1); // [1]
q.pushBack(2); // [1, 2]
q.pushMiddle(3); // [1, 3, 2]
q.pushMiddle(4); // [1, 4, 3, 2]
q.popFront(); // return 1 -> [4, 3, 2]
q.popMiddle(); // return 3 -> [4, 2]
q.popMiddle(); // return 4 -> [2]
q.popBack(); // return 2 -> []
q.popFront(); // return -1 -> [] (The queue is empty)
Constraints:
1 <= val <= 109
At most 1000 calls will be made to pushFront, pushMiddle, pushBack, popFront, popMiddle, and popBack.
| Medium | [
"array",
"linked-list",
"design",
"queue",
"data-stream"
] | [
"const FrontMiddleBackQueue = function() {\n this.arr = []\n};\n\n\nFrontMiddleBackQueue.prototype.pushFront = function(val) {\n this.arr.unshift(val)\n};\n\n\nFrontMiddleBackQueue.prototype.pushMiddle = function(val) {\n const len = this.arr.length\n const mid = Math.floor(len / 2)\n this.arr.splice(mid, 0, val)\n};\n\n\nFrontMiddleBackQueue.prototype.pushBack = function(val) {\n this.arr.push(val)\n};\n\n\nFrontMiddleBackQueue.prototype.popFront = function() {\n const tmp = this.arr.shift()\n return tmp == null ? -1 : tmp\n};\n\n\nFrontMiddleBackQueue.prototype.popMiddle = function() {\n const len = this.arr.length\n const mid = len % 2 === 0 ? Math.floor(len / 2) - 1 : ((len / 2) >> 0)\n if(len === 2) return this.arr.shift()\n const [tmp] = this.arr.splice(mid, 1)\n return tmp == null ? -1 : tmp\n};\n\n\nFrontMiddleBackQueue.prototype.popBack = function() {\n const tmp = this.arr.pop()\n return tmp == null ? -1 : tmp\n};"
] |
|
1,671 | minimum-number-of-removals-to-make-mountain-array | [
"Think the opposite direction instead of minimum elements to remove the maximum mountain subsequence",
"Think of LIS it's kind of close"
] | /**
* @param {number[]} nums
* @return {number}
*/
var minimumMountainRemovals = function(nums) {
}; | You may recall that an array arr is a mountain array if and only if:
arr.length >= 3
There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given an integer array nums, return the minimum number of elements to remove to make nums a mountain array.
Example 1:
Input: nums = [1,3,1]
Output: 0
Explanation: The array itself is a mountain array so we do not need to remove any elements.
Example 2:
Input: nums = [2,1,1,5,6,2,3,1]
Output: 3
Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].
Constraints:
3 <= nums.length <= 1000
1 <= nums[i] <= 109
It is guaranteed that you can make a mountain array out of nums.
| Hard | [
"array",
"binary-search",
"dynamic-programming",
"greedy"
] | [
"const minimumMountainRemovals = function(nums) {\n const inc = LIS(nums)\n const dec = LIS(nums.slice().reverse()).reverse()\n let res = 0\n for(let i = 0, len = nums.length; i < len; i++) {\n if(inc[i] > 1 && dec[i] > 1) res = Math.max(res, inc[i] + dec[i] - 1)\n }\n return nums.length - res\n};\n\nfunction LIS(arr) {\n const stack = []\n const res = []\n for(let e of arr) {\n if((stack.length && e > stack[stack.length - 1]) || stack.length === 0) {\n stack.push(e)\n res.push(stack.length)\n continue\n }\n let l = 0, r = stack.length - 1\n while(l < r) {\n const mid = l + ((r - l) >> 1)\n if(stack[mid] < e) l = mid + 1\n else r = mid\n }\n stack[l] = e\n res.push(stack.length)\n }\n \n return res\n}",
"const minimumMountainRemovals = function (nums) {\n if (nums.length <= 3) return 0\n const n = nums.length\n const inc = Array(n).fill(0)\n const dec = Array(n).fill(0)\n const { max, min } = Math\n for (let i = 1; i < n; i++) {\n for (let j = 0; j < i; j++) {\n if (nums[i] > nums[j]) inc[i] = max(inc[i], inc[j] + 1)\n }\n }\n for (let i = n - 2; i >= 0; i--) {\n for (let j = n - 1; j > i; j--) {\n if (nums[i] > nums[j]) dec[i] = max(dec[i], dec[j] + 1)\n }\n }\n let res = 0\n for (let i = 0; i < n; i++) {\n if (inc[i] > 0 && dec[i] > 0) res = max(res, inc[i] + dec[i])\n }\n return n - res - 1\n}"
] |
|
1,672 | richest-customer-wealth | [
"Calculate the wealth of each customer",
"Find the maximum element in array."
] | /**
* @param {number[][]} accounts
* @return {number}
*/
var maximumWealth = function(accounts) {
}; | You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the ith customer has in the jth bank. Return the wealth that the richest customer has.
A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.
Example 1:
Input: accounts = [[1,2,3],[3,2,1]]
Output: 6
Explanation:
1st customer has wealth = 1 + 2 + 3 = 6
2nd customer has wealth = 3 + 2 + 1 = 6
Both customers are considered the richest with a wealth of 6 each, so return 6.
Example 2:
Input: accounts = [[1,5],[7,3],[3,5]]
Output: 10
Explanation:
1st customer has wealth = 6
2nd customer has wealth = 10
3rd customer has wealth = 8
The 2nd customer is the richest with a wealth of 10.
Example 3:
Input: accounts = [[2,8,7],[7,1,3],[1,9,5]]
Output: 17
Constraints:
m == accounts.length
n == accounts[i].length
1 <= m, n <= 50
1 <= accounts[i][j] <= 100
| Easy | [
"array",
"matrix"
] | [
"const maximumWealth = function(accounts) {\n let max = -Infinity\n const m = accounts.length, n = accounts[0].length\n for(let i = 0; i < m; i++) {\n let tmp = 0\n for(let j = 0; j < n; j++) {\n tmp += accounts[i][j]\n }\n max = Math.max(max, tmp)\n }\n return max\n};"
] |
|
1,673 | find-the-most-competitive-subsequence | [
"In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?"
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var mostCompetitive = function(nums, k) {
}; | Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.
An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5.
Example 1:
Input: nums = [3,5,2,6], k = 2
Output: [2,6]
Explanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.
Example 2:
Input: nums = [2,4,3,3,5,4,9,6], k = 4
Output: [2,3,3,4]
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
1 <= k <= nums.length
| Medium | [
"array",
"stack",
"greedy",
"monotonic-stack"
] | [
"const mostCompetitive = function (nums, k) {\n const res = new Array(k).fill(0)\n let start = -1\n let idx = 0\n for (let i = k; i > 0; i--) {\n let min = Number.MAX_VALUE\n for (let j = start + 1; j < nums.length - i + 1; j++) {\n if (nums[j] < min) {\n start = j\n min = nums[j]\n }\n }\n res[idx++] = min\n }\n return res\n}",
"const mostCompetitive = function (nums, k) {\n const stack = [],\n n = nums.length\n let i = 0\n while (i < n) {\n while (\n stack.length &&\n stack[stack.length - 1] > nums[i] &&\n n - i + stack.length > k\n )\n stack.pop()\n if (stack.length < k) stack.push(nums[i])\n i++\n }\n return stack\n}",
"const mostCompetitive = function (nums, k) {\n const n = nums.length, stack = []\n for(let i = 0; i < n; i++) {\n const ch = nums[i]\n while(\n stack.length &&\n ch < stack[stack.length - 1] &&\n stack.length + (n - 1 - i) >= k\n ) {\n stack.pop()\n }\n if(stack.length < k) stack.push(ch)\n }\n return stack\n}"
] |
|
1,674 | minimum-moves-to-make-array-complementary | [
"Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications.",
"Can you find the optimal target sum x value such that the sum of modifications is minimized?",
"Create a difference array to efficiently sum all the modifications."
] | /**
* @param {number[]} nums
* @param {number} limit
* @return {number}
*/
var minMoves = function(nums, limit) {
}; | You are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive.
The array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i, nums[i] + nums[n - 1 - i] = 5.
Return the minimum number of moves required to make nums complementary.
Example 1:
Input: nums = [1,2,4,3], limit = 4
Output: 1
Explanation: In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).
nums[0] + nums[3] = 1 + 3 = 4.
nums[1] + nums[2] = 2 + 2 = 4.
nums[2] + nums[1] = 2 + 2 = 4.
nums[3] + nums[0] = 3 + 1 = 4.
Therefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary.
Example 2:
Input: nums = [1,2,2,1], limit = 2
Output: 2
Explanation: In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit.
Example 3:
Input: nums = [1,2,1,2], limit = 2
Output: 0
Explanation: nums is already complementary.
Constraints:
n == nums.length
2 <= n <= 105
1 <= nums[i] <= limit <= 105
n is even.
| Medium | [
"array",
"hash-table",
"prefix-sum"
] | [
"const minMoves = function (nums, limit) {\n const { min, max } = Math\n const n = nums.length\n const delta = Array(limit * 2 + 2).fill(0)\n for (let i = 0; i < n / 2; i++) {\n const lo = 1 + min(nums[i], nums[n - i - 1])\n const hi = limit + max(nums[i], nums[n - i - 1])\n const sum = nums[i] + nums[n - i - 1]\n delta[lo]--\n delta[sum]--\n delta[sum + 1]++\n delta[hi + 1]++\n }\n let now = n\n let ans = n\n for (let i = 2; i <= limit * 2; i++) {\n now += delta[i]\n ans = min(ans, now)\n }\n return ans\n}",
"const minMoves = function (nums, limit) {\n const n = nums.length, { max, min } = Math\n const delta = Array(2 * limit + 2).fill(0)\n for(let i = 0; i < n / 2; i++) {\n const a = nums[i], b = nums[n - 1 - i]\n // [2, min(a, b) + 1)\n delta[2] += 2\n // [min(a, b) + 1, a + b)\n delta[min(a, b) + 1] -= 1\n delta[a + b]--\n // [a + b + 1, max(a, b) + limit]\n delta[a + b + 1] += 1\n // (max(a, b) + limit, 2 * limit]\n delta[max(a, b) + limit + 1] +=1\n }\n \n let res = n, cur = 0\n for(let i = 2; i <= limit * 2; i++) {\n cur += delta[i]\n res = min(cur, res)\n }\n \n return res\n}",
"const minMoves = function (nums, limit) {\n const n = nums.length, { min, max } = Math\n const arr = Array(2 * limit + 2).fill(0)\n for(let i = 0, r = n / 2; i < r; i++) {\n const a = nums[i], b = nums[n - 1 - i]\n arr[2] += 2\n arr[min(a, b) + 1]--\n arr[a + b]--\n arr[a + b + 1]++\n arr[max(a, b) + limit + 1]++\n }\n let res = Infinity, cur = 0\n for(let i = 2, r = 2 * limit; i <= r; i++) {\n cur += arr[i]\n res = min(res, cur)\n }\n \n return res\n}",
"const minMoves = function (nums, limit) {\n const n = nums.length, { min, max } = Math\n const arr = Array(2 * limit + 2).fill(0)\n for(let i = 0, r = n / 2; i < r; i++) {\n const a = nums[i], b = nums[n - 1 - i]\n // [2, 2 * limit]\n arr[2] += 2\n arr[2 * limit + 1] -= 2\n // [min(a, b) + 1, max(a, b) + limit]\n arr[min(a, b) + 1]--\n arr[max(a, b) + limit + 1]++\n // a + b\n arr[a + b]--\n arr[a + b + 1]++\n\n }\n let res = Infinity, cur = 0\n for(let i = 2, r = 2 * limit; i <= r; i++) {\n cur += arr[i]\n res = min(res, cur)\n }\n \n return res\n}"
] |
|
1,675 | minimize-deviation-in-array | [
"Assume you start with the minimum possible value for each number so you can only multiply a number by 2 till it reaches its maximum possible value.",
"If there is a better solution than the current one, then it must have either its maximum value less than the current maximum value, or the minimum value larger than the current minimum value.",
"Since that we only increase numbers (multiply them by 2), we cannot decrease the current maximum value, so we must multiply the current minimum number by 2."
] | /**
* @param {number[]} nums
* @return {number}
*/
var minimumDeviation = function(nums) {
}; | You are given an array nums of n positive integers.
You can perform two types of operations on any element of the array any number of times:
If the element is even, divide it by 2.
For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].
If the element is odd, multiply it by 2.
For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4].
The deviation of the array is the maximum difference between any two elements in the array.
Return the minimum deviation the array can have after performing some number of operations.
Example 1:
Input: nums = [1,2,3,4]
Output: 1
Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.
Example 2:
Input: nums = [4,1,5,20,3]
Output: 3
Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.
Example 3:
Input: nums = [2,10,8]
Output: 3
Constraints:
n == nums.length
2 <= n <= 5 * 104
1 <= nums[i] <= 109
| Hard | [
"array",
"greedy",
"heap-priority-queue",
"ordered-set"
] | [
"const minimumDeviation = function (A) {\n const pq = new PriorityQueue()\n let n = A.length,\n mi = Number.MAX_VALUE,\n res = Number.MAX_VALUE\n for (let a of A) {\n if (a % 2 === 1) a *= 2\n pq.push(-a)\n mi = Math.min(mi, a)\n }\n while (true) {\n let a = -pq.pop()\n res = Math.min(res, a - mi)\n if (a % 2 === 1) break\n mi = Math.min(mi, a / 2)\n pq.push(-a / 2)\n }\n return res\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a < b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}"
] |
|
1,678 | goal-parser-interpretation | [
"You need to check at most 2 characters to determine which character comes next."
] | /**
* @param {string} command
* @return {string}
*/
var interpret = function(command) {
}; | You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concatenated in the original order.
Given the string command, return the Goal Parser's interpretation of command.
Example 1:
Input: command = "G()(al)"
Output: "Goal"
Explanation: The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal".
Example 2:
Input: command = "G()()()()(al)"
Output: "Gooooal"
Example 3:
Input: command = "(al)G(al)()()G"
Output: "alGalooG"
Constraints:
1 <= command.length <= 100
command consists of "G", "()", and/or "(al)" in some order.
| Easy | [
"string"
] | [
"const interpret = function(c) {\n const stack = [c[0]]\n const n = c.length\n let i = 1\n while(i < n) {\n if(c[i] === ')') {\n if(stack[stack.length - 1] === '(') {\n stack.pop()\n stack.push('o')\n i++\n } else {\n let res = ''\n while(stack[stack.length - 1] !== '(') {\n const tmp = stack.pop()\n res = tmp + res\n }\n stack.pop()\n stack.push(res)\n i++\n }\n } else {\n stack.push(c[i])\n i++\n }\n }\n return stack.join('')\n};"
] |
|
1,679 | max-number-of-k-sum-pairs | [
"The abstract problem asks to count the number of disjoint pairs with a given sum k.",
"For each possible value x, it can be paired up with k - x.",
"The number of such pairs equals to min(count(x), count(k-x)), unless that x = k / 2, where the number of such pairs will be floor(count(x) / 2)."
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var maxOperations = function(nums, k) {
}; | You are given an integer array nums and an integer k.
In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.
Return the maximum number of operations you can perform on the array.
Example 1:
Input: nums = [1,2,3,4], k = 5
Output: 2
Explanation: Starting with nums = [1,2,3,4]:
- Remove numbers 1 and 4, then nums = [2,3]
- Remove numbers 2 and 3, then nums = []
There are no more pairs that sum up to 5, hence a total of 2 operations.
Example 2:
Input: nums = [3,1,3,4,3], k = 6
Output: 1
Explanation: Starting with nums = [3,1,3,4,3]:
- Remove the first two 3's, then nums = [1,4,3]
There are no more pairs that sum up to 6, hence a total of 1 operation.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= 109
| Medium | [
"array",
"hash-table",
"two-pointers",
"sorting"
] | [
"const maxOperations = function(nums, k) {\n const m = new Map()\n let res = 0\n for(let e of nums) {\n if(!m.has(e)) m.set(e, 0)\n if(m.has(k - e) && m.get(k - e)) {\n res++\n m.set(k - e, m.get(k - e) - 1)\n } else {\n m.set(e, m.get(e) + 1)\n }\n }\n return res;\n};"
] |
|
1,680 | concatenation-of-consecutive-binary-numbers | [
"Express the nth number value in a recursion formula and think about how we can do a fast evaluation."
] | /**
* @param {number} n
* @return {number}
*/
var concatenatedBinary = function(n) {
}; | Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.
Example 1:
Input: n = 1
Output: 1
Explanation: "1" in binary corresponds to the decimal value 1.
Example 2:
Input: n = 3
Output: 27
Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".
After concatenating them, we have "11011", which corresponds to the decimal value 27.
Example 3:
Input: n = 12
Output: 505379714
Explanation: The concatenation results in "1101110010111011110001001101010111100".
The decimal value of that is 118505380540.
After modulo 109 + 7, the result is 505379714.
Constraints:
1 <= n <= 105
| Medium | [
"math",
"bit-manipulation",
"simulation"
] | [
"const concatenatedBinary = function(n) {\n let res = ''\n const mod = 10 ** 9 + 7\n for(let i = 1; i <= n; i++) {\n res += dec2bin(i)\n res = dec2bin(parseInt(res, 2) % mod)\n }\n return parseInt(res, 2) % mod\n};\nfunction dec2bin(dec){\n return (dec >>> 0).toString(2);\n}",
"const concatenatedBinary = function (n) {\n const mod = BigInt(1e9 + 7)\n let res = 0n\n for (let i = 1n, shift = 0n; i <= n; i++) {\n let singleBit = (i & (i - 1n)) == 0\n if (singleBit) shift++\n res <<= shift\n res += i\n res %= mod\n }\n return res\n}"
] |
|
1,681 | minimum-incompatibility | [
"The constraints are small enough for a backtrack solution but not any backtrack solution",
"If we use a naive n^k don't you think it can be optimized"
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var minimumIncompatibility = function(nums, k) {
}; | You are given an integer array nums and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset.
A subset's incompatibility is the difference between the maximum and minimum elements in that array.
Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible.
A subset is a group integers that appear in the array with no particular order.
Example 1:
Input: nums = [1,2,1,4], k = 2
Output: 4
Explanation: The optimal distribution of subsets is [1,2] and [1,4].
The incompatibility is (2-1) + (4-1) = 4.
Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.
Example 2:
Input: nums = [6,3,8,1,3,1,2,2], k = 4
Output: 6
Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].
The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.
Example 3:
Input: nums = [5,3,3,6,3,3], k = 3
Output: -1
Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.
Constraints:
1 <= k <= nums.length <= 16
nums.length is divisible by k
1 <= nums[i] <= nums.length
| Hard | [
"array",
"dynamic-programming",
"bit-manipulation",
"bitmask"
] | [
"const minimumIncompatibility = function(nums, k) {\n const n = nums.length\n const size = n / k\n const mod = 1e9 + 7\n if(size === 1) return 0\n const limit = 1 << n\n const dp = Array.from({ length: limit }, () => Array(16).fill(Infinity))\n for(let i = 0; i < n; i++) dp[1 << i][i] = 0\n \n for(let mask = 0; mask < limit; mask++) {\n for(let i = 0; i < n; i++) {\n if((mask & (1 << i)) === 0) continue\n for(let j = 0; j < n; j++) {\n if((mask & (1 << j))) continue\n const newMask = mask | (1 << j)\n if(bitCnt(mask) % size === 0) {\n dp[newMask][j] = Math.min(dp[newMask][j], dp[mask][i])\n } else if(nums[j] > nums[i]) {\n dp[newMask][j] = Math.min(dp[newMask][j], dp[mask][i] + nums[j] - nums[i])\n }\n }\n }\n }\n\n const candidate = Math.min(...dp.at(-1))\n \n return candidate === Infinity ? -1 : candidate\n \n function bitCnt(num) {\n let res = 0\n while(num) {\n if(num & 1) res++\n num = num >> 1\n }\n \n return res\n }\n};",
"var minimumIncompatibility = function (nums, k) {\n if (k === nums.length) {\n return 0\n }\n const counts = Array(nums.length + 1).fill(0)\n for (let num of nums) {\n counts[num]++\n if (counts[num] > k) {\n return -1\n }\n }\n const size = nums.length / k\n let ans = Number.MAX_VALUE\n const backtracking = (groupIdx, index, sum, lowIndex, curIndex) => {\n if (index === size) {\n sum += curIndex - lowIndex\n if (sum > ans) {\n return\n }\n if (groupIdx === k - 1) {\n ans = sum\n return\n } else {\n groupIdx++\n index = 0\n }\n }\n if (index === 0) {\n for (let i = 0; i < counts.length; i++) {\n if (counts[i]) {\n counts[i]--\n backtracking(groupIdx, index + 1, sum, i, i)\n counts[i]++\n }\n }\n } else {\n for (let i = curIndex + 1; i < counts.length; i++) {\n if (counts[i]) {\n counts[i]--\n backtracking(groupIdx, index + 1, sum, lowIndex, i)\n counts[i]++\n }\n }\n }\n }\n backtracking(0, 0, 0, 0, 0)\n return ans\n}",
"const minimumIncompatibility = function (nums, k) {\n if (nums.length === k) return 0\n const maxInBucket = nums.length / k\n const freqCount = {}\n for (const n of nums) {\n if (freqCount[n]) {\n if (freqCount[n] === k) {\n return -1\n } else {\n freqCount[n]++\n }\n } else {\n freqCount[n] = 1\n }\n }\n const cache = {}\n const allIndiciesUsedMask = 2 ** nums.length - 1\n const dfs = (usedIndicesBitMask) => {\n if (usedIndicesBitMask === allIndiciesUsedMask) {\n return 0\n }\n if (cache[usedIndicesBitMask]) {\n return cache[usedIndicesBitMask]\n }\n const valsToIndices = {}\n for (let i = 0; i < nums.length; i++) {\n const indexMask = 1 << i\n if (usedIndicesBitMask & indexMask) continue\n const value = nums[i]\n if (!valsToIndices.hasOwnProperty(value)) {\n valsToIndices[value] = i\n }\n }\n const indicesAvailable = Object.values(valsToIndices)\n let minIncompatibilityCost = Infinity\n const combinations = createCombinations(indicesAvailable, maxInBucket)\n for (const indices of combinations) {\n let nextMask = usedIndicesBitMask\n let minVal = Infinity\n let maxVal = -Infinity\n for (const index of indices) {\n minVal = Math.min(minVal, nums[index])\n maxVal = Math.max(maxVal, nums[index])\n nextMask = nextMask | (1 << index)\n }\n const incompatibilityCost = maxVal - minVal\n minIncompatibilityCost = Math.min(\n minIncompatibilityCost,\n dfs(nextMask) + incompatibilityCost\n )\n }\n return (cache[usedIndicesBitMask] = minIncompatibilityCost)\n }\n return dfs(0)\n}\n\nfunction createCombinations(indices, len) {\n const combinations = []\n if (indices.length < len) {\n return combinations\n }\n const stack = [[[], 0]]\n while (stack.length > 0) {\n let [combi, i] = stack.pop()\n for (; i < indices.length; i++) {\n const combination = [...combi, indices[i]]\n if (combination.length === len) {\n combinations.push(combination)\n } else {\n stack.push([combination, i + 1])\n }\n }\n }\n return combinations\n}"
] |
|
1,684 | count-the-number-of-consistent-strings | [
"A string is incorrect if it contains a character that is not allowed",
"Constraints are small enough for brute force"
] | /**
* @param {string} allowed
* @param {string[]} words
* @return {number}
*/
var countConsistentStrings = function(allowed, words) {
}; | You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed.
Return the number of consistent strings in the array words.
Example 1:
Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
Output: 2
Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.
Example 2:
Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
Output: 7
Explanation: All strings are consistent.
Example 3:
Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
Output: 4
Explanation: Strings "cc", "acd", "ac", and "d" are consistent.
Constraints:
1 <= words.length <= 104
1 <= allowed.length <= 26
1 <= words[i].length <= 10
The characters in allowed are distinct.
words[i] and allowed contain only lowercase English letters.
| Easy | [
"array",
"hash-table",
"string",
"bit-manipulation"
] | [
"var countConsistentStrings = function(allowed, words) {\n const set = new Set()\n for(let c of allowed) set.add(c)\n let res = 0\n for(let i = 0, len = words.length; i < len; i++) {\n const cur = words[i]\n let b = true\n for(let c of cur) {\n if(!set.has(c)) {\n b = false\n break\n }\n }\n if(b) res++\n }\n \n return res\n};"
] |
|
1,685 | sum-of-absolute-differences-in-a-sorted-array | [
"Absolute difference is the same as max(a, b) - min(a, b). How can you use this fact with the fact that the array is sorted?",
"For nums[i], the answer is (nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i-1]) + (nums[i+1] - nums[i]) + (nums[i+2] - nums[i]) + ... + (nums[n-1] - nums[i]).",
"It can be simplified to (nums[i] * i - (nums[0] + nums[1] + ... + nums[i-1])) + ((nums[i+1] + nums[i+2] + ... + nums[n-1]) - nums[i] * (n-i-1)). One can build prefix and suffix sums to compute this quickly."
] | /**
* @param {number[]} nums
* @return {number[]}
*/
var getSumAbsoluteDifferences = function(nums) {
}; | You are given an integer array nums sorted in non-decreasing order.
Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.
In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed).
Example 1:
Input: nums = [2,3,5]
Output: [4,3,5]
Explanation: Assuming the arrays are 0-indexed, then
result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
Example 2:
Input: nums = [1,4,6,8,10]
Output: [24,15,13,15,21]
Constraints:
2 <= nums.length <= 105
1 <= nums[i] <= nums[i + 1] <= 104
| Medium | [
"array",
"math",
"prefix-sum"
] | [
"const getSumAbsoluteDifferences = function(nums) {\n const res = [], n = nums.length\n let sum = 0\n for(let first = nums[0], i = 1; i < n; i++) {\n sum += nums[i] - first\n }\n res[0] = sum\n for(let i = 1; i < n; i++) {\n res[i] = res[i - 1] - (nums[i] - nums[i - 1]) * (n - i - 1) + (nums[i] - nums[i - 1]) * (i - 1)\n }\n\n return res\n};"
] |
|
1,686 | stone-game-vi | [
"When one takes the stone, they not only get the points, but they take them away from the other player too.",
"Greedily choose the stone with the maximum aliceValues[i] + bobValues[i]."
] | /**
* @param {number[]} aliceValues
* @param {number[]} bobValues
* @return {number}
*/
var stoneGameVI = function(aliceValues, bobValues) {
}; | Alice and Bob take turns playing a game, with Alice starting first.
There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently.
You are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the ith stone.
The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally. Both players know the other's values.
Determine the result of the game, and:
If Alice wins, return 1.
If Bob wins, return -1.
If the game results in a draw, return 0.
Example 1:
Input: aliceValues = [1,3], bobValues = [2,1]
Output: 1
Explanation:
If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.
Bob can only choose stone 0, and will only receive 2 points.
Alice wins.
Example 2:
Input: aliceValues = [1,2], bobValues = [3,1]
Output: 0
Explanation:
If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.
Draw.
Example 3:
Input: aliceValues = [2,4,3], bobValues = [1,6,7]
Output: -1
Explanation:
Regardless of how Alice plays, Bob will be able to have more points than Alice.
For example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.
Bob wins.
Constraints:
n == aliceValues.length == bobValues.length
1 <= n <= 105
1 <= aliceValues[i], bobValues[i] <= 100
| Medium | [
"array",
"math",
"greedy",
"sorting",
"heap-priority-queue",
"game-theory"
] | [
"const stoneGameVI = function (aliceValues, bobValues) {\n let data = []\n const length = aliceValues.length\n for (let i = 0; i < length; i++) {\n data.push([aliceValues[i] + bobValues[i], aliceValues[i], bobValues[i]])\n }\n data.sort((a, b) => a[0] - b[0])\n data = data.reverse()\n\n let aScore = 0\n let bScore = 0\n for (let i = 0; i < length; i++) {\n if (i % 2 == 0) aScore += data[i][1]\n else bScore += data[i][2]\n }\n\n if (aScore > bScore) return 1\n else if (aScore == bScore) return 0\n else return -1\n}"
] |
|
1,687 | delivering-boxes-from-storage-to-ports | [
"Try to think of the most basic dp which is n^2 now optimize it",
"Think of any range query data structure to optimize"
] | /**
* @param {number[][]} boxes
* @param {number} portsCount
* @param {number} maxBoxes
* @param {number} maxWeight
* @return {number}
*/
var boxDelivering = function(boxes, portsCount, maxBoxes, maxWeight) {
}; | You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry.
You are given an array boxes, where boxes[i] = [portsi, weighti], and three integers portsCount, maxBoxes, and maxWeight.
portsi is the port where you need to deliver the ith box and weightsi is the weight of the ith box.
portsCount is the number of ports.
maxBoxes and maxWeight are the respective box and weight limits of the ship.
The boxes need to be delivered in the order they are given. The ship will follow these steps:
The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints.
For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered.
The ship then makes a return trip to storage to take more boxes from the queue.
The ship must end at storage after all the boxes have been delivered.
Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.
Example 1:
Input: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3
Output: 4
Explanation: The optimal strategy is as follows:
- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.
So the total number of trips is 4.
Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).
Example 2:
Input: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6
Output: 6
Explanation: The optimal strategy is as follows:
- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.
- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.
- The ship takes the fifth box, goes to port 2, then returns to storage. 2 trips.
So the total number of trips is 2 + 2 + 2 = 6.
Example 3:
Input: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7
Output: 6
Explanation: The optimal strategy is as follows:
- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.
- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.
- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.
So the total number of trips is 2 + 2 + 2 = 6.
Constraints:
1 <= boxes.length <= 105
1 <= portsCount, maxBoxes, maxWeight <= 105
1 <= portsi <= portsCount
1 <= weightsi <= maxWeight
| Hard | [
"array",
"dynamic-programming",
"segment-tree",
"queue",
"heap-priority-queue",
"prefix-sum",
"monotonic-queue"
] | [
"var boxDelivering = function (boxes, portsCount, maxBoxes, maxWeight) {\n const n = boxes.length\n const diff = Array(n).fill(0)\n for (let i = 0; i < n - 1; i++) {\n if (boxes[i][0] != boxes[i + 1][0]) diff[i] = 1\n }\n const dp = Array(n).fill(0)\n let cur = 0\n let cbox = 0\n let start = 0\n for (let i = 0; i < n; i++) {\n if (i - start == maxBoxes) {\n cur -= boxes[start][1]\n cbox -= diff[start]\n start += 1\n }\n cur += boxes[i][1]\n if (i > 0) cbox += diff[i - 1]\n while (cur > maxWeight) {\n cur -= boxes[start][1]\n cbox -= diff[start]\n start += 1\n }\n while (start < i && dp[start] == dp[start - 1]) {\n cur -= boxes[start][1]\n cbox -= diff[start]\n start += 1\n }\n dp[i] = (start == 0 ? 0 : dp[start - 1]) + cbox + 2\n }\n return dp[n - 1]\n}"
] |
|
1,688 | count-of-matches-in-tournament | [
"Simulate the tournament as given in the statement.",
"Be careful when handling odd integers."
] | /**
* @param {number} n
* @return {number}
*/
var numberOfMatches = function(n) {
}; | You are given an integer n, the number of teams in a tournament that has strange rules:
If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.
If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round.
Return the number of matches played in the tournament until a winner is decided.
Example 1:
Input: n = 7
Output: 6
Explanation: Details of the tournament:
- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.
- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 3 + 2 + 1 = 6.
Example 2:
Input: n = 14
Output: 13
Explanation: Details of the tournament:
- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.
- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.
- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 7 + 3 + 2 + 1 = 13.
Constraints:
1 <= n <= 200
| Easy | [
"math",
"simulation"
] | [
"var numberOfMatches = function(n) {\n const obj = { res: 0 }\n helper(n, obj)\n return obj.res\n};\n\nfunction helper(num, obj) {\n if(num <= 1) return\n const odd = num % 2 === 1\n if(odd) {\n const tmp = Math.floor((num - 1) / 2) \n obj.res += tmp\n helper(tmp + 1, obj)\n } else {\n const tmp = Math.floor(num / 2) \n obj.res += tmp\n helper(tmp, obj)\n }\n}"
] |
|
1,689 | partitioning-into-minimum-number-of-deci-binary-numbers | [
"Think about if the input was only one digit. Then you need to add up as many ones as the value of this digit.",
"If the input has multiple digits, then you can solve for each digit independently, and merge the answers to form numbers that add up to that input.",
"Thus the answer is equal to the max digit."
] | /**
* @param {string} n
* @return {number}
*/
var minPartitions = function(n) {
}; | A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not.
Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n.
Example 1:
Input: n = "32"
Output: 3
Explanation: 10 + 11 + 11 = 32
Example 2:
Input: n = "82734"
Output: 8
Example 3:
Input: n = "27346209830709182346"
Output: 9
Constraints:
1 <= n.length <= 105
n consists of only digits.
n does not contain any leading zeros and represents a positive integer.
| Medium | [
"string",
"greedy"
] | [
"var minPartitions = function(n) {\n let res = 0\n const arr = n.split('').map(e => parseInt(e))\n for(let i = 0, len = arr.length; i < len; i++) {\n res = Math.max(arr[i], res)\n }\n return res\n};"
] |
|
1,690 | stone-game-vii | [
"The constraints are small enough for an N^2 solution.",
"Try using dynamic programming."
] | /**
* @param {number[]} stones
* @return {number}
*/
var stoneGameVII = function(stones) {
}; | Alice and Bob take turns playing a game, with Alice starting first.
There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove.
Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score.
Given an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob's score if they both play optimally.
Example 1:
Input: stones = [5,3,1,4,2]
Output: 6
Explanation:
- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4].
- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4].
- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4].
- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4].
- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = [].
The score difference is 18 - 12 = 6.
Example 2:
Input: stones = [7,90,5,1,100,10,10,2]
Output: 122
Constraints:
n == stones.length
2 <= n <= 1000
1 <= stones[i] <= 1000
| Medium | [
"array",
"math",
"dynamic-programming",
"game-theory"
] | [
"const stoneGameVII = function (stones) {\n let len = stones.length\n const dp = Array.from({ length: len }, () => Array(len).fill(0))\n for (let i = len - 2; i >= 0; i--) {\n let sum = stones[i]\n for (let j = i + 1; j < len; j++) {\n sum += stones[j]\n dp[i][j] = Math.max(\n sum - stones[i] - dp[i + 1][j],\n sum - stones[j] - dp[i][j - 1]\n )\n }\n }\n return dp[0][len - 1]\n}"
] |
|
1,691 | maximum-height-by-stacking-cuboids | [
"Does the dynamic programming sound like the right algorithm after sorting?",
"Let's say box1 can be placed on top of box2. No matter what orientation box2 is in, we can rotate box1 so that it can be placed on top. Why don't we orient everything such that height is the biggest?"
] | /**
* @param {number[][]} cuboids
* @return {number}
*/
var maxHeight = function(cuboids) {
}; | Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (0-indexed). Choose a subset of cuboids and place them on each other.
You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid.
Return the maximum height of the stacked cuboids.
Example 1:
Input: cuboids = [[50,45,20],[95,37,53],[45,23,12]]
Output: 190
Explanation:
Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.
Cuboid 0 is placed next with the 45x20 side facing down with height 50.
Cuboid 2 is placed next with the 23x12 side facing down with height 45.
The total height is 95 + 50 + 45 = 190.
Example 2:
Input: cuboids = [[38,25,45],[76,35,3]]
Output: 76
Explanation:
You can't place any of the cuboids on the other.
We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.
Example 3:
Input: cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]
Output: 102
Explanation:
After rearranging the cuboids, you can see that all cuboids have the same dimension.
You can place the 11x7 side down on all cuboids so their heights are 17.
The maximum height of stacked cuboids is 6 * 17 = 102.
Constraints:
n == cuboids.length
1 <= n <= 100
1 <= widthi, lengthi, heighti <= 100
| Hard | [
"array",
"dynamic-programming",
"sorting"
] | [
"var maxHeight = function (cuboids) {\n let n = cuboids.length\n for (let c of cuboids) {\n c.sort((a, b) => a - b)\n }\n const { max } = Math\n cuboids.sort(compare)\n const f = Array(n)\n let ans = 0\n for (let i = 0; i < n; i++) {\n f[i] = cuboids[i][2]\n for (let j = 0; j < i; j++) {\n if (\n cuboids[i][0] <= cuboids[j][0] &&\n cuboids[i][1] <= cuboids[j][1] &&\n cuboids[i][2] <= cuboids[j][2]\n )\n f[i] = max(f[i], f[j] + cuboids[i][2])\n }\n ans = max(ans, f[i])\n }\n return ans\n function compare(a, b) {\n if (a[0] != b[0]) return b[0] - a[0]\n if (a[1] != b[1]) return b[1] - a[1]\n return b[2] - a[2]\n }\n}",
"var maxHeight = function(cuboids) {\n cuboids.forEach((cuboid) => cuboid.sort((a, b) => a - b));\n cuboids.sort((a, b) => {\n if (a[0] !== b[0]) return b[0] - a[0];\n if (a[1] !== b[1]) return b[1] - a[1];\n return b[2] - a[2];\n });\n const n = cuboids.length;\n const dp = Array(n).fill(0);\n let res = 0;\n for (let j = 0; j < n; ++j) {\n dp[j] = cuboids[j][2];\n for (let i = 0; i < j; ++i) {\n if (cuboids[i][0] >= cuboids[j][0]\n && cuboids[i][1] >= cuboids[j][1]\n && cuboids[i][2] >= cuboids[j][2]\n ) {\n dp[j] = Math.max(dp[j], dp[i] + cuboids[j][2]);\n }\n }\n res = Math.max(res, dp[j]);\n }\n return res;\n};"
] |
|
1,694 | reformat-phone-number | [
"Discard all the spaces and dashes.",
"Use a while loop. While the string still has digits, check its length and see which rule to apply."
] | /**
* @param {string} number
* @return {string}
*/
var reformatNumber = function(number) {
}; | You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'.
You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows:
2 digits: A single block of length 2.
3 digits: A single block of length 3.
4 digits: Two blocks of length 2 each.
The blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2.
Return the phone number after formatting.
Example 1:
Input: number = "1-23-45 6"
Output: "123-456"
Explanation: The digits are "123456".
Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123".
Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456".
Joining the blocks gives "123-456".
Example 2:
Input: number = "123 4-567"
Output: "123-45-67"
Explanation: The digits are "1234567".
Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123".
Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are "45" and "67".
Joining the blocks gives "123-45-67".
Example 3:
Input: number = "123 4-5678"
Output: "123-456-78"
Explanation: The digits are "12345678".
Step 1: The 1st block is "123".
Step 2: The 2nd block is "456".
Step 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is "78".
Joining the blocks gives "123-456-78".
Constraints:
2 <= number.length <= 100
number consists of digits and the characters '-' and ' '.
There are at least two digits in number.
| Easy | [
"string"
] | [
"const reformatNumber = function(number) {\n let str = number.replace(/\\-/g, '')\n str = str.split(' ').join('')\n const n = str.length\n const re = n % 3\n let lo = 0, hi = 0\n let tmp = []\n if(re === 1) {\n hi = n - 5\n tmp.push(str.slice(n - 4, n - 2), str.slice(n - 2))\n } else if(re === 2) {\n hi = n - 3\n tmp.push(str.slice(n - 2))\n } else {\n hi = n - 1\n }\n const res = []\n for(let i = lo; i <= hi; i += 3) {\n res.push(str.slice(i, i + 3))\n }\n \n res.push(...tmp)\n \n return res.join('-')\n};"
] |
|
1,695 | maximum-erasure-value | [
"The main point here is for the subarray to contain unique elements for each index. Only the first subarrays starting from that index have unique elements.",
"This can be solved using the two pointers technique"
] | /**
* @param {number[]} nums
* @return {number}
*/
var maximumUniqueSubarray = function(nums) {
}; | You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.
Return the maximum score you can get by erasing exactly one subarray.
An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r).
Example 1:
Input: nums = [4,2,4,5,6]
Output: 17
Explanation: The optimal subarray here is [2,4,5,6].
Example 2:
Input: nums = [5,2,1,2,5,2,1,2,5]
Output: 8
Explanation: The optimal subarray here is [5,2,1] or [1,2,5].
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 104
| Medium | [
"array",
"hash-table",
"sliding-window"
] | [
"const maximumUniqueSubarray = function(nums) {\n return maxSumSubarray(nums, nums.length)\n};\n\nfunction maxSumSubarray(arr, n) {\n\n let i = 0, j = 1;\n const set = new Set();\n set.add(arr[0]);\n\n let sum = arr[0];\n let maxsum = sum;\n let end = arr[0]\n \n while (i < n - 1 && j < n) {\n const is_in = set.has(arr[j])\n if (!is_in) {\n sum = sum + arr[j];\n maxsum = Math.max(sum, maxsum);\n \n set.add(arr[j++]);\n } else {\n sum -= arr[i];\n set.delete(arr[i++]);\n }\n }\n return maxsum;\n}\n\nfunction end(s) {\n return Array.from(s).pop();\n}"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.