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,433 | check-if-a-string-can-break-another-string | [
"Sort both strings and then check if one of them can break the other."
] | /**
* @param {string} s1
* @param {string} s2
* @return {boolean}
*/
var checkIfCanBreak = function(s1, s2) {
}; | Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa.
A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.
Example 1:
Input: s1 = "abc", s2 = "xya"
Output: true
Explanation: "ayx" is a permutation of s2="xya" which can break to string "abc" which is a permutation of s1="abc".
Example 2:
Input: s1 = "abe", s2 = "acd"
Output: false
Explanation: All permutations for s1="abe" are: "abe", "aeb", "bae", "bea", "eab" and "eba" and all permutation for s2="acd" are: "acd", "adc", "cad", "cda", "dac" and "dca". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.
Example 3:
Input: s1 = "leetcodee", s2 = "interview"
Output: true
Constraints:
s1.length == n
s2.length == n
1 <= n <= 10^5
All strings consist of lowercase English letters.
| Medium | [
"string",
"greedy",
"sorting"
] | null | [] |
1,434 | number-of-ways-to-wear-different-hats-to-each-other | [
"Dynamic programming + bitmask.",
"dp(peopleMask, idHat) number of ways to wear different hats given a bitmask (people visited) and used hats from 1 to idHat-1."
] | /**
* @param {number[][]} hats
* @return {number}
*/
var numberWays = function(hats) {
}; | There are n people and 40 types of hats labeled from 1 to 40.
Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person.
Return the number of ways that the n people wear different hats to each other.
Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: hats = [[3,4],[4,5],[5]]
Output: 1
Explanation: There is only one way to choose hats given the conditions.
First person choose hat 3, Second person choose hat 4 and last one hat 5.
Example 2:
Input: hats = [[3,5,1],[3,5]]
Output: 4
Explanation: There are 4 ways to choose hats:
(3,5), (5,3), (1,3) and (1,5)
Example 3:
Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
Output: 24
Explanation: Each person can choose hats labeled from 1 to 4.
Number of Permutations of (1,2,3,4) = 24.
Constraints:
n == hats.length
1 <= n <= 10
1 <= hats[i].length <= 40
1 <= hats[i][j] <= 40
hats[i] contains a list of unique integers.
| Hard | [
"array",
"dynamic-programming",
"bit-manipulation",
"bitmask"
] | [
"const numberWays = function(hats) {\n const map = new Map()\n const n = hats.length\n for(let i = 0; i < n; i++) {\n for(const h of hats[i]) {\n if(!map.has(h)) map.set(h, [])\n map.get(h).push(i)\n }\n }\n const mod = 1e9 + 7\n const allMask = (1 << n) - 1\n const dp = Array.from({ length: 41 }, () => Array(1024))\n \n return dfs(1, 0)\n \n function dfs(hat, mask) {\n if(mask === allMask) return 1\n if(hat > 40) return 0\n if(dp[hat][mask] != null) return dp[hat][mask]\n \n let res = 0\n \n // not using this `hat`\n res += dfs(hat + 1, mask)\n for(const p of (map.get(hat) || [])) {\n if(((mask >> p) & 1) === 0) {\n res += dfs(hat + 1, mask | (1 << p))\n res = res % mod\n }\n }\n dp[hat][mask] = res\n return res\n }\n \n};",
"const numberWays = function (hats) {\n const pplThatCanWearHats = new Array(40 + 1).fill(null).map(() => [])\n for (let i = 0; i < hats.length; i++) {\n const personMask = 1 << i\n for (let hat of hats[i]) {\n pplThatCanWearHats[hat].push(personMask)\n }\n }\n\n const cache = {}\n const dfs = (hat, pplWithoutHatsMask) => {\n if (!pplWithoutHatsMask) return 1\n if (hat === 41) return 0\n const key = `${hat}-${pplWithoutHatsMask}`\n if (cache.hasOwnProperty(key)) return cache[key]\n const nextHat = hat + 1\n let total = dfs(nextHat, pplWithoutHatsMask)\n for (let personMask of pplThatCanWearHats[hat]) {\n if (!(pplWithoutHatsMask & personMask)) continue\n total += dfs(nextHat, pplWithoutHatsMask ^ personMask)\n }\n return (cache[key] = total % 1000000007)\n }\n return dfs(1, (1 << hats.length) - 1)\n}"
] |
|
1,436 | destination-city | [
"Start in any city and use the path to move to the next city.",
"Eventually, you will reach a city with no path outgoing, this is the destination city."
] | /**
* @param {string[][]} paths
* @return {string}
*/
var destCity = function(paths) {
}; | You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.
It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.
Example 1:
Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
Output: "Sao Paulo"
Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo".
Example 2:
Input: paths = [["B","C"],["D","B"],["C","A"]]
Output: "A"
Explanation: All possible trips are:
"D" -> "B" -> "C" -> "A".
"B" -> "C" -> "A".
"C" -> "A".
"A".
Clearly the destination city is "A".
Example 3:
Input: paths = [["A","Z"]]
Output: "Z"
Constraints:
1 <= paths.length <= 100
paths[i].length == 2
1 <= cityAi.length, cityBi.length <= 10
cityAi != cityBi
All strings consist of lowercase and uppercase English letters and the space character.
| Easy | [
"hash-table",
"string"
] | [
"const destCity = function(paths) {\n const hash = {}\n for(let [s, e] of paths) {\n if(hash[e] == null) hash[e] = true\n hash[s] = false\n if(hash[s] === true) hash[s] = false\n }\n \n for(let k in hash) {\n if(hash[k]) return k\n }\n};",
"const destCity = function(paths) {\n const set = new Set()\n for(let [s, e] of paths) set.add(e)\n for(let [s, e] of paths) set.delete(s)\n \n return set[Symbol.iterator]().next().value\n};"
] |
|
1,437 | check-if-all-1s-are-at-least-length-k-places-away | [
"Each time you find a number 1, check whether or not it is K or more places away from the next one. If it's not, return false."
] | /**
* @param {number[]} nums
* @param {number} k
* @return {boolean}
*/
var kLengthApart = function(nums, k) {
}; | Given an binary array nums and an integer k, return true if all 1's are at least k places away from each other, otherwise return false.
Example 1:
Input: nums = [1,0,0,0,1,0,0,1], k = 2
Output: true
Explanation: Each of the 1s are at least 2 places away from each other.
Example 2:
Input: nums = [1,0,0,1,0,1], k = 2
Output: false
Explanation: The second 1 and third 1 are only one apart from each other.
Constraints:
1 <= nums.length <= 105
0 <= k <= nums.length
nums[i] is 0 or 1
| Easy | [
"array"
] | null | [] |
1,438 | longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit | [
"Use a sliding window approach keeping the maximum and minimum value using a data structure like a multiset from STL in C++.",
"More specifically, use the two pointer technique, moving the right pointer as far as possible to the right until the subarray is not valid (maxValue - minValue > limit), then moving the left pointer until the subarray is valid again (maxValue - minValue <= limit). Keep repeating this process."
] | /**
* @param {number[]} nums
* @param {number} limit
* @return {number}
*/
var longestSubarray = function(nums, limit) {
}; | Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.
Example 1:
Input: nums = [8,2,4,7], limit = 4
Output: 2
Explanation: All subarrays are:
[8] with maximum absolute diff |8-8| = 0 <= 4.
[8,2] with maximum absolute diff |8-2| = 6 > 4.
[8,2,4] with maximum absolute diff |8-2| = 6 > 4.
[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.
[2] with maximum absolute diff |2-2| = 0 <= 4.
[2,4] with maximum absolute diff |2-4| = 2 <= 4.
[2,4,7] with maximum absolute diff |2-7| = 5 > 4.
[4] with maximum absolute diff |4-4| = 0 <= 4.
[4,7] with maximum absolute diff |4-7| = 3 <= 4.
[7] with maximum absolute diff |7-7| = 0 <= 4.
Therefore, the size of the longest subarray is 2.
Example 2:
Input: nums = [10,1,2,4,7,2], limit = 5
Output: 4
Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.
Example 3:
Input: nums = [4,2,2,2,4,4,2,2], limit = 0
Output: 3
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
0 <= limit <= 109
| Medium | [
"array",
"queue",
"sliding-window",
"heap-priority-queue",
"ordered-set",
"monotonic-queue"
] | [
"const longestSubarray = function(nums, limit) {\n let maxd = [], mind = [];\n let i = 0, j;\n for (j = 0; j < nums.length; ++j) {\n // non-increase\n while (maxd.length && nums[j] > maxd[maxd.length - 1]) maxd.pop();\n // non-decrease\n while (mind.length && nums[j] < mind[mind.length - 1]) mind.pop();\n\n maxd.push(nums[j]);\n mind.push(nums[j]);\n\n if (maxd[0] - mind[0] > limit) {\n if (maxd[0] == nums[i]) maxd.shift();\n if (mind[0] == nums[i]) mind.shift();\n ++i;\n }\n }\n return j - i; \n};",
"const longestSubarray = function (nums, limit) {\n const maxDq = new Deque(), minDq = new Deque(), n = nums.length\n let l = 0, r = 0\n let res = 0\n for(r = 0; r < n; r++) {\n const cur = nums[r]\n while(!maxDq.isEmpty() && maxDq.last() < cur) {\n maxDq.pop()\n }\n maxDq.enqueue(cur)\n while(!minDq.isEmpty() && minDq.last() > cur) {\n minDq.pop()\n }\n minDq.enqueue(cur)\n\n while(maxDq.first() - minDq.first() > limit) {\n if(nums[l] === maxDq.first()) maxDq.dequeue()\n if(nums[l] === minDq.first()) minDq.dequeue()\n l++\n }\n res = Math.max(res, r - l + 1)\n }\n return res\n}\n\nclass Deque {\n constructor() {\n this.head = new Node()\n this.tail = this.head\n }\n\n isEmpty() {\n return this.head.next === null\n }\n\n first() {\n return this.head.next.value\n }\n\n last() {\n return this.tail.value\n }\n\n dequeue() {\n this.head = this.head.next\n this.head.prev = null\n }\n\n enqueue(value) {\n this.tail.next = new Node(value)\n this.tail.next.prev = this.tail\n this.tail = this.tail.next\n }\n\n pop() {\n this.tail = this.tail.prev\n this.tail.next = null\n }\n}\n\nclass Node {\n constructor(value) {\n this.value = value\n this.next = null\n this.prev = null\n }\n}"
] |
|
1,439 | find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows | [
"Save all visited sums and corresponding indexes in a priority queue. Then, once you pop the smallest sum so far, you can quickly identify the next m candidates for smallest sum by incrementing each row index by 1."
] | /**
* @param {number[][]} mat
* @param {number} k
* @return {number}
*/
var kthSmallest = function(mat, k) {
}; | You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k.
You are allowed to choose exactly one element from each row to form an array.
Return the kth smallest array sum among all possible arrays.
Example 1:
Input: mat = [[1,3,11],[2,4,6]], k = 5
Output: 7
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.
Example 2:
Input: mat = [[1,3,11],[2,4,6]], k = 9
Output: 17
Example 3:
Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
Output: 9
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.
Constraints:
m == mat.length
n == mat.length[i]
1 <= m, n <= 40
1 <= mat[i][j] <= 5000
1 <= k <= min(200, nm)
mat[i] is a non-decreasing array.
| Hard | [
"array",
"binary-search",
"heap-priority-queue",
"matrix"
] | [
"const kthSmallest = function(mat, k) {\n let lo = 0;\n let hi = 0;\n for(let r of mat) {\n lo += r[0];\n hi += r[r.length-1];\n }\n\n const check = (row, sum, limit) => {\n if (sum > limit) return 0;\n if (row === mat.length) return 1;\n let totalcnt = 0;\n for(let v of mat[row]) {\n const cnt = check(row + 1, v + sum, limit);\n totalcnt += cnt;\n if (cnt === 0 || totalcnt > k) break; \n }\n return totalcnt;\n };\n\n while(lo <= hi) {\n const m = (lo + (hi - lo) / 2) >> 0;\n const cnt = check(0, 0, m);\n if (cnt < k) {\n lo = m + 1;\n } else {\n hi = m - 1;\n }\n }\n\n return lo;\n};"
] |
|
1,441 | build-an-array-with-stack-operations | [
"Use “Push” for numbers to be kept in target array and [“Push”, “Pop”] for numbers to be discarded."
] | /**
* @param {number[]} target
* @param {number} n
* @return {string[]}
*/
var buildArray = function(target, n) {
}; | You are given an integer array target and an integer n.
You have an empty stack with the two following operations:
"Push": pushes an integer to the top of the stack.
"Pop": removes the integer on the top of the stack.
You also have a stream of the integers in the range [1, n].
Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to target. You should follow the following rules:
If the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack.
If the stack is not empty, pop the integer at the top of the stack.
If, at any moment, the elements in the stack (from the bottom to the top) are equal to target, do not read new integers from the stream and do not do more operations on the stack.
Return the stack operations needed to build target following the mentioned rules. If there are multiple valid answers, return any of them.
Example 1:
Input: target = [1,3], n = 3
Output: ["Push","Push","Pop","Push"]
Explanation: Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = [1].
Read 2 from the stream and push it to the stack. s = [1,2].
Pop the integer on the top of the stack. s = [1].
Read 3 from the stream and push it to the stack. s = [1,3].
Example 2:
Input: target = [1,2,3], n = 3
Output: ["Push","Push","Push"]
Explanation: Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = [1].
Read 2 from the stream and push it to the stack. s = [1,2].
Read 3 from the stream and push it to the stack. s = [1,2,3].
Example 3:
Input: target = [1,2], n = 4
Output: ["Push","Push"]
Explanation: Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = [1].
Read 2 from the stream and push it to the stack. s = [1,2].
Since the stack (from the bottom to the top) is equal to target, we stop the stack operations.
The answers that read integer 3 from the stream are not accepted.
Constraints:
1 <= target.length <= 100
1 <= n <= 100
1 <= target[i] <= n
target is strictly increasing.
| Medium | [
"array",
"stack",
"simulation"
] | [
" const buildArray = function(target, n) {\n const res = []\n let ti = 0, ni = 1, num = 0\n while(num !== target.length && ni <= n) {\n if(ni !== target[ti]) {\n res.push('Push', 'Pop')\n ni++\n }else {\n res.push('Push')\n ni++\n num++\n ti++\n }\n }\n\n return res\n};"
] |
|
1,442 | count-triplets-that-can-form-two-arrays-of-equal-xor | [
"We are searching for sub-array of length ≥ 2 and we need to split it to 2 non-empty arrays so that the xor of the first array is equal to the xor of the second array. This is equivalent to searching for sub-array with xor = 0.",
"Keep the prefix xor of arr in another array, check the xor of all sub-arrays in O(n^2), if the xor of sub-array of length x is 0 add x-1 to the answer."
] | /**
* @param {number[]} arr
* @return {number}
*/
var countTriplets = function(arr) {
}; | Given an array of integers arr.
We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).
Let's define a and b as follows:
a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
Note that ^ denotes the bitwise-xor operation.
Return the number of triplets (i, j and k) Where a == b.
Example 1:
Input: arr = [2,3,1,6,7]
Output: 4
Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)
Example 2:
Input: arr = [1,1,1,1,1]
Output: 10
Constraints:
1 <= arr.length <= 300
1 <= arr[i] <= 108
| Medium | [
"array",
"hash-table",
"math",
"bit-manipulation",
"prefix-sum"
] | [
"const countTriplets = function(arr) {\n let res = 0\n const n = arr.length\n for(let i = 0; i < n; i++) {\n let xor = arr[i]\n for(let j = i + 1; j < n; j++) {\n xor ^= arr[j]\n if(xor === 0) res += j - i\n }\n }\n \n return res\n};",
"const countTriplets = function(arr) {\n arr.unshift(0)\n const n = arr.length\n let res = 0\n for(let i = 1; i < n; i++) {\n arr[i] ^= arr[i - 1]\n }\n const count = {}, total = {}\n for(let i = 0; i < n; i++) {\n if(count[arr[i]] == null) count[arr[i]] = 0\n if(total[arr[i]] == null) total[arr[i]] = 0\n res += count[arr[i]]++ * (i - 1) - total[arr[i]]\n total[arr[i]] += i\n }\n return res\n};"
] |
|
1,443 | minimum-time-to-collect-all-apples-in-a-tree | [
"Note that if a node u contains an apple then all edges in the path from the root to the node u have to be used forward and backward (2 times).",
"Therefore use a depth-first search (DFS) to check if an edge will be used or not."
] | /**
* @param {number} n
* @param {number[][]} edges
* @param {boolean[]} hasApple
* @return {number}
*/
var minTime = function(n, edges, hasApple) {
}; | Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.
The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.
Example 1:
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]
Output: 8
Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.
Example 2:
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]
Output: 6
Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.
Example 3:
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]
Output: 0
Constraints:
1 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai < bi <= n - 1
hasApple.length == n
| Medium | [
"hash-table",
"tree",
"depth-first-search",
"breadth-first-search"
] | null | [] |
1,444 | number-of-ways-of-cutting-a-pizza | [
"Note that after each cut the remaining piece of pizza always has the lower right coordinate at (rows-1,cols-1).",
"Use dynamic programming approach with states (row1, col1, c) which computes the number of ways of cutting the pizza using \"c\" cuts where the current piece of pizza has upper left coordinate at (row1,col1) and lower right coordinate at (rows-1,cols-1).",
"For the transitions try all vertical and horizontal cuts such that the piece of pizza you have to give a person must contain at least one apple. The base case is when c=k-1.",
"Additionally use a 2D dynamic programming to respond in O(1) if a piece of pizza contains at least one apple."
] | /**
* @param {string[]} pizza
* @param {number} k
* @return {number}
*/
var ways = function(pizza, k) {
}; | Given a rectangular pizza represented as a rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts.
For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.
Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.
Example 1:
Input: pizza = ["A..","AAA","..."], k = 3
Output: 3
Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.
Example 2:
Input: pizza = ["A..","AA.","..."], k = 3
Output: 1
Example 3:
Input: pizza = ["A..","A..","..."], k = 1
Output: 1
Constraints:
1 <= rows, cols <= 50
rows == pizza.length
cols == pizza[i].length
1 <= k <= 10
pizza consists of characters 'A' and '.' only.
| Hard | [
"array",
"dynamic-programming",
"memoization",
"matrix"
] | [
"const ways = function (pizza, K) {\n const MOD = 1e9 + 7\n const M = pizza.length\n const N = pizza[0].length\n const count = Array(M + 1)\n .fill(0)\n .map(() => Array(N + 1).fill(0))\n for (let i = M - 1; i >= 0; i--) {\n let rowCount = 0\n for (let j = N - 1; j >= 0; j--) {\n rowCount += pizza[i][j] === 'A' ? 1 : 0\n count[i][j] = count[i + 1][j] + rowCount\n }\n }\n const dp = Array(M)\n .fill(0)\n .map(() =>\n Array(N)\n .fill(0)\n .map(() => Array(K + 1).fill(0))\n )\n for (let i = M - 1; i >= 0; i--) {\n for (let j = N - 1; j >= 0; j--) {\n dp[i][j][1] = 1\n for (let k = 2; k <= K; k++) {\n for (let t = i + 1; t < M; t++) {\n if (count[i][j] === count[t][j]) continue\n if (count[t][j] === 0) break\n dp[i][j][k] = (dp[i][j][k] + dp[t][j][k - 1]) % MOD\n }\n for (let t = j + 1; t < N; t++) {\n if (count[i][j] === count[i][t]) continue\n if (count[i][t] === 0) break\n dp[i][j][k] = (dp[i][j][k] + dp[i][t][k - 1]) % MOD\n }\n }\n }\n }\n return dp[0][0][K]\n}"
] |
|
1,446 | consecutive-characters | [
"Keep an array power where power[i] is the maximum power of the i-th character.",
"The answer is max(power[i])."
] | /**
* @param {string} s
* @return {number}
*/
var maxPower = function(s) {
}; | The power of the string is the maximum length of a non-empty substring that contains only one unique character.
Given a string s, return the power of s.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Example 2:
Input: s = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
Constraints:
1 <= s.length <= 500
s consists of only lowercase English letters.
| Easy | [
"string"
] | [
"const maxPower = function(s) {\n let res = 1, cnt = 1\n for(let i = 1; i < s.length; i++) {\n if(s[i] === s[i - 1]) {\n if(++cnt > res) res = cnt\n } else {\n cnt = 1\n }\n }\n return res\n};",
"const maxPower = function(s) {\n let prev = '', prevIdx = -1, res = -Infinity\n for(let i = 0; i < s.length; i++) {\n const cur = s[i]\n if(cur !== prev) {\n res = Math.max(res, i - prevIdx)\n prev = cur\n prevIdx = i\n } else {\n if(i === s.length - 1) res = Math.max(res, i - prevIdx + 1)\n }\n }\n return res\n};"
] |
|
1,447 | simplified-fractions | [
"A fraction is fully simplified if there is no integer that divides cleanly into the numerator and denominator.",
"In other words the greatest common divisor of the numerator and the denominator of a simplified fraction is 1."
] | /**
* @param {number} n
* @return {string[]}
*/
var simplifiedFractions = function(n) {
}; | Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order.
Example 1:
Input: n = 2
Output: ["1/2"]
Explanation: "1/2" is the only unique fraction with a denominator less-than-or-equal-to 2.
Example 2:
Input: n = 3
Output: ["1/2","1/3","2/3"]
Example 3:
Input: n = 4
Output: ["1/2","1/3","1/4","2/3","3/4"]
Explanation: "2/4" is not a simplified fraction because it can be simplified to "1/2".
Constraints:
1 <= n <= 100
| Medium | [
"math",
"string",
"number-theory"
] | null | [] |
1,448 | count-good-nodes-in-binary-tree | [
"Use DFS (Depth First Search) to traverse the tree, and constantly keep track of the current path maximum."
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var goodNodes = function(root) {
}; | Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:
Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
Example 3:
Input: root = [1]
Output: 1
Explanation: Root is considered as good.
Constraints:
The number of nodes in the binary tree is in the range [1, 10^5].
Each node's value is between [-10^4, 10^4].
| Medium | [
"tree",
"depth-first-search",
"breadth-first-search",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const goodNodes = function(root) {\n if(root == null) return 0\n let res = 0\n\n helper(root, root.val)\n\n return res\n \n function helper(node, max) {\n if(node == null) return\n if(node.val >= max) {\n res++\n max = node.val\n }\n helper(node.left, max)\n helper(node.right, max)\n }\n};"
] |
1,449 | form-largest-integer-with-digits-that-add-up-to-target | [
"Use dynamic programming to find the maximum digits to paint given a total cost.",
"Build the largest number possible using this DP table."
] | /**
* @param {number[]} cost
* @param {number} target
* @return {string}
*/
var largestNumber = function(cost, target) {
}; | Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:
The cost of painting a digit (i + 1) is given by cost[i] (0-indexed).
The total cost used must be equal to target.
The integer does not have 0 digits.
Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return "0".
Example 1:
Input: cost = [4,3,2,5,6,7,2,5,5], target = 9
Output: "7772"
Explanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost("7772") = 2*3+ 3*1 = 9. You could also paint "977", but "7772" is the largest number.
Digit cost
1 -> 4
2 -> 3
3 -> 2
4 -> 5
5 -> 6
6 -> 7
7 -> 2
8 -> 5
9 -> 5
Example 2:
Input: cost = [7,6,5,5,5,6,8,7,8], target = 12
Output: "85"
Explanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost("85") = 7 + 5 = 12.
Example 3:
Input: cost = [2,4,6,2,4,6,4,4,4], target = 5
Output: "0"
Explanation: It is impossible to paint any integer with total cost equal to target.
Constraints:
cost.length == 9
1 <= cost[i], target <= 5000
| Hard | [
"array",
"dynamic-programming"
] | [
"const largestNumber = function (cost, target) {\n const dp = new Array(target + 1).fill(-Infinity)\n dp[0] = 0\n for (let i = 1; i <= target; i++) {\n for (let c of cost) {\n if (i - c >= 0 && dp[i - c] >= 0) {\n dp[i] = Math.max(dp[i - c] + 1, dp[i])\n }\n }\n }\n let left = target\n let paint = ''\n if (dp[target] < 1) return '0'\n for (let i = cost.length - 1; i >= 0; i--) {\n while (left > 0 && dp[left - cost[i]] === dp[left] - 1) {\n paint += (i + 1).toString()\n left -= cost[i]\n }\n }\n return paint\n}",
"const largestNumber = function(cost, target) {\n const m = new Map()\n const res = dfs(cost, 1, target, m)\n return res.indexOf('0') !== -1 ? '0' : res\n};\nfunction dfs(cost, index, remain, m) {\n if(remain === 0) return ''\n if(remain < 0 || index === cost.length + 1) return '0'\n if(m.has(remain)) return m.get(remain)\n const take = '' + index + dfs(cost, 1, remain - cost[index - 1], m)\n const skip = dfs(cost, index + 1, remain, m)\n const res = getBigger(take, skip)\n m.set(remain, res)\n return res\n}\nfunction getBigger(num1, num2) {\n if(num1.indexOf('0') !== -1) return num2\n if(num2.indexOf('0') !== -1) return num1\n if(num1.length > num2.length) return num1\n else if(num1.length < num2.length) return num2\n else return num1 > num2 ? num1 : num2\n}"
] |
|
1,450 | number-of-students-doing-homework-at-a-given-time | [
"Imagine that startTime[i] and endTime[i] form an interval (i.e. [startTime[i], endTime[i]]).",
"The answer is how many times the queryTime laid in those mentioned intervals."
] | /**
* @param {number[]} startTime
* @param {number[]} endTime
* @param {number} queryTime
* @return {number}
*/
var busyStudent = function(startTime, endTime, queryTime) {
}; | Given two integer arrays startTime and endTime and given an integer queryTime.
The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].
Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.
Example 1:
Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4
Output: 1
Explanation: We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.
Example 2:
Input: startTime = [4], endTime = [4], queryTime = 4
Output: 1
Explanation: The only student was doing their homework at the queryTime.
Constraints:
startTime.length == endTime.length
1 <= startTime.length <= 100
1 <= startTime[i] <= endTime[i] <= 1000
1 <= queryTime <= 1000
| Easy | [
"array"
] | null | [] |
1,451 | rearrange-words-in-a-sentence | [
"Store each word and their relative position. Then, sort them by length of words in case of tie by their original order."
] | /**
* @param {string} text
* @return {string}
*/
var arrangeWords = function(text) {
}; | Given a sentence text (A sentence is a string of space-separated words) in the following format:
First letter is in upper case.
Each word in text are separated by a single space.
Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.
Return the new text following the format shown above.
Example 1:
Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.
Example 2:
Input: text = "Keep calm and code on"
Output: "On and keep calm code"
Explanation: Output is ordered as follows:
"On" 2 letters.
"and" 3 letters.
"keep" 4 letters in case of tie order by position in original text.
"calm" 4 letters.
"code" 4 letters.
Example 3:
Input: text = "To be or not to be"
Output: "To be or to be not"
Constraints:
text begins with a capital letter and then contains lowercase letters and single space between words.
1 <= text.length <= 10^5
| Medium | [
"string",
"sorting"
] | null | [] |
1,452 | people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list | [
"Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list.",
"In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is the maximum number of elements in a list."
] | /**
* @param {string[][]} favoriteCompanies
* @return {number[]}
*/
var peopleIndexes = function(favoriteCompanies) {
}; | Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).
Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.
Example 1:
Input: favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]
Output: [0,1,4]
Explanation:
Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0.
Person with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"].
Other lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].
Example 2:
Input: favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]]
Output: [0,1]
Explanation: In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1].
Example 3:
Input: favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]]
Output: [0,1,2,3]
Constraints:
1 <= favoriteCompanies.length <= 100
1 <= favoriteCompanies[i].length <= 500
1 <= favoriteCompanies[i][j].length <= 20
All strings in favoriteCompanies[i] are distinct.
All lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].
All strings consist of lowercase English letters only.
| Medium | [
"array",
"hash-table",
"string"
] | [
"const peopleIndexes = function(favoriteCompanies) {\n const fcs = []\n for(const fc of favoriteCompanies) fcs.push(new Set(fc))\n const n = fcs.length, uf = new Array(n).fill(0)\n for(let i = 0; i < n; i++) uf[i] = i\n for(let i = 0; i < n; i++) {\n for(let j = i + 1; j < n; j++) {\n const a = find(uf, i), b = find(uf, j)\n if(a === b) continue\n else if(contains(fcs[a], fcs[b])) uf[b] = a\n else if(contains(fcs[b], fcs[a])) uf[a] = b\n }\n }\n const set = new Set()\n for(const i of uf) set.add(find(uf, i))\n return Array.from(set).sort((a, b) => a - b)\n\n function contains(a, b) {\n if(a.size < b.size) return false\n for(let e of b) {\n if(!a.has(e)) return false\n } \n return true\n }\n\n function find(uf, e) {\n while(uf[e] !== e) {\n uf[e] = uf[uf[e]]\n e = uf[e]\n }\n return e\n }\n};"
] |
|
1,453 | maximum-number-of-darts-inside-of-a-circular-dartboard | [
"If there is an optimal solution, you can always move the circle so that two points lie on the boundary of the circle.",
"When the radius is fixed, you can find either 0 or 1 or 2 circles that pass two given points at the same time.",
"Loop for each pair of points and find the center of the circle, after that count the number of points inside the circle."
] | /**
* @param {number[][]} darts
* @param {number} r
* @return {number}
*/
var numPoints = function(darts, r) {
}; | Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall.
Bob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice throws lie on the dartboard.
Given the integer r, return the maximum number of darts that can lie on the dartboard.
Example 1:
Input: darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2
Output: 4
Explanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.
Example 2:
Input: darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5
Output: 5
Explanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).
Constraints:
1 <= darts.length <= 100
darts[i].length == 2
-104 <= xi, yi <= 104
All the darts are unique
1 <= r <= 5000
| Hard | [
"array",
"math",
"geometry"
] | null | [] |
1,455 | check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence | [
"First extract the words of the sentence.",
"Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed)",
"If searchWord doesn't exist as a prefix of any word return the default value (-1)."
] | /**
* @param {string} sentence
* @param {string} searchWord
* @return {number}
*/
var isPrefixOfWord = function(sentence, searchWord) {
}; | Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence.
Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.
A prefix of a string s is any leading contiguous substring of s.
Example 1:
Input: sentence = "i love eating burger", searchWord = "burg"
Output: 4
Explanation: "burg" is prefix of "burger" which is the 4th word in the sentence.
Example 2:
Input: sentence = "this problem is an easy problem", searchWord = "pro"
Output: 2
Explanation: "pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.
Example 3:
Input: sentence = "i am tired", searchWord = "you"
Output: -1
Explanation: "you" is not a prefix of any word in the sentence.
Constraints:
1 <= sentence.length <= 100
1 <= searchWord.length <= 10
sentence consists of lowercase English letters and spaces.
searchWord consists of lowercase English letters.
| Easy | [
"string",
"string-matching"
] | null | [] |
1,456 | maximum-number-of-vowels-in-a-substring-of-given-length | [
"Keep a window of size k and maintain the number of vowels in it.",
"Keep moving the window and update the number of vowels while moving. Answer is max number of vowels of any window."
] | /**
* @param {string} s
* @param {number} k
* @return {number}
*/
var maxVowels = function(s, k) {
}; | Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.
Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.
Example 1:
Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.
Example 2:
Input: s = "aeiou", k = 2
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.
Example 3:
Input: s = "leetcode", k = 3
Output: 2
Explanation: "lee", "eet" and "ode" contain 2 vowels.
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
1 <= k <= s.length
| Medium | [
"string",
"sliding-window"
] | null | [] |
1,457 | pseudo-palindromic-paths-in-a-binary-tree | [
"Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity).",
"Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity)."
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var pseudoPalindromicPaths = function(root) {
}; | Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
Return the number of pseudo-palindromic paths going from the root node to leaf nodes.
Example 1:
Input: root = [2,3,1,3,1,null,1]
Output: 2
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).
Example 2:
Input: root = [2,1,1,1,3,null,null,null,null,null,1]
Output: 1
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).
Example 3:
Input: root = [9]
Output: 1
Constraints:
The number of nodes in the tree is in the range [1, 105].
1 <= Node.val <= 9
| Medium | [
"bit-manipulation",
"tree",
"depth-first-search",
"breadth-first-search",
"binary-tree"
] | null | [] |
1,458 | max-dot-product-of-two-subsequences | [
"Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2."
] | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var maxDotProduct = function(nums1, nums2) {
}; | Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
| Hard | [
"array",
"dynamic-programming"
] | [
"const maxDotProduct = function (nums1, nums2) {\n const n = nums1.length\n const m = nums2.length\n const dp = Array.from({ length: n + 1 }, () => Array(m + 1).fill(-Infinity))\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= m; j++) {\n dp[i][j] = Math.max(\n nums1[i - 1] * nums2[j - 1],\n dp[i - 1][j - 1] + nums1[i - 1] * nums2[j - 1],\n dp[i - 1][j],\n dp[i][j - 1]\n )\n }\n }\n return dp[n][m]\n}"
] |
|
1,460 | make-two-arrays-equal-by-reversing-subarrays | [
"Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false.",
"To solve it easiely you can sort the two arrays and check if they are equal."
] | /**
* @param {number[]} target
* @param {number[]} arr
* @return {boolean}
*/
var canBeEqual = function(target, arr) {
}; | You are given two integer arrays of equal length target and arr. In one step, you can select any non-empty subarray of arr and reverse it. You are allowed to make any number of steps.
Return true if you can make arr equal to target or false otherwise.
Example 1:
Input: target = [1,2,3,4], arr = [2,4,1,3]
Output: true
Explanation: You can follow the next steps to convert arr to target:
1- Reverse subarray [2,4,1], arr becomes [1,4,2,3]
2- Reverse subarray [4,2], arr becomes [1,2,4,3]
3- Reverse subarray [4,3], arr becomes [1,2,3,4]
There are multiple ways to convert arr to target, this is not the only way to do so.
Example 2:
Input: target = [7], arr = [7]
Output: true
Explanation: arr is equal to target without any reverses.
Example 3:
Input: target = [3,7,9], arr = [3,7,11]
Output: false
Explanation: arr does not have value 9 and it can never be converted to target.
Constraints:
target.length == arr.length
1 <= target.length <= 1000
1 <= target[i] <= 1000
1 <= arr[i] <= 1000
| Easy | [
"array",
"hash-table",
"sorting"
] | [
"const canBeEqual = function(target, arr) {\n if(target.length !== arr.length) return false\n const tHash = {}, aHash = {}\n for(let i = 0, len = arr.length; i < len;i++) {\n const t = target[i], a = arr[i]\n if(tHash[t] == null) tHash[t] = 0\n if(aHash[a] == null) aHash[a] = 0\n tHash[t]++\n aHash[a]++\n }\n \n const keys = Object.keys(tHash)\n for(let k of keys) {\n if(tHash[k] !== aHash[k]) return false \n }\n \n return true\n};"
] |
|
1,461 | check-if-a-string-contains-all-binary-codes-of-size-k | [
"We need only to check all sub-strings of length k.",
"The number of distinct sub-strings should be exactly 2^k."
] | /**
* @param {string} s
* @param {number} k
* @return {boolean}
*/
var hasAllCodes = function(s, k) {
}; | Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.
Example 1:
Input: s = "00110110", k = 2
Output: true
Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.
Example 2:
Input: s = "0110", k = 1
Output: true
Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring.
Example 3:
Input: s = "0110", k = 2
Output: false
Explanation: The binary code "00" is of length 2 and does not exist in the array.
Constraints:
1 <= s.length <= 5 * 105
s[i] is either '0' or '1'.
1 <= k <= 20
| Medium | [
"hash-table",
"string",
"bit-manipulation",
"rolling-hash",
"hash-function"
] | [
"const hasAllCodes = function (s, k) {\n if (s.length < k) return false\n const set = new Set()\n for (let i = 0; i <= s.length - k; i++) {\n set.add(s.slice(i, i + k))\n }\n\n return set.size == Math.pow(2, k)\n}"
] |
|
1,462 | course-schedule-iv | [
"Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j].",
"Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True.",
"Answer the queries from the isReachable array."
] | /**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @param {number[][]} queries
* @return {boolean[]}
*/
var checkIfPrerequisite = function(numCourses, prerequisites, queries) {
}; | There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.
For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1.
Prerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c.
You are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not.
Return a boolean array answer, where answer[j] is the answer to the jth query.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]
Output: [false,true]
Explanation: The pair [1, 0] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
Example 2:
Input: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]
Output: [false,false]
Explanation: There are no prerequisites, and each course is independent.
Example 3:
Input: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]
Output: [true,true]
Constraints:
2 <= numCourses <= 100
0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)
prerequisites[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
All the pairs [ai, bi] are unique.
The prerequisites graph has no cycles.
1 <= queries.length <= 104
0 <= ui, vi <= n - 1
ui != vi
| Medium | [
"depth-first-search",
"breadth-first-search",
"graph",
"topological-sort"
] | [
"const checkIfPrerequisite = function (numCourses, prerequisites, queries) {\n const n = numCourses, m = prerequisites.length\n const graph = {}, inDegree = Array(n).fill(0)\n \n for(const [s, e] of prerequisites) {\n if(graph[s] == null) graph[s] = []\n inDegree[e]++\n graph[s].push(e)\n }\n \n let q = []\n \n for(let i = 0; i < n; i++) {\n if(inDegree[i] === 0) q.push(i)\n }\n \n const hash = {}\n\n while(q.length) {\n const size = q.length\n const nxt = []\n for(let i = 0; i < size; i++) {\n const cur = q[i]\n for(const e of (graph[cur] || [])) {\n inDegree[e]--\n if(hash[e] == null) hash[e] = new Set()\n hash[e].add(cur)\n for(const dep of (hash[cur] || [])) {\n hash[e].add(dep)\n }\n \n if(inDegree[e] === 0) {\n nxt.push(e)\n }\n }\n }\n \n q = nxt\n }\n \n const res = []\n for(const [p, e] of queries) {\n if(hash[e] && hash[e].has(p)) res.push(true)\n else res.push(false)\n }\n \n return res\n}",
"const checkIfPrerequisite = function(numCourses, prerequisites, queries) {\n // https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm\n const n = numCourses\n const connected = Array.from({ length: n }, () => Array(n).fill(false))\n for(let p of prerequisites) connected[p[0]][p[1]] = true\n for(let k = 0; k < n; k++) {\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < n; j++) {\n connected[i][j] = connected[i][j] || (connected[i][k] && connected[k][j]);\n }\n }\n }\n const res = []\n for(let q of queries) res.push(connected[q[0]][q[1]])\n return res\n};",
"const checkIfPrerequisite = function (numCourses, prerequisites, queries) {\n const n = numCourses\n const connected = Array.from({ length: n }, () => Array(n).fill(false))\n for (let p of prerequisites) connected[p[0]][p[1]] = true\n for (let k = 0; k < n; k++) {\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n connected[i][j] =\n connected[i][j] || (connected[i][k] && connected[k][j])\n }\n }\n }\n const res = []\n for (let q of queries) res.push(connected[q[0]][q[1]])\n return res\n}",
"const checkIfPrerequisite = function (numCourses, prerequisites, queries) {\n const graph = {},\n connected = Array.from({ length: numCourses }, () =>\n Array(numCourses).fill(-1)\n )\n for (const [u, v] of prerequisites) {\n if (graph[u] == null) graph[u] = []\n graph[u].push(v)\n connected[u][v] = 1\n }\n\n const res = []\n for (const [u, v] of queries) res.push(dfs(u, v))\n\n return res\n\n function dfs(u, v) {\n if (connected[u][v] !== -1) return connected[u][v]\n let res = false\n for (const next of graph[u] || []) {\n if (!res) {\n res ||= dfs(next, v)\n } else break\n }\n connected[u][v] = res\n return res\n }\n}"
] |
|
1,463 | cherry-pickup-ii | [
"Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var cherryPickup = function(grid) {
}; | You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell.
You have two robots that can collect cherries for you:
Robot #1 is located at the top-left corner (0, 0), and
Robot #2 is located at the top-right corner (0, cols - 1).
Return the maximum number of cherries collection using both robots by following the rules below:
From a cell (i, j), robots can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1).
When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
When both robots stay in the same cell, only one takes the cherries.
Both robots cannot move outside of the grid at any moment.
Both robots should reach the bottom row in grid.
Example 1:
Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
Output: 24
Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
Example 2:
Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]
Output: 28
Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.
Constraints:
rows == grid.length
cols == grid[i].length
2 <= rows, cols <= 70
0 <= grid[i][j] <= 100
| Hard | [
"array",
"dynamic-programming",
"matrix"
] | [
"const cherryPickup = function (grid) {\n const m = grid.length\n const n = grid[0].length\n const memo = new Array(m)\n .fill(0)\n .map((mat) => new Array(n).fill(0).map((row) => new Array(n).fill(0)))\n return dfs(grid, m, n, 0, 0, n - 1, memo)\n}\n\nconst dfs = (grid, m, n, r, c1, c2, memo) => {\n if (r === m) return 0\n if (memo[r][c1][c2]) return memo[r][c1][c2]\n let count = 0\n for (let i = -1; i <= 1; i++) {\n for (let j = -1; j <= 1; j++) {\n const nc1 = c1 + i\n const nc2 = c2 + j\n if (0 <= nc1 && nc1 < n && 0 <= nc2 && nc2 < n) {\n count = Math.max(count, dfs(grid, m, n, r + 1, nc1, nc2, memo))\n }\n }\n }\n count += c1 === c2 ? grid[r][c1] : grid[r][c1] + grid[r][c2]\n return (memo[r][c1][c2] = memo[r][c2][c1] = count)\n}"
] |
|
1,464 | maximum-product-of-two-elements-in-an-array | [
"Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1)."
] | /**
* @param {number[]} nums
* @return {number}
*/
var maxProduct = function(nums) {
}; | Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).
Example 1:
Input: nums = [3,4,5,2]
Output: 12
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.
Example 2:
Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.
Example 3:
Input: nums = [3,7]
Output: 12
Constraints:
2 <= nums.length <= 500
1 <= nums[i] <= 10^3
| Easy | [
"array",
"sorting",
"heap-priority-queue"
] | [
"const maxProduct = function(nums) {\n const n = nums.length\n let res = 0, m1 = 0, m2 = 0\n for(const e of nums) {\n if(e > m1) {\n m2 = m1\n m1 = e\n } else if(e > m2) {\n m2 = e\n }\n }\n\n return (m1 - 1) * (m2 - 1)\n};"
] |
|
1,465 | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | [
"Sort the arrays, then compute the maximum difference between two consecutive elements for horizontal cuts and vertical cuts.",
"The answer is the product of these maximum values in horizontal cuts and vertical cuts."
] | /**
* @param {number} h
* @param {number} w
* @param {number[]} horizontalCuts
* @param {number[]} verticalCuts
* @return {number}
*/
var maxArea = function(h, w, horizontalCuts, verticalCuts) {
}; | You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where:
horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and
verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.
Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 109 + 7.
Example 1:
Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
Output: 4
Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.
Example 2:
Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]
Output: 6
Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.
Example 3:
Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]
Output: 9
Constraints:
2 <= h, w <= 109
1 <= horizontalCuts.length <= min(h - 1, 105)
1 <= verticalCuts.length <= min(w - 1, 105)
1 <= horizontalCuts[i] < h
1 <= verticalCuts[i] < w
All the elements in horizontalCuts are distinct.
All the elements in verticalCuts are distinct.
| Medium | [
"array",
"greedy",
"sorting"
] | [
"const maxArea = function(h, w, horizontalCuts, verticalCuts) {\n return getMax(h, horizontalCuts) * getMax(w, verticalCuts) % (10 ** 9 + 7)\n};\n\nfunction getMax(limit, cuts) {\n cuts.sort((a, b) => a - b)\n const n = cuts.length\n let max = Math.max(cuts[0], limit - cuts[n - 1])\n for(let i = 1; i < n; i++) {\n max = Math.max(max, cuts[i] - cuts[i - 1])\n }\n return max\n}",
"const maxArea = function(h, w, horizontalCuts, verticalCuts) {\n return (BigInt(maxGap(h, horizontalCuts)) * BigInt(maxGap(w, verticalCuts))) % BigInt(1e9 + 7)\n function maxGap(limit, arr) {\n let res = 0\n arr.sort((a, b) => a - b)\n for(let i = 0, n = arr.length; i < n; i++) {\n let tmp = i === 0 ? arr[0] : arr[i] - arr[i - 1]\n res = Math.max(res, tmp)\n }\n res = Math.max(res, limit - arr[arr.length - 1])\n \n return res\n }\n};"
] |
|
1,466 | reorder-routes-to-make-all-paths-lead-to-the-city-zero | [
"Treat the graph as undirected. Start a dfs from the root, if you come across an edge in the forward direction, you need to reverse the edge."
] | /**
* @param {number} n
* @param {number[][]} connections
* @return {number}
*/
var minReorder = function(n, connections) {
}; | There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.
This year, there will be a big event in the capital (city 0), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.
It's guaranteed that each city can reach city 0 after reorder.
Example 1:
Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 2:
Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
Output: 2
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 3:
Input: n = 3, connections = [[1,0],[2,0]]
Output: 0
Constraints:
2 <= n <= 5 * 104
connections.length == n - 1
connections[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
| Medium | [
"depth-first-search",
"breadth-first-search",
"graph"
] | null | [] |
1,467 | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | [
"Check how many ways you can distribute the balls between the boxes.",
"Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n).",
"The probability of a draw is the sigma of probabilities of different ways to achieve draw.",
"Can you use Dynamic programming to solve this problem in a better complexity ?"
] | /**
* @param {number[]} balls
* @return {number}
*/
var getProbability = function(balls) {
}; | Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i.
All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully).
Please note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully).
Return the probability that the two boxes have the same number of distinct balls. Answers within 10-5 of the actual value will be accepted as correct.
Example 1:
Input: balls = [1,1]
Output: 1.00000
Explanation: Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
Example 2:
Input: balls = [2,1,1]
Output: 0.66667
Explanation: We have the set of balls [1, 1, 2, 3]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):
[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]
After that, we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667
Example 3:
Input: balls = [1,2,1,2]
Output: 0.60000
Explanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6
Constraints:
1 <= balls.length <= 8
1 <= balls[i] <= 6
sum(balls) is even.
| Hard | [
"array",
"math",
"dynamic-programming",
"backtracking",
"combinatorics",
"probability-and-statistics"
] | [
"const getProbability = function(balls) {\n const k = balls.length;\n const halfUsed = balls.reduce((acc, val) => acc + val, 0) / 2;\n const startArray = new Array(k);\n startArray.fill(0);\n const perm = function (b1, b2) {\n let p1, p2, s1, s2;\n s1 = b1.reduce((acc, val) => acc + val, 0);\n s2 = b2.reduce((acc, val) => acc + val, 0);\n const fact = function (n) {\n let f = 1;\n for (let i = 2; i <= n; i++) f *= i;\n return f;\n };\n p1 = fact(s1);\n p2 = fact(s2);\n b1.forEach((val) => {\n if (val > 1) p1 /= fact(val);\n });\n b2.forEach((val) => {\n if (val > 1) p2 /= fact(val);\n });\n return p1 * p2;\n };\n\n const getValidCombos = function (ballsUsed, colorNum = 0) {\n let box1Used = ballsUsed.reduce((acc, val) => acc + val, 0);\n let matches = { good: 0, total: 0 },\n thisColorMax = halfUsed - box1Used;\n if (colorNum === k - 1) {\n if (thisColorMax > balls[colorNum]) return { good: 0, total: 0 };\n ballsUsed[colorNum] = thisColorMax;\n let ballsLeft = [];\n let colorsUsed = [0, 0];\n for (let i = 0; i < k; i++) {\n ballsLeft[i] = balls[i] - ballsUsed[i];\n if (ballsUsed[i] > 0) colorsUsed[0]++;\n if (ballsLeft[i] > 0) colorsUsed[1]++;\n }\n let permutations = perm(ballsUsed, ballsLeft, k);\n return {\n good: colorsUsed[1] === colorsUsed[0] ? permutations : 0,\n total: permutations,\n };\n }\n thisColorMax = Math.min(thisColorMax, balls[colorNum]);\n for (let i = 0; i <= thisColorMax; i++) {\n let match = getValidCombos([...ballsUsed], colorNum + 1);\n matches = {\n good: matches.good + match.good,\n total: matches.total + match.total,\n };\n ballsUsed[colorNum]++;\n }\n return matches;\n };\n let res = getValidCombos(startArray);\n return res.good / res.total;\n};",
"const getProbability = function (balls) {\n const k = balls.length\n const halfUsed = balls.reduce((acc, val) => acc + val, 0) / 2\n const startArray = new Array(k)\n startArray.fill(0)\n const perm = function (b1, b2) {\n let p1, p2, s1, s2\n s1 = b1.reduce((acc, val) => acc + val, 0)\n s2 = b2.reduce((acc, val) => acc + val, 0)\n const fact = function (n) {\n let f = 1\n for (let i = 2; i <= n; i++) f *= i\n return f\n }\n p1 = fact(s1)\n p2 = fact(s2)\n b1.forEach((val) => {\n if (val > 1) p1 /= fact(val)\n })\n b2.forEach((val) => {\n if (val > 1) p2 /= fact(val)\n })\n return p1 * p2\n }\n\n const getValidCombos = function (ballsUsed, colorNum = 0) {\n let box1Used = ballsUsed.reduce((acc, val) => acc + val, 0)\n let matches = { good: 0, total: 0 },\n thisColorMax = halfUsed - box1Used\n if (colorNum === k - 1) {\n if (thisColorMax > balls[colorNum]) return { good: 0, total: 0 }\n ballsUsed[colorNum] = thisColorMax\n let ballsLeft = []\n let colorsUsed = [0, 0]\n for (let i = 0; i < k; i++) {\n ballsLeft[i] = balls[i] - ballsUsed[i]\n if (ballsUsed[i] > 0) colorsUsed[0]++\n if (ballsLeft[i] > 0) colorsUsed[1]++\n }\n let permutations = perm(ballsUsed, ballsLeft, k)\n return {\n good: colorsUsed[1] === colorsUsed[0] ? permutations : 0,\n total: permutations,\n }\n }\n thisColorMax = Math.min(thisColorMax, balls[colorNum])\n for (let i = 0; i <= thisColorMax; i++) {\n let match = getValidCombos([...ballsUsed], colorNum + 1)\n matches = {\n good: matches.good + match.good,\n total: matches.total + match.total,\n }\n ballsUsed[colorNum]++\n }\n return matches\n }\n let res = getValidCombos(startArray)\n return res.good / res.total\n}"
] |
|
1,470 | shuffle-the-array | [
"Use two pointers to create the new array of 2n elements. The first starting at the beginning and the other starting at (n+1)th position. Alternate between them and create the new array."
] | /**
* @param {number[]} nums
* @param {number} n
* @return {number[]}
*/
var shuffle = function(nums, n) {
}; | Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
Constraints:
1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3
| Easy | [
"array"
] | [
"const shuffle = function(nums, n) {\n const res = []\n for(let i = 0; i < n; i++) {\n res.push(nums[i], nums[i + n])\n }\n return res\n};"
] |
|
1,471 | the-k-strongest-values-in-an-array | [
"Calculate the median of the array as defined in the statement.",
"Use custom sort function to sort values (Strongest first), then slice the first k."
] | /**
* @param {number[]} arr
* @param {number} k
* @return {number[]}
*/
var getStrongest = function(arr, k) {
}; | Given an array of integers arr and an integer k.
A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.
If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].
Return a list of the strongest k values in the array. return the answer in any arbitrary order.
Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed).
For arr = [6, -3, 7, 2, 11], n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2. The median is 6.
For arr = [-7, 22, 17, 3], n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1. The median is 3.
Example 1:
Input: arr = [1,2,3,4,5], k = 2
Output: [5,1]
Explanation: Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.
Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.
Example 2:
Input: arr = [1,1,3,5,5], k = 2
Output: [5,5]
Explanation: Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].
Example 3:
Input: arr = [6,7,11,7,6,8], k = 5
Output: [11,8,6,6,7]
Explanation: Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].
Any permutation of [11,8,6,6,7] is accepted.
Constraints:
1 <= arr.length <= 105
-105 <= arr[i] <= 105
1 <= k <= arr.length
| Medium | [
"array",
"two-pointers",
"sorting"
] | null | [] |
1,472 | design-browser-history | [
"Use two stacks: one for back history, and one for forward history. You can simulate the functions by popping an element from one stack and pushing it into the other.",
"Can you improve program runtime by using a different data structure?"
] | /**
* @param {string} homepage
*/
var BrowserHistory = function(homepage) {
};
/**
* @param {string} url
* @return {void}
*/
BrowserHistory.prototype.visit = function(url) {
};
/**
* @param {number} steps
* @return {string}
*/
BrowserHistory.prototype.back = function(steps) {
};
/**
* @param {number} steps
* @return {string}
*/
BrowserHistory.prototype.forward = function(steps) {
};
/**
* Your BrowserHistory object will be instantiated and called as such:
* var obj = new BrowserHistory(homepage)
* obj.visit(url)
* var param_2 = obj.back(steps)
* var param_3 = obj.forward(steps)
*/ | You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps.
Implement the BrowserHistory class:
BrowserHistory(string homepage) Initializes the object with the homepage of the browser.
void visit(string url) Visits url from the current page. It clears up all the forward history.
string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps.
string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.
Example:
Input:
["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]
Output:
[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]
Explanation:
BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
browserHistory.visit("google.com"); // You are in "leetcode.com". Visit "google.com"
browserHistory.visit("facebook.com"); // You are in "google.com". Visit "facebook.com"
browserHistory.visit("youtube.com"); // You are in "facebook.com". Visit "youtube.com"
browserHistory.back(1); // You are in "youtube.com", move back to "facebook.com" return "facebook.com"
browserHistory.back(1); // You are in "facebook.com", move back to "google.com" return "google.com"
browserHistory.forward(1); // You are in "google.com", move forward to "facebook.com" return "facebook.com"
browserHistory.visit("linkedin.com"); // You are in "facebook.com". Visit "linkedin.com"
browserHistory.forward(2); // You are in "linkedin.com", you cannot move forward any steps.
browserHistory.back(2); // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com"
browserHistory.back(7); // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"
Constraints:
1 <= homepage.length <= 20
1 <= url.length <= 20
1 <= steps <= 100
homepage and url consist of '.' or lower case English letters.
At most 5000 calls will be made to visit, back, and forward.
| Medium | [
"array",
"linked-list",
"stack",
"design",
"doubly-linked-list",
"data-stream"
] | [
"const BrowserHistory = function(homepage) {\n this.idx = 0\n this.last = 0\n this.arr = [homepage]\n};\n\n\nBrowserHistory.prototype.visit = function(url) {\n this.idx++\n this.arr[this.idx] = url\n this.last = this.idx\n};\n\n\nBrowserHistory.prototype.back = function(steps) {\n const idx = this.idx\n let tmp = idx - steps\n if(tmp < 0) {\n this.idx = 0\n return this.arr[0]\n } else {\n this.idx = tmp\n return this.arr[tmp]\n }\n};\n\n\nBrowserHistory.prototype.forward = function(steps) {\n const n = this.last + 1\n let tmp = this.idx + steps\n if(tmp >= n) {\n this.idx = n - 1\n return this.arr[n - 1]\n } else {\n this.idx = tmp\n return this.arr[tmp]\n }\n};"
] |
|
1,473 | paint-house-iii | [
"Use Dynamic programming.",
"Define dp[i][j][k] as the minimum cost where we have k neighborhoods in the first i houses and the i-th house is painted with the color j."
] | /**
* @param {number[]} houses
* @param {number[][]} cost
* @param {number} m
* @param {number} n
* @param {number} target
* @return {number}
*/
var minCost = function(houses, cost, m, n, target) {
}; | There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color.
For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}].
Given an array houses, an m x n matrix cost and an integer target where:
houses[i]: is the color of the house i, and 0 if the house is not painted yet.
cost[i][j]: is the cost of paint the house i with the color j + 1.
Return the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1.
Example 1:
Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3
Output: 9
Explanation: Paint houses of this way [1,2,2,1,1]
This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].
Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.
Example 2:
Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3
Output: 11
Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]
This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}].
Cost of paint the first and last house (10 + 1) = 11.
Example 3:
Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3
Output: -1
Explanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.
Constraints:
m == houses.length == cost.length
n == cost[i].length
1 <= m <= 100
1 <= n <= 20
1 <= target <= m
0 <= houses[i] <= n
1 <= cost[i][j] <= 104
| Hard | [
"array",
"dynamic-programming"
] | [
"const minCost = function (houses, cost, m, n, target) {\n const dp = Array(m)\n .fill(null)\n .map(() =>\n Array(target)\n .fill(null)\n .map(() => Array(n + 1).fill(0))\n )\n function dfs(i, t, p) {\n if (i === m && t === 0) {\n return 0\n } else if (t < 0 || m - i < t || (i === m && t > 0)) {\n return Infinity\n } else if (p > -1 && dp[i][t][p]) {\n return dp[i][t][p]\n } else {\n let res = Infinity\n if (houses[i]) {\n const tmp = houses[i] !== p ? 1 : 0\n res = dfs(i + 1, t - tmp, houses[i])\n } else {\n for (let k = 1; k <= n; k++) {\n const tmp = k !== p ? 1 : 0\n res = Math.min(res, cost[i][k - 1] + dfs(i + 1, t - tmp, k))\n }\n }\n if (p > -1) {\n dp[i][t][p] = res\n }\n return res\n }\n }\n const answer = dfs(0, target, -1)\n return answer === Infinity ? -1 : answer\n}"
] |
|
1,475 | final-prices-with-a-special-discount-in-a-shop | [
"Use brute force: For the ith item in the shop with a loop find the first position j satisfying the conditions and apply the discount, otherwise, the discount is 0."
] | /**
* @param {number[]} prices
* @return {number[]}
*/
var finalPrices = function(prices) {
}; | You are given an integer array prices where prices[i] is the price of the ith item in a shop.
There is a special discount for items in the shop. If you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i]. Otherwise, you will not receive any discount at all.
Return an integer array answer where answer[i] is the final price you will pay for the ith item of the shop, considering the special discount.
Example 1:
Input: prices = [8,4,6,2,3]
Output: [4,2,4,2,3]
Explanation:
For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.
For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.
For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.
For items 3 and 4 you will not receive any discount at all.
Example 2:
Input: prices = [1,2,3,4,5]
Output: [1,2,3,4,5]
Explanation: In this case, for all items, you will not receive any discount at all.
Example 3:
Input: prices = [10,1,1,6]
Output: [9,0,1,6]
Constraints:
1 <= prices.length <= 500
1 <= prices[i] <= 1000
| Easy | [
"array",
"stack",
"monotonic-stack"
] | [
"const finalPrices = function(prices) {\n const res = [], n = prices.length\n for(let i = 0; i < n; i++) {\n const cur = prices[i]\n let dis = null\n for(let j = i + 1; j < n; j++) {\n if(prices[j] <= cur) {\n dis = prices[j]\n break\n }\n }\n res.push(dis == null ? cur : cur - dis)\n }\n return res\n};"
] |
|
1,476 | subrectangle-queries | [
"Use brute force to update a rectangle and, response to the queries in O(1)."
] | /**
* @param {number[][]} rectangle
*/
var SubrectangleQueries = function(rectangle) {
};
/**
* @param {number} row1
* @param {number} col1
* @param {number} row2
* @param {number} col2
* @param {number} newValue
* @return {void}
*/
SubrectangleQueries.prototype.updateSubrectangle = function(row1, col1, row2, col2, newValue) {
};
/**
* @param {number} row
* @param {number} col
* @return {number}
*/
SubrectangleQueries.prototype.getValue = function(row, col) {
};
/**
* Your SubrectangleQueries object will be instantiated and called as such:
* var obj = new SubrectangleQueries(rectangle)
* obj.updateSubrectangle(row1,col1,row2,col2,newValue)
* var param_2 = obj.getValue(row,col)
*/ | Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:
1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)
Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2).
2. getValue(int row, int col)
Returns the current value of the coordinate (row,col) from the rectangle.
Example 1:
Input
["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue","getValue"]
[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]
Output
[null,1,null,5,5,null,10,5]
Explanation
SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]);
// The initial rectangle (4x3) looks like:
// 1 2 1
// 4 3 4
// 3 2 1
// 1 1 1
subrectangleQueries.getValue(0, 2); // return 1
subrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);
// After this update the rectangle looks like:
// 5 5 5
// 5 5 5
// 5 5 5
// 5 5 5
subrectangleQueries.getValue(0, 2); // return 5
subrectangleQueries.getValue(3, 1); // return 5
subrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);
// After this update the rectangle looks like:
// 5 5 5
// 5 5 5
// 5 5 5
// 10 10 10
subrectangleQueries.getValue(3, 1); // return 10
subrectangleQueries.getValue(0, 2); // return 5
Example 2:
Input
["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue"]
[[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]
Output
[null,1,null,100,100,null,20]
Explanation
SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);
subrectangleQueries.getValue(0, 0); // return 1
subrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);
subrectangleQueries.getValue(0, 0); // return 100
subrectangleQueries.getValue(2, 2); // return 100
subrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20);
subrectangleQueries.getValue(2, 2); // return 20
Constraints:
There will be at most 500 operations considering both methods: updateSubrectangle and getValue.
1 <= rows, cols <= 100
rows == rectangle.length
cols == rectangle[i].length
0 <= row1 <= row2 < rows
0 <= col1 <= col2 < cols
1 <= newValue, rectangle[i][j] <= 10^9
0 <= row < rows
0 <= col < cols
| Medium | [
"array",
"design",
"matrix"
] | [
"const SubrectangleQueries = function(rectangle) {\n this.rect = rectangle\n this.ops = []\n};\n\n\nSubrectangleQueries.prototype.updateSubrectangle = function(row1, col1, row2, col2, newValue) {\n this.ops.push([row1, col1, row2, col2, newValue])\n};\n\n\nSubrectangleQueries.prototype.getValue = function(row, col) {\n for(let i = this.ops.length - 1; i >= 0; i--) {\n const op = this.ops[i]\n if(op[0] <= row && op[1] <= col && row <= op[2] && col <= op[3]) return op[4]\n }\n return this.rect[row][col]\n};"
] |
|
1,477 | find-two-non-overlapping-sub-arrays-each-with-target-sum | [
"Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k.",
"The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr.length.",
"If you are still stuck with how to build prefix and suffix, you can store for each index i the length of the sub-array starts at i and has sum = k or infinity otherwise, and you can use it to build both prefix and suffix."
] | /**
* @param {number[]} arr
* @param {number} target
* @return {number}
*/
var minSumOfLengths = function(arr, target) {
}; | You are given an array of integers arr and an integer target.
You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.
Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.
Example 1:
Input: arr = [3,2,2,4,3], target = 3
Output: 2
Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.
Example 2:
Input: arr = [7,3,4,7], target = 7
Output: 2
Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.
Example 3:
Input: arr = [4,3,2,6,2,3,4], target = 6
Output: -1
Explanation: We have only one sub-array of sum = 6.
Constraints:
1 <= arr.length <= 105
1 <= arr[i] <= 1000
1 <= target <= 108
| Medium | [
"array",
"hash-table",
"binary-search",
"dynamic-programming",
"sliding-window"
] | null | [] |
1,478 | allocate-mailboxes | [
"If k =1, the minimum distance is obtained allocating the mailbox in the median of the array houses.",
"Generalize this idea, using dynamic programming allocating k mailboxes."
] | /**
* @param {number[]} houses
* @param {number} k
* @return {number}
*/
var minDistance = function(houses, k) {
}; | Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street.
Return the minimum total distance between each house and its nearest mailbox.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: houses = [1,4,8,10,20], k = 3
Output: 5
Explanation: Allocate mailboxes in position 3, 9 and 20.
Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5
Example 2:
Input: houses = [2,3,5,12,18], k = 2
Output: 9
Explanation: Allocate mailboxes in position 3 and 14.
Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.
Constraints:
1 <= k <= houses.length <= 100
1 <= houses[i] <= 104
All the integers of houses are unique.
| Hard | [
"array",
"math",
"dynamic-programming",
"sorting"
] | [
"const minDistance = function (A, K) {\n A.sort((a, b) => a - b)\n let n = A.length,\n B = new Array(n + 1).fill(0),\n dp = Array(n).fill(0)\n for (let i = 0; i < n; ++i) {\n B[i + 1] = B[i] + A[i]\n dp[i] = 1e6\n }\n for (let k = 1; k <= K; ++k) {\n for (let j = n - 1; j > k - 2; --j) {\n for (let i = k - 2; i < j; ++i) {\n let m1 = ((i + j + 1) / 2) >> 0,\n m2 = ((i + j + 2) / 2) >> 0\n let last = B[j + 1] - B[m2] - (B[m1 + 1] - B[i + 1])\n dp[j] = Math.min(dp[j], (i >= 0 ? dp[i] : 0) + last)\n }\n }\n }\n return dp[n - 1]\n}",
"function minDistance(houses, k) {\n const n = houses.length, { abs, min } = Math, INF = Infinity\n houses.sort((a, b) => a - b)\n const costs = Array.from({ length: 100 }, () => Array(100).fill(0))\n const memo = Array.from({ length: 100 }, () => Array(100).fill(null))\n\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < n; j++) {\n const mid = houses[~~((i + j) >> 1)]\n for (let k = i; k <= j; k++) costs[i][j] += abs(mid - houses[k])\n }\n }\n \n return dp(k, 0)\n\n function dp(k, i) {\n if (k === 0 && i === n) return 0\n if (k === 0 || i === n) return INF\n if (memo[k][i] != null) return memo[k][i]\n let res = INF\n for (let j = i; j < n; j++) {\n res = min(res, costs[i][j] + dp(k - 1, j + 1))\n }\n\n return memo[k][i] = res\n }\n}"
] |
|
1,480 | running-sum-of-1d-array | [
"Think about how we can calculate the i-th number in the running sum from the (i-1)-th number."
] | /**
* @param {number[]} nums
* @return {number[]}
*/
var runningSum = function(nums) {
}; | Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Example 2:
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
Example 3:
Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]
Constraints:
1 <= nums.length <= 1000
-10^6 <= nums[i] <= 10^6
| Easy | [
"array",
"prefix-sum"
] | [
"const runningSum = function(nums) {\n for(let i = 1, len = nums.length; i < len; i++) {\n nums[i] += nums[i - 1]\n }\n return nums\n};"
] |
|
1,481 | least-number-of-unique-integers-after-k-removals | [
"Use a map to count the frequencies of the numbers in the array.",
"An optimal strategy is to remove the numbers with the smallest count first."
] | /**
* @param {number[]} arr
* @param {number} k
* @return {number}
*/
var findLeastNumOfUniqueInts = function(arr, k) {
}; | Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
Example 1:
Input: arr = [5,5,4], k = 1
Output: 1
Explanation: Remove the single 4, only 5 is left.
Example 2:
Input: arr = [4,3,1,1,3,3,2], k = 3
Output: 2
Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 10^9
0 <= k <= arr.length
| Medium | [
"array",
"hash-table",
"greedy",
"sorting",
"counting"
] | [
"// Given an array of integers arr and an integer k. Find the least number of unique integers \n// after removing exactly k elements.\n\n\n// Example 1:\n\n// Input: arr = [5,5,4], k = 1\n// Output: 1\n// Explanation: Remove the single 4, only 5 is left.\n// Example 2:\n// Input: arr = [4,3,1,1,3,3,2], k = 3\n// Output: 2\n// Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.\n\n\n// Constraints:\n\n// 1 <= arr.length <= 10^5\n// 1 <= arr[i] <= 10^9\n// 0 <= k <= arr.length\n\n\nconst findLeastNumOfUniqueInts = function (arr, k) {\n const map = {}\n \n for (const num of arr) {\n map[num] = map[num] || 0\n map[num] += 1\n }\n const keys = Object.keys(map).sort((a, b) => map[a] - map[b])\n for (const key of keys) {\n while (map[key] > 0 && k > 0) {\n k--\n map[key] -= 1\n if (map[key] === 0) {\n delete map[key]\n }\n }\n }\n return Object.keys(map).length\n}"
] |
|
1,482 | minimum-number-of-days-to-make-m-bouquets | [
"If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x.",
"We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x."
] | /**
* @param {number[]} bloomDay
* @param {number} m
* @param {number} k
* @return {number}
*/
var minDays = function(bloomDay, m, k) {
}; | You are given an integer array bloomDay, an integer m and an integer k.
You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here is the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Constraints:
bloomDay.length == n
1 <= n <= 105
1 <= bloomDay[i] <= 109
1 <= m <= 106
1 <= k <= n
| Medium | [
"array",
"binary-search"
] | [
"const minDays = function(bloomDay, m, k) {\n const n = bloomDay.length\n let l = -1, r = Math.max(...bloomDay)\n while(l < r) {\n const mid = l + Math.floor((r - l) / 2)\n if(valid(mid)) r = mid\n else l = mid + 1\n }\n return valid(l) ? l : -1\n\n function valid(mid) {\n let res = 0, cur = 0\n for (let i = 0; i < n; i++) {\n const e = bloomDay[i]\n if(e <= mid) {\n cur++\n if(cur >= k) {\n res++\n cur = 0\n }\n } else {\n cur = 0\n }\n }\n return res >= m\n }\n};"
] |
|
1,483 | kth-ancestor-of-a-tree-node | [
"The queries must be answered efficiently to avoid time limit exceeded verdict.",
"Use sparse table (dynamic programming application) to travel the tree upwards in a fast way."
] | /**
* @param {number} n
* @param {number[]} parent
*/
var TreeAncestor = function(n, parent) {
};
/**
* @param {number} node
* @param {number} k
* @return {number}
*/
TreeAncestor.prototype.getKthAncestor = function(node, k) {
};
/**
* Your TreeAncestor object will be instantiated and called as such:
* var obj = new TreeAncestor(n, parent)
* var param_1 = obj.getKthAncestor(node,k)
*/ | You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node.
The kth ancestor of a tree node is the kth node in the path from that node to the root node.
Implement the TreeAncestor class:
TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array.
int getKthAncestor(int node, int k) return the kth ancestor of the given node node. If there is no such ancestor, return -1.
Example 1:
Input
["TreeAncestor", "getKthAncestor", "getKthAncestor", "getKthAncestor"]
[[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]]
Output
[null, 1, 0, -1]
Explanation
TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);
treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3
treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5
treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor
Constraints:
1 <= k <= n <= 5 * 104
parent.length == n
parent[0] == -1
0 <= parent[i] < n for all 0 < i < n
0 <= node < n
There will be at most 5 * 104 queries.
| Hard | [
"binary-search",
"dynamic-programming",
"tree",
"depth-first-search",
"breadth-first-search",
"design"
] | [
"var TreeAncestor = function(n, parent) {\n // initialize\n this.P = Array.from({length: 20}, () => Array(n).fill(-1))\n // 2^0\n for(let i = 0; i < parent.length; i++){\n this.P[0][i] = parent[i];\n }\n\n // 2^i\n for(let i = 1; i < 20; i++){\n for(let node = 0; node < parent.length; node++){\n let nodep = this.P[i-1][node];\n if(nodep != -1) this.P[i][node] = this.P[i-1][nodep];\n }\n } \n};\n\n\nTreeAncestor.prototype.getKthAncestor = function(node, k) {\n for(let i = 0; i < 20; i++){\n if(k & (1 << i)){\n node = this.P[i][node];\n if(node == -1) return -1;\n }\n }\n return node; \n};"
] |
|
1,486 | xor-operation-in-an-array | [
"Simulate the process, create an array nums and return the Bitwise XOR of all elements of it."
] | /**
* @param {number} n
* @param {number} start
* @return {number}
*/
var xorOperation = function(n, start) {
}; | You are given an integer n and an integer start.
Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length.
Return the bitwise XOR of all elements of nums.
Example 1:
Input: n = 5, start = 0
Output: 8
Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^" corresponds to bitwise XOR operator.
Example 2:
Input: n = 4, start = 3
Output: 8
Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.
Constraints:
1 <= n <= 1000
0 <= start <= 1000
n == nums.length
| Easy | [
"math",
"bit-manipulation"
] | [
"const xorOperation = function(n, start) {\n const nums = []\n let i = 0\n while (i < n) {\n nums[i] = start + 2 * i\n i++\n }\n // console.log(nums)\n let res = nums[0]\n for(let i = 1; i < n; i++) res ^= nums[i]\n return res\n};"
] |
|
1,487 | making-file-names-unique | [
"Keep a map of each name and the smallest valid integer that can be appended as a suffix to it.",
"If the name is not present in the map, you can use it without adding any suffixes.",
"If the name is present in the map, append the smallest proper suffix, and add the new name to the map."
] | /**
* @param {string[]} names
* @return {string[]}
*/
var getFolderNames = function(names) {
}; | Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i].
Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique.
Return an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it.
Example 1:
Input: names = ["pes","fifa","gta","pes(2019)"]
Output: ["pes","fifa","gta","pes(2019)"]
Explanation: Let's see how the file system creates folder names:
"pes" --> not assigned before, remains "pes"
"fifa" --> not assigned before, remains "fifa"
"gta" --> not assigned before, remains "gta"
"pes(2019)" --> not assigned before, remains "pes(2019)"
Example 2:
Input: names = ["gta","gta(1)","gta","avalon"]
Output: ["gta","gta(1)","gta(2)","avalon"]
Explanation: Let's see how the file system creates folder names:
"gta" --> not assigned before, remains "gta"
"gta(1)" --> not assigned before, remains "gta(1)"
"gta" --> the name is reserved, system adds (k), since "gta(1)" is also reserved, systems put k = 2. it becomes "gta(2)"
"avalon" --> not assigned before, remains "avalon"
Example 3:
Input: names = ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"]
Output: ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"]
Explanation: When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4)".
Constraints:
1 <= names.length <= 5 * 104
1 <= names[i].length <= 20
names[i] consists of lowercase English letters, digits, and/or round brackets.
| Medium | [
"array",
"hash-table",
"string"
] | null | [] |
1,488 | avoid-flood-in-the-city | [
"Keep An array of the last day there was rains over each city.",
"Keep an array of the days you can dry a lake when you face one.",
"When it rains over a lake, check the first possible day you can dry this lake and assign this day to this lake."
] | /**
* @param {number[]} rains
* @return {number[]}
*/
var avoidFlood = function(rains) {
}; | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake.
Given an integer array rains where:
rains[i] > 0 means there will be rains over the rains[i] lake.
rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.
Return an array ans where:
ans.length == rains.length
ans[i] == -1 if rains[i] > 0.
ans[i] is the lake you choose to dry in the ith day if rains[i] == 0.
If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.
Example 1:
Input: rains = [1,2,3,4]
Output: [-1,-1,-1,-1]
Explanation: After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day full lakes are [1,2,3]
After the fourth day full lakes are [1,2,3,4]
There's no day to dry any lake and there is no flood in any lake.
Example 2:
Input: rains = [1,2,0,0,2,1]
Output: [-1,-1,2,1,-1,-1]
Explanation: After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day, we dry lake 2. Full lakes are [1]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are [2].
After the sixth day, full lakes are [1,2].
It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.
Example 3:
Input: rains = [1,2,0,1,2]
Output: []
Explanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day.
After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
Constraints:
1 <= rains.length <= 105
0 <= rains[i] <= 109
| Medium | [
"array",
"hash-table",
"binary-search",
"greedy",
"heap-priority-queue"
] | null | [] |
1,489 | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | [
"Use the Kruskal algorithm to find the minimum spanning tree by sorting the edges and picking edges from ones with smaller weights.",
"Use a disjoint set to avoid adding redundant edges that result in a cycle.",
"To find if one edge is critical, delete that edge and re-run the MST algorithm and see if the weight of the new MST increases.",
"To find if one edge is non-critical (in any MST), include that edge to the accepted edge list and continue the MST algorithm, then see if the resulting MST has the same weight of the initial MST of the entire graph."
] | /**
* @param {number} n
* @param {number[][]} edges
* @return {number[][]}
*/
var findCriticalAndPseudoCriticalEdges = function(n, edges) {
}; | Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
Example 1:
Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]
Output: [[0,1],[2,3,4,5]]
Explanation: The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
Example 2:
Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]
Output: [[],[0,1,2,3]]
Explanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
Constraints:
2 <= n <= 100
1 <= edges.length <= min(200, n * (n - 1) / 2)
edges[i].length == 3
0 <= ai < bi < n
1 <= weighti <= 1000
All pairs (ai, bi) are distinct.
| Hard | [
"union-find",
"graph",
"sorting",
"minimum-spanning-tree",
"strongly-connected-component"
] | [
"const findCriticalAndPseudoCriticalEdges = function (n, edges) {\n const criticalEdges = [],\n psuedoCriticalEdges = [],\n map = new Map()\n edges.forEach((edge, i) => map.set(edge, i))\n edges.sort((a, b) => a[2] - b[2])\n const buildMST = (pick, skip) => {\n const uf = new UnionFind(n)\n let cost = 0\n if (pick !== null) {\n uf.union(pick[0], pick[1])\n cost += pick[2]\n }\n for (let edge of edges) {\n if (edge !== skip && uf.union(edge[0], edge[1])) cost += edge[2]\n }\n return uf.count === 1 ? cost : Number.MAX_SAFE_INTEGER\n }\n const minCost = buildMST(null, null)\n for (let edge of edges) {\n const index = map.get(edge)\n const costWithout = buildMST(null, edge)\n if (costWithout > minCost) {\n criticalEdges.push(index)\n } else {\n const costWith = buildMST(edge, null)\n if (costWith === minCost) psuedoCriticalEdges.push(index)\n }\n }\n return [criticalEdges, psuedoCriticalEdges]\n}\nclass UnionFind {\n constructor(n) {\n this.parents = Array(n)\n .fill(0)\n .map((e, i) => i)\n this.ranks = Array(n).fill(0)\n this.count = n\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 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 if (rx !== ry) {\n this.count--\n return true\n } else return false\n }\n}"
] |
|
1,491 | average-salary-excluding-the-minimum-and-maximum-salary | [
"Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2."
] | /**
* @param {number[]} salary
* @return {number}
*/
var average = function(salary) {
}; | You are given an array of unique integers salary where salary[i] is the salary of the ith employee.
Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: salary = [4000,3000,1000,2000]
Output: 2500.00000
Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500
Example 2:
Input: salary = [1000,2000,3000]
Output: 2000.00000
Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000
Constraints:
3 <= salary.length <= 100
1000 <= salary[i] <= 106
All the integers of salary are unique.
| Easy | [
"array",
"sorting"
] | null | [] |
1,492 | the-kth-factor-of-n | [
"The factors of n will be always in the range [1, n].",
"Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list."
] | /**
* @param {number} n
* @param {number} k
* @return {number}
*/
var kthFactor = function(n, k) {
}; | You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0.
Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.
Example 1:
Input: n = 12, k = 3
Output: 3
Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.
Example 2:
Input: n = 7, k = 2
Output: 7
Explanation: Factors list is [1, 7], the 2nd factor is 7.
Example 3:
Input: n = 4, k = 4
Output: -1
Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.
Constraints:
1 <= k <= n <= 1000
Follow up:
Could you solve this problem in less than O(n) complexity?
| Medium | [
"math",
"number-theory"
] | [
"const kthFactor = function (n, k) {\n let d = 1\n for (let i = 1; i * i < n; i++) {\n if (n % i === 0) {\n k--\n if (k === 0) return i\n }\n }\n\n for (let i = ~~Math.sqrt(n); i >= 1; i--) {\n if (n % ~~(n / i) === 0) {\n k--\n // console.log(n, i, n/i, n % (n / i))\n if (k === 0) return n / i\n }\n }\n\n return -1\n}"
] |
|
1,493 | longest-subarray-of-1s-after-deleting-one-element | [
"Maintain a sliding window where there is at most one zero on it."
] | /**
* @param {number[]} nums
* @return {number}
*/
var longestSubarray = function(nums) {
}; | Given a binary array nums, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.
Example 1:
Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
Example 2:
Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].
Example 3:
Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.
Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1.
| Medium | [
"array",
"dynamic-programming",
"sliding-window"
] | [
"const longestSubarray = function(nums) {\n const n = nums.length\n let res = 0\n const pre = Array(n).fill(0)\n const suf = Array(n).fill(0)\n \n let cnt = 0, hasZero = false\n for(let i = 0; i < n; i++) {\n if(nums[i] === 1) {\n cnt++\n pre[i] = cnt\n res = Math.max(res, cnt)\n } else {\n hasZero = true\n cnt = 0\n pre[i] = cnt\n }\n }\n if(!hasZero) res--\n \n cnt = 0\n \n for(let i = n - 1; i >= 0; i--) {\n if(nums[i] === 1) {\n cnt++\n suf[i] = cnt\n\n } else {\n cnt = 0\n suf[i] = cnt\n\n }\n }\n // console.log(pre,suf)\n for(let i = 1; i < n - 1; i++) {\n if(nums[i] === 0) {\n res = Math.max(res, pre[i - 1] + suf[i + 1])\n }\n }\n \n \n return res\n};"
] |
|
1,494 | parallel-courses-ii | [
"Use backtracking with states (bitmask, degrees) where bitmask represents the set of courses, if the ith bit is 1 then the ith course was taken, otherwise, you can take the ith course. Degrees represent the degree for each course (nodes in the graph).",
"Note that you can only take nodes (courses) with degree = 0 and it is optimal at every step in the backtracking take the maximum number of courses limited by k."
] | /**
* @param {number} n
* @param {number[][]} relations
* @param {number} k
* @return {number}
*/
var minNumberOfSemesters = function(n, relations, k) {
}; | You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei. Also, you are given the integer k.
In one semester, you can take at most k courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking.
Return the minimum number of semesters needed to take all courses. The testcases will be generated such that it is possible to take every course.
Example 1:
Input: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2
Output: 3
Explanation: The figure above represents the given graph.
In the first semester, you can take courses 2 and 3.
In the second semester, you can take course 1.
In the third semester, you can take course 4.
Example 2:
Input: n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2
Output: 4
Explanation: The figure above represents the given graph.
In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.
In the second semester, you can take course 4.
In the third semester, you can take course 1.
In the fourth semester, you can take course 5.
Constraints:
1 <= n <= 15
1 <= k <= n
0 <= relations.length <= n * (n-1) / 2
relations[i].length == 2
1 <= prevCoursei, nextCoursei <= n
prevCoursei != nextCoursei
All the pairs [prevCoursei, nextCoursei] are unique.
The given graph is a directed acyclic graph.
| Hard | [
"dynamic-programming",
"bit-manipulation",
"graph",
"bitmask"
] | [
"const minNumberOfSemesters = function (n, dependencies, k) {\n const preq = new Array(n).fill(0)\n for (let dep of dependencies) {\n // to study j, what are the prerequisites?\n // each set bit is a class that we need to take. ith bit means ith class\n // -1 because classes are 1 to n\n preq[dep[1] - 1] |= 1 << (dep[0] - 1)\n }\n const dp = new Array(1 << n).fill(n)\n dp[0] = 0\n for (let i = 0; i < 1 << n; i++) {\n // we are now at status i. we can \"influence\" a later status from this status\n let canStudy = 0 // what are the classes we can study?\n for (let j = 0; j < n; j++) {\n // a & b== b means b is a's subset\n // so if preq[j] is i's subset, we can now study j given status i\n if ((i & preq[j]) == preq[j]) {\n canStudy |= 1 << j\n }\n }\n canStudy &= ~i\n // take out i, so that we only enumerate a subset canStudy without i.\n // note we will | later so here we need a set that has no\n // intersection with i to reduce the enumeration cost\n for (let sub = canStudy; sub > 0; sub = (sub - 1) & canStudy) {\n // we can study one or more courses indicated by set \"canStudy\".\n // we need to enumerate all non empty subset of it.\n // This for loop is a typical way to enumerate all subsets of a given set \"canStudy\"\n // we studied i using dp[i] semesters. now if we also study the\n // subset sub, we need dp [i ]+1 semesters,\n // and the status we can \"influence\" is dp[ i | sub] because at\n // that state, we studied what we want to study in \"sub\"\n if (bitCount(sub) <= k) {\n dp[i | sub] = Math.min(dp[i | sub], dp[i] + 1)\n }\n }\n }\n return dp[(1 << n) - 1]\n}\nfunction bitCount(n) {\n n = n - ((n >> 1) & 0x55555555)\n n = (n & 0x33333333) + ((n >> 2) & 0x33333333)\n return (((n + (n >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24\n}",
"const minNumberOfSemesters = function (n, dependencies, k) {\n const pre = Array(n).fill(0)\n const limit = 1 << n\n for(const [p, v] of dependencies) {\n pre[v - 1] |= (1 << (p - 1))\n }\n const dp = Array(limit).fill(Infinity)\n dp[0] = 0\n \n for(let learned = 0; learned < limit; learned++) {\n let wait = 0\n for(let i = 0; i < n; i++) {\n if( (learned & pre[i]) === pre[i]) {\n wait |= (1 << i)\n }\n }\n wait = wait & (~learned)\n for(let sub = wait; sub; sub = (sub - 1) & wait) {\n if(bitCnt(sub) > k) continue\n const mask = learned | sub\n dp[mask] = Math.min(dp[mask], dp[learned] + 1)\n }\n }\n \n return dp[limit - 1]\n}\n\nfunction bitCnt(num) {\n let res = 0\n while(num) {\n num &= (num - 1)\n res++\n }\n \n return res\n}"
] |
|
1,496 | path-crossing | [
"Simulate the process while keeping track of visited points.",
"Use a set to store previously visited points."
] | /**
* @param {string} path
* @return {boolean}
*/
var isPathCrossing = function(path) {
}; | Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.
Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise.
Example 1:
Input: path = "NES"
Output: false
Explanation: Notice that the path doesn't cross any point more than once.
Example 2:
Input: path = "NESWW"
Output: true
Explanation: Notice that the path visits the origin twice.
Constraints:
1 <= path.length <= 104
path[i] is either 'N', 'S', 'E', or 'W'.
| Easy | [
"hash-table",
"string"
] | null | [] |
1,497 | check-if-array-pairs-are-divisible-by-k | [
"Keep an array of the frequencies of ((x % k) + k) % k for each x in arr.",
"for each i in [0, k - 1] we need to check if freq[k] == freq[k - i]",
"Take care of the case when i == k - i and when i == 0"
] | /**
* @param {number[]} arr
* @param {number} k
* @return {boolean}
*/
var canArrange = function(arr, k) {
}; | Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return true If you can find a way to do that or false otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Constraints:
arr.length == n
1 <= n <= 105
n is even.
-109 <= arr[i] <= 109
1 <= k <= 105
| Medium | [
"array",
"hash-table",
"counting"
] | null | [] |
1,498 | number-of-subsequences-that-satisfy-the-given-sum-condition | [
"Sort the array nums.",
"Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target.",
"Count the number of subsequences."
] | /**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var numSubseq = function(nums, target) {
}; | You are given an array of integers nums and an integer target.
Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: nums = [3,5,6,7], target = 9
Output: 4
Explanation: There are 4 subsequences that satisfy the condition.
[3] -> Min value + max value <= target (3 + 3 <= 9)
[3,5] -> (3 + 5 <= 9)
[3,5,6] -> (3 + 6 <= 9)
[3,6] -> (3 + 6 <= 9)
Example 2:
Input: nums = [3,3,6,8], target = 10
Output: 6
Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]
Example 3:
Input: nums = [2,3,3,4,6,7], target = 12
Output: 61
Explanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).
Number of valid subsequences (63 - 2 = 61).
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106
1 <= target <= 106
| Medium | [
"array",
"two-pointers",
"binary-search",
"sorting"
] | [
"const numSubseq = function(nums, target) {\n const n = nums.length, mod = 1e9 + 7\n const pows = Array(n).fill(1)\n for(let i = 1; i < n; i++) {\n pows[i] = pows[i - 1] * 2 % mod\n }\n let res = 0, l = 0, r = n - 1\n nums.sort((a, b) => a - b)\n while(l <= r) {\n if(nums[l] + nums[r] > target) r--\n else {\n res = (res + pows[r - l]) % mod\n l++\n }\n }\n \n return res\n};"
] |
|
1,499 | max-value-of-equation | [
"Use a priority queue to store for each point i, the tuple [yi-xi, xi]",
"Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue.",
"After popping elements from the queue. If the queue is not empty, calculate the equation with the current point and the point on top of the queue and maximize the answer."
] | /**
* @param {number[][]} points
* @param {number} k
* @return {number}
*/
var findMaxValueOfEquation = function(points, k) {
}; | You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k.
Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length.
It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k.
Example 1:
Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1
Output: 4
Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
Example 2:
Input: points = [[0,0],[3,0],[9,2]], k = 3
Output: 3
Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
Constraints:
2 <= points.length <= 105
points[i].length == 2
-108 <= xi, yi <= 108
0 <= k <= 2 * 108
xi < xj for all 1 <= i < j <= points.length
xi form a strictly increasing sequence.
| Hard | [
"array",
"queue",
"sliding-window",
"heap-priority-queue",
"monotonic-queue"
] | [
"const findMaxValueOfEquation = function (points, k) {\n let res = -Number.MAX_VALUE\n const deque = []\n for (let i = 0; i < points.length; i++) {\n const x = points[i][0]\n const y = points[i][1]\n while (deque.length != 0 && x - deque[0][1] > k) {\n deque.shift()\n }\n if (deque.length != 0) {\n res = Math.max(res, deque[0][0] + x + y)\n }\n while (deque.length != 0 && deque[deque.length - 1][0] <= y - x) {\n deque.pop()\n }\n deque.push([y - x, x])\n }\n return res\n}",
"const findMaxValueOfEquation = function (points, k) {\n const pq = new PriorityQueue((a, b) =>\n a[0] === b[0] ? a[1] < b[1] : b[0] < a[0]\n )\n let res = -Infinity\n for (let point of points) {\n while (!pq.isEmpty() && point[0] - pq.peek()[1] > k) {\n pq.pop()\n }\n if (!pq.isEmpty()) {\n res = Math.max(res, pq.peek()[0] + point[0] + point[1])\n }\n pq.push([point[1] - point[0], point[0]])\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,502 | can-make-arithmetic-progression-from-sequence | [
"Consider that any valid arithmetic progression will be in sorted order.",
"Sort the array, then check if the differences of all consecutive elements are equal."
] | /**
* @param {number[]} arr
* @return {boolean}
*/
var canMakeArithmeticProgression = function(arr) {
}; | A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.
Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.
Example 1:
Input: arr = [3,5,1]
Output: true
Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
Example 2:
Input: arr = [1,2,4]
Output: false
Explanation: There is no way to reorder the elements to obtain an arithmetic progression.
Constraints:
2 <= arr.length <= 1000
-106 <= arr[i] <= 106
| Easy | [
"array",
"sorting"
] | null | [] |
1,503 | last-moment-before-all-ants-fall-out-of-a-plank | [
"The ants change their way when they meet is equivalent to continue moving without changing their direction.",
"Answer is the max distance for one ant to reach the end of the plank in the facing direction."
] | /**
* @param {number} n
* @param {number[]} left
* @param {number[]} right
* @return {number}
*/
var getLastMoment = function(n, left, right) {
}; | We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right.
When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time.
When an ant reaches one end of the plank at a time t, it falls out of the plank immediately.
Given an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank.
Example 1:
Input: n = 4, left = [4,3], right = [0,1]
Output: 4
Explanation: In the image above:
-The ant at index 0 is named A and going to the right.
-The ant at index 1 is named B and going to the right.
-The ant at index 3 is named C and going to the left.
-The ant at index 4 is named D and going to the left.
The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).
Example 2:
Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7]
Output: 7
Explanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall.
Example 3:
Input: n = 7, left = [0,1,2,3,4,5,6,7], right = []
Output: 7
Explanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall.
Constraints:
1 <= n <= 104
0 <= left.length <= n + 1
0 <= left[i] <= n
0 <= right.length <= n + 1
0 <= right[i] <= n
1 <= left.length + right.length <= n + 1
All values of left and right are unique, and each value can appear only in one of the two arrays.
| Medium | [
"array",
"brainteaser",
"simulation"
] | null | [] |
1,504 | count-submatrices-with-all-ones | [
"For each row i, create an array nums where: if mat[i][j] == 0 then nums[j] = 0 else nums[j] = nums[j-1] +1.",
"In the row i, number of rectangles between column j and k(inclusive) and ends in row i, is equal to SUM(min(nums[j, .. idx])) where idx go from j to k. Expected solution is O(n^3)."
] | /**
* @param {number[][]} mat
* @return {number}
*/
var numSubmat = function(mat) {
}; | Given an m x n binary matrix mat, return the number of submatrices that have all ones.
Example 1:
Input: mat = [[1,0,1],[1,1,0],[1,1,0]]
Output: 13
Explanation:
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
There are 3 rectangles of side 2x1.
There is 1 rectangle of side 2x2.
There is 1 rectangle of side 3x1.
Total number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.
Example 2:
Input: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]
Output: 24
Explanation:
There are 8 rectangles of side 1x1.
There are 5 rectangles of side 1x2.
There are 2 rectangles of side 1x3.
There are 4 rectangles of side 2x1.
There are 2 rectangles of side 2x2.
There are 2 rectangles of side 3x1.
There is 1 rectangle of side 3x2.
Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.
Constraints:
1 <= m, n <= 150
mat[i][j] is either 0 or 1.
| Medium | [
"array",
"dynamic-programming",
"stack",
"matrix",
"monotonic-stack"
] | null | [] |
1,505 | minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits | [
"We want to make the smaller digits the most significant digits in the number.",
"For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly."
] | /**
* @param {string} num
* @param {number} k
* @return {string}
*/
var minInteger = function(num, k) {
}; | You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times.
Return the minimum integer you can obtain also as a string.
Example 1:
Input: num = "4321", k = 4
Output: "1342"
Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
Example 2:
Input: num = "100", k = 1
Output: "010"
Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
Example 3:
Input: num = "36789", k = 1000
Output: "36789"
Explanation: We can keep the number without any swaps.
Constraints:
1 <= num.length <= 3 * 104
num consists of only digits and does not contain leading zeros.
1 <= k <= 109
| Hard | [
"string",
"greedy",
"binary-indexed-tree",
"segment-tree"
] | [
"const minInteger = function (num, k) {\n const nums = num.split('')\n const len = nums.length\n const q = Array(10)\n .fill(null)\n .map(() => [])\n nums.forEach((n, i) => q[+n].push(i))\n const tree = new Fenwick(nums.length)\n for (let i = 1; i <= len; i++) tree.update(i, 1)\n let re = ''\n for (let i = 0; i < len; i++) {\n for (let j = 0; j <= 9; j++) {\n const idxArr = q[j]\n if (idxArr && idxArr.length) {\n const idx = idxArr[0]\n const num = tree.query(idx)\n if (num > k) continue\n k -= num\n idxArr.shift()\n tree.update(idx + 1, -1)\n re += j\n break\n }\n }\n }\n\n return re\n}\nclass Fenwick {\n constructor(n) {\n this.sums = new Array(n + 1).fill(0)\n }\n\n update(i, delta) {\n while (i < this.sums.length) {\n this.sums[i] += delta\n i += i & -i\n }\n }\n\n query(i) {\n let sum = 0\n while (i > 0) {\n sum += this.sums[i]\n i -= i & -i\n }\n return sum\n }\n}"
] |
|
1,507 | reformat-date | [
"Handle the conversions of day, month and year separately.",
"Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number."
] | /**
* @param {string} date
* @return {string}
*/
var reformatDate = function(date) {
}; | Given a date string in the form Day Month Year, where:
Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}.
Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.
Year is in the range [1900, 2100].
Convert the date string to the format YYYY-MM-DD, where:
YYYY denotes the 4 digit year.
MM denotes the 2 digit month.
DD denotes the 2 digit day.
Example 1:
Input: date = "20th Oct 2052"
Output: "2052-10-20"
Example 2:
Input: date = "6th Jun 1933"
Output: "1933-06-06"
Example 3:
Input: date = "26th May 1960"
Output: "1960-05-26"
Constraints:
The given dates are guaranteed to be valid, so no error handling is necessary.
| Easy | [
"string"
] | [
"const reformatDate = function(date) {\n const months = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n const map = new Map();\n for (let i = 0; i < months.length; ++i) {\n map.set(months[i], (i + 1 < 10 ? \"0\" : \"\") + (i+1)); \n }\n const parts = date.split(\" \"); \n const day = (parts[0].length == 3 ? \"0\" : \"\") + parts[0].slice(0, parts[0].length - 2);\n return parts[2] + \"-\" + map.get(parts[1]) + \"-\" + day; \n};"
] |
|
1,508 | range-sum-of-sorted-subarray-sums | [
"Compute all sums and save it in array.",
"Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7."
] | /**
* @param {number[]} nums
* @param {number} n
* @param {number} left
* @param {number} right
* @return {number}
*/
var rangeSum = function(nums, n, left, right) {
}; | You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.
Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.
Example 1:
Input: nums = [1,2,3,4], n = 4, left = 1, right = 5
Output: 13
Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.
Example 2:
Input: nums = [1,2,3,4], n = 4, left = 3, right = 4
Output: 6
Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
Example 3:
Input: nums = [1,2,3,4], n = 4, left = 1, right = 10
Output: 50
Constraints:
n == nums.length
1 <= nums.length <= 1000
1 <= nums[i] <= 100
1 <= left <= right <= n * (n + 1) / 2
| Medium | [
"array",
"two-pointers",
"binary-search",
"sorting"
] | null | [] |
1,509 | minimum-difference-between-largest-and-smallest-value-in-three-moves | [
"The minimum difference possible is obtained by removing three elements between the three smallest and three largest values in the array."
] | /**
* @param {number[]} nums
* @return {number}
*/
var minDifference = function(nums) {
}; | You are given an integer array nums.
In one move, you can choose one element of nums and change it to any value.
Return the minimum difference between the largest and smallest value of nums after performing at most three moves.
Example 1:
Input: nums = [5,3,2,4]
Output: 0
Explanation: We can make at most 3 moves.
In the first move, change 2 to 3. nums becomes [5,3,3,4].
In the second move, change 4 to 3. nums becomes [5,3,3,3].
In the third move, change 5 to 3. nums becomes [3,3,3,3].
After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.
Example 2:
Input: nums = [1,5,0,10,14]
Output: 1
Explanation: We can make at most 3 moves.
In the first move, change 5 to 0. nums becomes [1,0,0,10,14].
In the second move, change 10 to 0. nums becomes [1,0,0,0,14].
In the third move, change 14 to 1. nums becomes [1,0,0,0,1].
After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1.
It can be shown that there is no way to make the difference 0 in 3 moves.
Example 3:
Input: nums = [3,100,20]
Output: 0
Explanation: We can make at most 3 moves.
In the first move, change 100 to 7. nums becomes [3,7,20].
In the second move, change 20 to 7. nums becomes [3,7,7].
In the third move, change 3 to 7. nums becomes [7,7,7].
After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
| Medium | [
"array",
"greedy",
"sorting"
] | [
" const minDifference = function(nums) {\n let res = Infinity\n const n = nums.length\n if(n < 5) return 0\n nums.sort((a, b) => a - b)\n for(let i = 0; i < 4; i++) {\n res = Math.min(res, nums[n - 4 + i] - nums[i])\n }\n\n return res\n};"
] |
|
1,510 | stone-game-iv | [
"Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state."
] | /**
* @param {number} n
* @return {boolean}
*/
var winnerSquareGame = function(n) {
}; | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.
Example 1:
Input: n = 1
Output: true
Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.
Example 2:
Input: n = 2
Output: false
Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).
Example 3:
Input: n = 4
Output: true
Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).
Constraints:
1 <= n <= 105
| Hard | [
"math",
"dynamic-programming",
"game-theory"
] | [
"const winnerSquareGame = function(n) {\n const dp = new Array(n + 1).fill(0);\n for (let i = 1; i <= n; ++i) {\n for (let k = 1; k * k <= i; ++k) {\n if (!dp[i - k * k]) {\n dp[i] = true;\n break;\n }\n }\n }\n return dp[n];\n};"
] |
|
1,512 | number-of-good-pairs | [
"Count how many times each number appears. If a number appears n times, then n * (n – 1) // 2 good pairs can be made with this number."
] | /**
* @param {number[]} nums
* @return {number}
*/
var numIdenticalPairs = function(nums) {
}; | Given an array of integers nums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.
Example 3:
Input: nums = [1,2,3]
Output: 0
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
| Easy | [
"array",
"hash-table",
"math",
"counting"
] | [
"const numIdenticalPairs = function(nums) {\n let res = 0, count = Array(101).fill(0)\n for(let e of nums) {\n res += count[e]++\n }\n return res\n};"
] |
|
1,513 | number-of-substrings-with-only-1s | [
"Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2."
] | /**
* @param {string} s
* @return {number}
*/
var numSub = function(s) {
}; | Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Constraints:
1 <= s.length <= 105
s[i] is either '0' or '1'.
| Medium | [
"math",
"string"
] | null | [] |
1,514 | path-with-maximum-probability | [
"Multiplying probabilities will result in precision errors.",
"Take log probabilities to sum up numbers instead of multiplying them.",
"Use Dijkstra's algorithm to find the minimum path between the two nodes after negating all costs."
] | /**
* @param {number} n
* @param {number[][]} edges
* @param {number[]} succProb
* @param {number} start_node
* @param {number} end_node
* @return {number}
*/
var maxProbability = function(n, edges, succProb, start_node, end_node) {
}; | You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].
Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.
If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.
Example 1:
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
Output: 0.25000
Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.
Example 2:
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
Output: 0.30000
Example 3:
Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
Output: 0.00000
Explanation: There is no path between 0 and 2.
Constraints:
2 <= n <= 10^4
0 <= start, end < n
start != end
0 <= a, b < n
a != b
0 <= succProb.length == edges.length <= 2*10^4
0 <= succProb[i] <= 1
There is at most one edge between every two nodes.
| Medium | [
"array",
"graph",
"heap-priority-queue",
"shortest-path"
] | [
"const maxProbability = function (n, edges, succProb, start, end) {\n const g = {}\n for (let i = 0; i < edges.length; ++i) {\n const a = edges[i][0],\n b = edges[i][1]\n if (g[a] == null) g[a] = []\n if (g[b] == null) g[b] = []\n g[a].push([b, i])\n g[b].push([a, i])\n }\n const p = new Array(n).fill(0)\n p[start] = 1\n const pq = new PriorityQueue((a, b) => p[a] > p[b])\n pq.push(start)\n while (!pq.isEmpty()) {\n const cur = pq.pop()\n if (cur === end) {\n return p[end]\n }\n for (let a of g[cur] || []) {\n const neighbor = a[0],\n index = a[1]\n if (p[cur] * succProb[index] > p[neighbor]) {\n p[neighbor] = p[cur] * succProb[index]\n pq.push(neighbor)\n }\n }\n }\n return 0\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,515 | best-position-for-a-service-centre | [
"The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median.",
"Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle."
] | /**
* @param {number[][]} positions
* @return {number}
*/
var getMinDistSum = function(positions) {
}; | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum.
Given an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers.
In other words, you need to choose the position of the service center [xcentre, ycentre] such that the following formula is minimized:
Answers within 10-5 of the actual value will be accepted.
Example 1:
Input: positions = [[0,1],[1,0],[1,2],[2,1]]
Output: 4.00000
Explanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.
Example 2:
Input: positions = [[1,1],[3,3]]
Output: 2.82843
Explanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843
Constraints:
1 <= positions.length <= 50
positions[i].length == 2
0 <= xi, yi <= 100
| Hard | [
"math",
"geometry",
"randomized"
] | [
"const getMinDistSum = function(positions) {\n const n = positions.length\n let x = positions.reduce((ac, e) => ac + e[0], 0) / n\n let y = positions.reduce((ac, e) => ac + e[1], 0) / n\n \n const dirs = [[1,0],[-1,0],[0,1],[0,-1]]\n let res = fn(x, y, positions)\n let chg = 100\n while(chg > 1e-6) {\n let zoom = true\n for(let [dx, dy] of dirs) {\n const nx = x + dx * chg\n const ny = y + dy * chg\n const nRes = fn(nx, ny, positions)\n if(nRes < res) {\n res = nRes\n x = nx\n y = ny\n zoom = false\n break\n }\n }\n if(zoom) chg /= 2\n }\n return res\n};\n\nfunction fn(x, y, arr) {\n let res = 0\n const n = arr.length\n for(let i = 0; i < n; i++) {\n res += Math.sqrt((x - arr[i][0]) ** 2 + (y - arr[i][1]) ** 2)\n }\n return res\n}"
] |
|
1,518 | water-bottles | [
"Simulate the process until there are not enough empty bottles for even one full bottle of water."
] | /**
* @param {number} numBottles
* @param {number} numExchange
* @return {number}
*/
var numWaterBottles = function(numBottles, numExchange) {
}; | There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.
Example 1:
Input: numBottles = 9, numExchange = 3
Output: 13
Explanation: You can exchange 3 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 9 + 3 + 1 = 13.
Example 2:
Input: numBottles = 15, numExchange = 4
Output: 19
Explanation: You can exchange 4 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 15 + 3 + 1 = 19.
Constraints:
1 <= numBottles <= 100
2 <= numExchange <= 100
| Easy | [
"math",
"simulation"
] | null | [] |
1,519 | number-of-nodes-in-the-sub-tree-with-the-same-label | [
"Start traversing the tree and each node should return a vector to its parent node.",
"The vector should be of length 26 and have the count of all the labels in the sub-tree of this node."
] | /**
* @param {number} n
* @param {number[][]} edges
* @param {string} labels
* @return {number[]}
*/
var countSubTrees = function(n, edges, labels) {
}; | You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]).
The edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree.
Return an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i.
A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.
Example 1:
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"
Output: [2,1,1,1,1,1,1]
Explanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.
Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).
Example 2:
Input: n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"
Output: [4,2,1,1]
Explanation: The sub-tree of node 2 contains only node 2, so the answer is 1.
The sub-tree of node 3 contains only node 3, so the answer is 1.
The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.
The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.
Example 3:
Input: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"
Output: [3,2,1,1,1]
Constraints:
1 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
labels.length == n
labels is consisting of only of lowercase English letters.
| Medium | [
"hash-table",
"tree",
"depth-first-search",
"breadth-first-search",
"counting"
] | null | [] |
1,520 | maximum-number-of-non-overlapping-substrings | [
"Notice that it's impossible for any two valid substrings to overlap unless one is inside another.",
"We can start by finding the starting and ending index for each character.",
"From these indices, we can form the substrings by expanding each character's range if necessary (if another character exists in the range with smaller/larger starting/ending index).",
"Sort the valid substrings by length and greedily take those with the smallest length, discarding the ones that overlap those we took."
] | /**
* @param {string} s
* @return {string[]}
*/
var maxNumOfSubstrings = function(s) {
}; | Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions:
The substrings do not overlap, that is for any two substrings s[i..j] and s[x..y], either j < x or i > y is true.
A substring that contains a certain character c must also contain all occurrences of c.
Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.
Notice that you can return the substrings in any order.
Example 1:
Input: s = "adefaddaccc"
Output: ["e","f","ccc"]
Explanation: The following are all the possible substrings that meet the conditions:
[
"adefaddaccc"
"adefadda",
"ef",
"e",
"f",
"ccc",
]
If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda", we are left with "ccc" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef" since it can be split into two. Therefore, the optimal way is to choose ["e","f","ccc"] which gives us 3 substrings. No other solution of the same number of substrings exist.
Example 2:
Input: s = "abbaccd"
Output: ["d","bb","cc"]
Explanation: Notice that while the set of substrings ["d","abba","cc"] also has length 3, it's considered incorrect since it has larger total length.
Constraints:
1 <= s.length <= 105
s contains only lowercase English letters.
| Hard | [
"string",
"greedy"
] | null | [] |
1,521 | find-a-value-of-a-mysterious-function-closest-to-target | [
"If the and value of sub-array arr[i...j] is ≥ the and value of the sub-array arr[i...j+1].",
"For each index i using binary search or ternary search find the index j where |target - AND(arr[i...j])| is minimum, minimize this value with the global answer."
] | /**
* @param {number[]} arr
* @param {number} target
* @return {number}
*/
var closestToTarget = function(arr, target) {
}; |
Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible.
Return the minimum possible value of |func(arr, l, r) - target|.
Notice that func should be called with the values l and r where 0 <= l, r < arr.length.
Example 1:
Input: arr = [9,12,3,7,15], target = 5
Output: 2
Explanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.
Example 2:
Input: arr = [1000000,1000000,1000000], target = 1
Output: 999999
Explanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.
Example 3:
Input: arr = [1,2,4,8,16], target = 0
Output: 0
Constraints:
1 <= arr.length <= 105
1 <= arr[i] <= 106
0 <= target <= 107
| Hard | [
"array",
"binary-search",
"bit-manipulation",
"segment-tree"
] | [
"const closestToTarget = function (arr, target) {\n let res = Infinity\n let set = new Set()\n for (let i = 0; i < arr.length; i++) {\n const set2 = new Set()\n for (let j of set) {\n set2.add(j & arr[i])\n }\n set2.add(arr[i])\n for (let j of set2) {\n res = Math.min(res, Math.abs(j - target))\n }\n set = set2\n }\n return res\n}"
] |
|
1,523 | count-odd-numbers-in-an-interval-range | [
"If the range (high - low + 1) is even, the number of even and odd numbers in this range will be the same.",
"If the range (high - low + 1) is odd, the solution will depend on the parity of high and low."
] | /**
* @param {number} low
* @param {number} high
* @return {number}
*/
var countOdds = function(low, high) {
}; | Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).
Example 1:
Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].
Example 2:
Input: low = 8, high = 10
Output: 1
Explanation: The odd numbers between 8 and 10 are [9].
Constraints:
0 <= low <= high <= 10^9
| Easy | [
"math"
] | [
"const countOdds = function(low, high) {\n let res = 0\n \n const odd = num => num % 2 === 1\n if(odd(low)) res++\n \n const num = Math.floor( (high - low) / 2 )\n res += num\n \n if(high > low + 2 * num && odd(high)) res++\n \n return res\n};",
"const countOdds = function(low, high) {\n return ~~((high + 1) / 2) - (~~(low / 2))\n};"
] |
|
1,524 | number-of-sub-arrays-with-odd-sum | [
"Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ?",
"if the current accu sum is odd, we care only about previous even accu sums and vice versa."
] | /**
* @param {number[]} arr
* @return {number}
*/
var numOfSubarrays = function(arr) {
}; | Given an array of integers arr, return the number of subarrays with an odd sum.
Since the answer can be very large, return it modulo 109 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Constraints:
1 <= arr.length <= 105
1 <= arr[i] <= 100
| Medium | [
"array",
"math",
"dynamic-programming",
"prefix-sum"
] | [
"const numOfSubarrays = function(arr) {\n const n = arr.length, mod = 1e9 + 7\n let sum = 0, res = 0, oddCnt = 0, evenCnt = 0\n \n for(let i = 0; i < n; i++) {\n const cur = arr[i]\n sum += cur\n if(sum % 2 === 1) {\n res++\n res += evenCnt\n oddCnt++\n } else {\n res += oddCnt\n evenCnt++\n }\n }\n \n return res % mod\n};",
"const numOfSubarrays = function(arr) {\n const n = arr.length, mod = 1e9 + 7\n\n let oc = 0, ec = 1\n let sum = 0\n let res = 0\n for(let i = 0; i < n; i++) {\n sum += arr[i]\n if(sum % 2 === 1) {\n res += ec\n oc++\n } else {\n res += oc\n ec++\n }\n }\n \n return res % mod\n};"
] |
|
1,525 | number-of-good-ways-to-split-a-string | [
"Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index."
] | /**
* @param {string} s
* @return {number}
*/
var numSplits = function(s) {
}; | You are given a string s.
A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same.
Return the number of good splits you can make in s.
Example 1:
Input: s = "aacaba"
Output: 2
Explanation: There are 5 ways to split "aacaba" and 2 of them are good.
("a", "acaba") Left string and right string contains 1 and 3 different letters respectively.
("aa", "caba") Left string and right string contains 1 and 3 different letters respectively.
("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split).
("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split).
("aacab", "a") Left string and right string contains 3 and 1 different letters respectively.
Example 2:
Input: s = "abcd"
Output: 1
Explanation: Split the string as follows ("ab", "cd").
Constraints:
1 <= s.length <= 105
s consists of only lowercase English letters.
| Medium | [
"string",
"dynamic-programming",
"bit-manipulation"
] | [
"const numSplits = function(s) {\n const n = s.length\n const freq = new Map()\n const prefix = Array(26).fill(0)\n for(let i = 0; i < n; i++) {\n if(freq.get(s[i]) == null) freq.set(s[i], 0)\n freq.set(s[i], freq.get(s[i]) + 1)\n prefix[i] = freq.size\n }\n freq.clear()\n const suffix = Array(26).fill(0)\n for(let i = n - 1; i >= 0 ;i--) {\n if(freq.get(s[i]) == null) freq.set(s[i], 0)\n freq.set(s[i], freq.get(s[i]) + 1)\n suffix[i] = freq.size\n }\n // console.log(prefix, suffix)\n let res = 0\n for(let i = 1; i < n; i++) {\n if(prefix[i - 1] === suffix[i]) res++\n }\n \n return res\n};",
"const numSplits = function(s) {\n const arr = Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n for(let i = 0, len = s.length; i < len; i++) {\n arr[s.charCodeAt(i) - a]++\n }\n const cur = Array(26).fill(0)\n let res = 0\n for(let i = 0, len = s.length; i < len - 1; i++) {\n cur[s.charCodeAt(i) - a]++\n let tmp = false, clone = arr.slice()\n for(let j = 0; j < 26; j++) {\n clone[j] -= cur[j]\n }\n const curNum = cur.reduce((ac, e) => ac + (e > 0 ? 1 : 0), 0)\n const cloneNum = clone.reduce((ac, e) => ac + (e > 0 ? 1 : 0), 0)\n if(curNum === cloneNum) res++\n }\n \n return res\n};"
] |
|
1,526 | minimum-number-of-increments-on-subarrays-to-form-a-target-array | [
"For a given range of values in target, an optimal strategy is to increment the entire range by the minimum value. The minimum in a range could be obtained with Range minimum query or Segment trees algorithm."
] | /**
* @param {number[]} target
* @return {number}
*/
var minNumberOperations = function(target) {
}; | You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.
In one operation you can choose any subarray from initial and increment each value by one.
Return the minimum number of operations to form a target array from initial.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: target = [1,2,3,2,1]
Output: 3
Explanation: We need at least 3 operations to form the target array from the initial array.
[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).
[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).
[1,2,2,2,1] increment 1 at index 2.
[1,2,3,2,1] target array is formed.
Example 2:
Input: target = [3,1,1,2]
Output: 4
Explanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]
Example 3:
Input: target = [3,1,5,4,2]
Output: 7
Explanation: [0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].
Constraints:
1 <= target.length <= 105
1 <= target[i] <= 105
| Hard | [
"array",
"dynamic-programming",
"stack",
"greedy",
"monotonic-stack"
] | [
"const minNumberOperations = function(target) {\n let res = target[0]\n \n for(let i = 1; i < target.length; i++) {\n res += Math.max(0, target[i] - target[i - 1])\n }\n \n return res\n}",
"const minNumberOperations = function(target) {\n let totalOperations = target[0];\n for (let i = 1; i < target.length; ++i) {\n if (target[i] > target[i-1]) {\n totalOperations += target[i] - target[i-1];\n }\n }\n return totalOperations;\n};"
] |
|
1,528 | shuffle-string | [
"You can create an auxiliary string t of length n.",
"Assign t[indexes[i]] to s[i] for each i from 0 to n-1."
] | /**
* @param {string} s
* @param {number[]} indices
* @return {string}
*/
var restoreString = function(s, indices) {
}; | You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
Return the shuffled string.
Example 1:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.
Example 2:
Input: s = "abc", indices = [0,1,2]
Output: "abc"
Explanation: After shuffling, each character remains in its position.
Constraints:
s.length == indices.length == n
1 <= n <= 100
s consists of only lowercase English letters.
0 <= indices[i] < n
All values of indices are unique.
| Easy | [
"array",
"string"
] | [
"const restoreString = function(s, indices) {\n const n = s.length\n const arr = Array(n)\n for(let i = 0; i < n; i++) {\n arr[indices[i]] = s[i]\n }\n return arr.join('')\n};"
] |
|
1,529 | minimum-suffix-flips | [
"Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left."
] | /**
* @param {string} target
* @return {number}
*/
var minFlips = function(target) {
}; | You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target.
In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'.
Return the minimum number of operations needed to make s equal to target.
Example 1:
Input: target = "10111"
Output: 3
Explanation: Initially, s = "00000".
Choose index i = 2: "00000" -> "00111"
Choose index i = 0: "00111" -> "11000"
Choose index i = 1: "11000" -> "10111"
We need at least 3 flip operations to form target.
Example 2:
Input: target = "101"
Output: 3
Explanation: Initially, s = "000".
Choose index i = 0: "000" -> "111"
Choose index i = 1: "111" -> "100"
Choose index i = 2: "100" -> "101"
We need at least 3 flip operations to form target.
Example 3:
Input: target = "00000"
Output: 0
Explanation: We do not need any operations since the initial s already equals target.
Constraints:
n == target.length
1 <= n <= 105
target[i] is either '0' or '1'.
| Medium | [
"string",
"greedy"
] | [
"const minFlips = function (target) {\n const n = target.length\n let res = 0, flip = 0\n\n for(let i = 0; i < n; i++) {\n if(target[i] === '0' && flip % 2 === 0) continue\n if(target[i] === '1' && flip % 2 === 1) continue\n flip++\n res++\n }\n\n return res\n}"
] |
|
1,530 | number-of-good-leaf-nodes-pairs | [
"Start DFS from each leaf node. stop the DFS when the number of steps done > distance.",
"If you reach another leaf node within distance steps, add 1 to the answer.",
"Note that all pairs will be counted twice so divide the answer by 2."
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} distance
* @return {number}
*/
var countPairs = function(root, distance) {
}; | You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
Example 1:
Input: root = [1,2,3,null,4], distance = 3
Output: 1
Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.
Example 2:
Input: root = [1,2,3,4,5,6,7], distance = 3
Output: 2
Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.
Example 3:
Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3
Output: 1
Explanation: The only good pair is [2,5].
Constraints:
The number of nodes in the tree is in the range [1, 210].
1 <= Node.val <= 100
1 <= distance <= 10
| Medium | [
"tree",
"depth-first-search",
"binary-tree"
] | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const countPairs = function(root, distance) {\n let res = 0\n traverse(root)\n return res\n \n \n function traverse(node) {\n if(node == null) return []\n if(node.left == null && node.right == null) return [0]\n \n const left = traverse(node.left)\n const right = traverse(node.right)\n for(let i = 0; i < left.length; i++) {\n for(let j = 0; j < right.length; j++) {\n if(left[i] + right[j] + 2 <= distance) res++\n }\n }\n \n return [...left.map(e => e + 1), ...right.map(e => e + 1)]\n }\n};"
] |
1,531 | string-compression-ii | [
"Use dynamic programming.",
"The state of the DP can be the current index and the remaining characters to delete.",
"Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range."
] | /**
* @param {string} s
* @param {number} k
* @return {number}
*/
var getLengthOfOptimalCompression = function(s, k) {
}; | Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3".
Notice that in this problem, we are not adding '1' after single characters.
Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.
Find the minimum length of the run-length encoded version of s after deleting at most k characters.
Example 1:
Input: s = "aaabcccd", k = 2
Output: 4
Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.
Example 2:
Input: s = "aabbaa", k = 2
Output: 2
Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2.
Example 3:
Input: s = "aaaaaaaaaaa", k = 0
Output: 3
Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.
Constraints:
1 <= s.length <= 100
0 <= k <= s.length
s contains only lowercase English letters.
| Hard | [
"string",
"dynamic-programming"
] | [
"const getLengthOfOptimalCompression = function(s, k) {\n const m = new Map()\n function counter(start, last, lastCount, left) {\n if(left < 0) return Infinity\n if(start >= s.length) return 0\n let res\n const k = `${start}-${last}-${lastCount}-${left}`\n if(m.has(k)) return m.get(k)\n if(s[start] === last) {\n const incr = (lastCount === 1 || lastCount === 9 || lastCount === 99) ? 1 : 0\n res = incr + counter(start + 1, last, lastCount + 1, left)\n } else {\n const keepCounter = 1 + counter(start + 1, s[start], 1, left)\n const delCounter = counter(start + 1, last, lastCount, left - 1)\n res = Math.min(keepCounter, delCounter)\n }\n m.set(k, res)\n return res\n }\n return counter(0, '', 0, k)\n};",
"const getLengthOfOptimalCompression = function (s, k) {\n const n = s.length\n const dp = new Array(n + 1).fill(n).map((row) => new Array(k + 1).fill(n))\n dp[0][0] = 0\n\n for (let i = 1; i <= n; i++) {\n for (let j = 0; j <= k; j++) {\n let letterCount = 0\n let deletion = 0\n // keep s[i], compress same letters, remove different letters\n for (let l = i; l >= 1; l--) {\n if (s.charAt(l - 1) === s.charAt(i - 1)) letterCount++\n else deletion++\n // places = length needed to rep compressed letters.\n // 0 places for count = 1,0, 1 place = <10, 10-99 requires 2 places, 100+ requires 3\n let places = 0\n if (letterCount >= 100) places = 3\n else if (letterCount >= 10) places = 2\n else if (letterCount >= 2) places = 1\n if (j - deletion >= 0) {\n dp[i][j] = Math.min(dp[i][j], dp[l - 1][j - deletion] + 1 + places)\n }\n }\n // delete\n if (j > 0) {\n dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1])\n }\n }\n }\n return dp[n][k]\n}"
] |
|
1,534 | count-good-triplets | [
"Notice that the constraints are small enough for a brute force solution to pass.",
"Loop through all triplets, and count the ones that are good."
] | /**
* @param {number[]} arr
* @param {number} a
* @param {number} b
* @param {number} c
* @return {number}
*/
var countGoodTriplets = function(arr, a, b, c) {
}; | Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:
0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
Where |x| denotes the absolute value of x.
Return the number of good triplets.
Example 1:
Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
Output: 4
Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].
Example 2:
Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1
Output: 0
Explanation: No triplet satisfies all conditions.
Constraints:
3 <= arr.length <= 100
0 <= arr[i] <= 1000
0 <= a, b, c <= 1000
| Easy | [
"array",
"enumeration"
] | [
"const countGoodTriplets = function(arr, a, b, c) {\n const n = arr.length, { abs } = Math\n let res = 0\n \n for(let i = 0; i < n - 2; i++) {\n for(let j = i + 1; j < n - 1; j++) {\n if(abs(arr[i] - arr[j]) > a) continue\n for(let k = j + 1; k < n; k++) {\n if(abs(arr[j] - arr[k]) <= b && abs(arr[i] - arr[k]) <= c) res++\n }\n }\n }\n \n return res\n \n};"
] |
|
1,535 | find-the-winner-of-an-array-game | [
"If k ≥ arr.length return the max element of the array.",
"If k < arr.length simulate the game until a number wins k consecutive games."
] | /**
* @param {number[]} arr
* @param {number} k
* @return {number}
*/
var getWinner = function(arr, k) {
}; | Given an integer array arr of distinct integers and an integer k.
A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds.
Return the integer which will win the game.
It is guaranteed that there will be a winner of the game.
Example 1:
Input: arr = [2,1,3,5,4,6,7], k = 2
Output: 5
Explanation: Let's see the rounds of the game:
Round | arr | winner | win_count
1 | [2,1,3,5,4,6,7] | 2 | 1
2 | [2,3,5,4,6,7,1] | 3 | 1
3 | [3,5,4,6,7,1,2] | 5 | 1
4 | [5,4,6,7,1,2,3] | 5 | 2
So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.
Example 2:
Input: arr = [3,2,1], k = 10
Output: 3
Explanation: 3 will win the first 10 rounds consecutively.
Constraints:
2 <= arr.length <= 105
1 <= arr[i] <= 106
arr contains distinct integers.
1 <= k <= 109
| Medium | [
"array",
"simulation"
] | null | [] |
1,536 | minimum-swaps-to-arrange-a-binary-grid | [
"For each row of the grid calculate the most right 1 in the grid in the array maxRight.",
"To check if there exist answer, sort maxRight and check if maxRight[i] ≤ i for all possible i's.",
"If there exist an answer, simulate the swaps."
] | /**
* @param {number[][]} grid
* @return {number}
*/
var minSwaps = function(grid) {
}; | Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.
A grid is said to be valid if all the cells above the main diagonal are zeros.
Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.
The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).
Example 1:
Input: grid = [[0,0,1],[1,1,0],[1,0,0]]
Output: 3
Example 2:
Input: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]
Output: -1
Explanation: All rows are similar, swaps have no effect on the grid.
Example 3:
Input: grid = [[1,0,0],[1,1,0],[1,1,1]]
Output: 0
Constraints:
n == grid.length == grid[i].length
1 <= n <= 200
grid[i][j] is either 0 or 1
| Medium | [
"array",
"greedy",
"matrix"
] | null | [] |
1,537 | get-the-maximum-score | [
"Partition the array by common integers, and choose the path with larger sum with a DP technique."
] | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var maxSum = function(nums1, nums2) {
}; | You are given two sorted arrays of distinct integers nums1 and nums2.
A valid path is defined as follows:
Choose array nums1 or nums2 to traverse (from index-0).
Traverse the current array from left to right.
If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).
The score is defined as the sum of uniques values in a valid path.
Return the maximum score you can obtain of all possible valid paths. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]
Output: 30
Explanation: Valid paths:
[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)
[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)
The maximum is obtained with the path in green [2,4,6,8,10].
Example 2:
Input: nums1 = [1,3,5,7,9], nums2 = [3,5,100]
Output: 109
Explanation: Maximum sum is obtained with the path [1,3,5,100].
Example 3:
Input: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]
Output: 40
Explanation: There are no common elements between nums1 and nums2.
Maximum sum is obtained with the path [6,7,8,9,10].
Constraints:
1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[i] <= 107
nums1 and nums2 are strictly increasing.
| Hard | [
"array",
"two-pointers",
"dynamic-programming",
"greedy"
] | [
"const maxSum = function(nums1, nums2) {\n let i = 0, j = 0, n = nums1.length, m = nums2.length;\n let a = 0, b = 0, mod = 10 ** 9 + 7;\n while (i < n || j < m) {\n if (i < n && (j === m || nums1[i] < nums2[j])) {\n a += nums1[i++];\n } else if (j < m && (i === n || nums1[i] > nums2[j])) {\n b += nums2[j++];\n } else {\n a = b = Math.max(a, b) + nums1[i];\n i++; j++;\n }\n }\n return Math.max(a, b) % mod;\n};",
"const maxSum = function(nums1, nums2) {\n const len1 = nums1.length, len2 = nums2.length\n const mod = 10 ** 9 + 7\n const map = new Map()\n for(let i = 0; i < len1 - 1; i++) {\n if(!map.has(nums1[i])) map.set(nums1[i], [])\n map.get(nums1[i]).push(nums1[i + 1])\n }\n for(let j = 0; j < len2 - 1; j++) {\n if(!map.has(nums2[j])) map.set(nums2[j], [])\n map.get(nums2[j]).push(nums2[j + 1])\n }\n const memo = new Map()\n return Math.max(greedy(nums1[0], map, memo), greedy(nums2[0], map, memo)) % mod\n};\n\nfunction greedy(cur, map, memo) {\n if(memo.has(cur)) return memo.get(cur)\n if(!map.has(cur)) return cur\n let res = 0\n for(let next of map.get(cur)) {\n const tmp = greedy(next, map, memo)\n if(tmp > res) res = tmp\n }\n res += cur\n memo.set(cur, res)\n return res\n}"
] |
|
1,539 | kth-missing-positive-number | [
"Keep track of how many positive numbers are missing as you scan the array."
] | /**
* @param {number[]} arr
* @param {number} k
* @return {number}
*/
var findKthPositive = function(arr, k) {
}; | Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.
Return the kth positive integer that is missing from this array.
Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
Example 2:
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j] for 1 <= i < j <= arr.length
Follow up:
Could you solve this problem in less than O(n) complexity?
| Easy | [
"array",
"binary-search"
] | [
"const findKthPositive = function(arr, k) {\n let l = 0, r = arr.length, m;\n while (l < r) {\n m = (l + r) >> 1;\n if (arr[m] - 1 - m < k) l = m + 1;\n else r = m;\n }\n return l + k;\n};"
] |
|
1,540 | can-convert-string-in-k-moves | [
"Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times.",
"You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26."
] | /**
* @param {string} s
* @param {string} t
* @param {number} k
* @return {boolean}
*/
var canConvertString = function(s, t, k) {
}; | Given two strings s and t, your goal is to convert s into t in k moves or less.
During the ith (1 <= i <= k) move you can:
Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times.
Do nothing.
Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Shifting a character by i means applying the shift operations i times.
Remember that any index j can be picked at most once.
Return true if it's possible to convert s into t in no more than k moves, otherwise return false.
Example 1:
Input: s = "input", t = "ouput", k = 9
Output: true
Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.
Example 2:
Input: s = "abc", t = "bcd", k = 10
Output: false
Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.
Example 3:
Input: s = "aab", t = "bbb", k = 27
Output: true
Explanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.
Constraints:
1 <= s.length, t.length <= 10^5
0 <= k <= 10^9
s, t contain only lowercase English letters.
| Medium | [
"hash-table",
"string"
] | [
"const canConvertString = function(s, t, k) {\n if(s == null || t == null) return false\n const slen = s.length, tlen = t.length\n if(slen !== tlen) return false\n const count = Array(26).fill(0)\n for(let i = 0; i < slen; i++) {\n const scode = s.charCodeAt(i)\n const tcode = t.charCodeAt(i)\n const diff = (tcode - scode + 26) % 26;\n if (diff > 0 && diff + count[diff] * 26 > k) {\n return false;\n }\n count[diff]++;\n }\n return true\n};"
] |
|
1,541 | minimum-insertions-to-balance-a-parentheses-string | [
"Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'.",
"If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer."
] | /**
* @param {string} s
* @return {number}
*/
var minInsertions = function(s) {
}; | Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:
Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.
Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.
In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis.
For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not balanced.
You can insert the characters '(' and ')' at any position of the string to balance it if needed.
Return the minimum number of insertions needed to make s balanced.
Example 1:
Input: s = "(()))"
Output: 1
Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(())))" which is balanced.
Example 2:
Input: s = "())"
Output: 0
Explanation: The string is already balanced.
Example 3:
Input: s = "))())("
Output: 3
Explanation: Add '(' to match the first '))', Add '))' to match the last '('.
Constraints:
1 <= s.length <= 105
s consists of '(' and ')' only.
| Medium | [
"string",
"stack",
"greedy"
] | [
"const minInsertions = function(s) {\n let insert = 0, idx = 0, open = 0, len = s.length\n while(idx < len) {\n const ch = s[idx]\n if(ch === '(') {\n open++\n idx++\n } else {\n if(open > 0) {\n open--\n } else {\n insert++\n }\n if(idx < len - 1 && s[idx + 1] === ')') {\n idx += 2\n } else {\n insert++\n idx++\n }\n }\n }\n if(open) insert += open * 2\n return insert\n};",
"const minInsertions = function(s) {\n let res = 0, right = 0;\n for (let i = 0; i < s.length; ++i) {\n if (s.charAt(i) == '(') {\n if (right % 2 > 0) {\n right--;\n res++;\n }\n right += 2;\n } else {\n right--;\n if (right < 0) {\n right += 2;\n res++;\n }\n }\n }\n return right + res;\n};",
"const minInsertions = function(s) {\n let add = 0, req = 0 // number of parentheses added, number of closing parentheses required\n for(let ch of s) {\n if(ch === '(') {\n req += 2\n if(req % 2 === 1) {\n add++\n req--\n }\n } else {\n if(req === 0) {\n add++\n req++\n }else {\n req--\n }\n }\n }\n \n return add + req\n};"
] |
|
1,542 | find-longest-awesome-substring | [
"Given the character counts, under what conditions can a palindrome be formed ?",
"From left to right, use bitwise xor-operation to compute for any prefix the number of times modulo 2 of each digit. (mask ^= (1<<(s[i]-'0')).",
"Expected complexity is O(n*A) where A is the alphabet (10)."
] | /**
* @param {string} s
* @return {number}
*/
var longestAwesome = function(s) {
}; | You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome.
Return the length of the maximum length awesome substring of s.
Example 1:
Input: s = "3242415"
Output: 5
Explanation: "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps.
Example 2:
Input: s = "12345678"
Output: 1
Example 3:
Input: s = "213123"
Output: 6
Explanation: "213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps.
Constraints:
1 <= s.length <= 105
s consists only of digits.
| Hard | [
"hash-table",
"string",
"bit-manipulation"
] | [
"const longestAwesome = function (s) {\n const dp = new Array(1024).fill(s.length)\n let res = 0,\n mask = 0\n dp[0] = -1\n for (let i = 0; i < s.length; ++i) {\n mask ^= 1 << +s.charAt(i)\n res = Math.max(res, i - dp[mask])\n for (let j = 0; j <= 9; ++j) res = Math.max(res, i - dp[mask ^ (1 << j)])\n dp[mask] = Math.min(dp[mask], i)\n }\n return res\n}",
"const longestAwesome = function(s) {\n const n = s.length, { max, min } = Math\n const dp = Array(2 ** 10).fill(n)\n let res = 0, mask = 0\n dp[0] = -1\n for(let i = 0; i < n; i++) {\n mask ^= (1 << parseInt(s[i]))\n res = max(res, i - dp[mask])\n for(let j = 0; j <= 9; j++) {\n const tmp = mask ^ (1 << j)\n res = max(res, i - dp[tmp])\n }\n dp[mask] = min(i, dp[mask])\n }\n \n return res\n};"
] |
|
1,544 | make-the-string-great | [
"The order you choose 2 characters to remove doesn't matter.",
"Keep applying the mentioned step to s till the length of the string is not changed."
] | /**
* @param {string} s
* @return {string}
*/
var makeGood = function(s) {
}; | Given a string s of lower and upper case English letters.
A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:
0 <= i <= s.length - 2
s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
Notice that an empty string is also good.
Example 1:
Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
Example 2:
Input: s = "abBAcC"
Output: ""
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""
Example 3:
Input: s = "s"
Output: "s"
Constraints:
1 <= s.length <= 100
s contains only lower and upper case English letters.
| Easy | [
"string",
"stack"
] | null | [] |
1,545 | find-kth-bit-in-nth-binary-string | [
"Since n is small, we can simply simulate the process of constructing S1 to Sn."
] | /**
* @param {number} n
* @param {number} k
* @return {character}
*/
var findKthBit = function(n, k) {
}; | Given two positive integers n and k, the binary string Sn is formed as follows:
S1 = "0"
Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i > 1
Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).
For example, the first four strings in the above sequence are:
S1 = "0"
S2 = "011"
S3 = "0111001"
S4 = "011100110110001"
Return the kth bit in Sn. It is guaranteed that k is valid for the given n.
Example 1:
Input: n = 3, k = 1
Output: "0"
Explanation: S3 is "0111001".
The 1st bit is "0".
Example 2:
Input: n = 4, k = 11
Output: "1"
Explanation: S4 is "011100110110001".
The 11th bit is "1".
Constraints:
1 <= n <= 20
1 <= k <= 2n - 1
| Medium | [
"string",
"recursion"
] | null | [] |
1,546 | maximum-number-of-non-overlapping-subarrays-with-sum-equals-target | [
"Keep track of prefix sums to quickly look up what subarray that sums \"target\" can be formed at each step of scanning the input array.",
"It can be proved that greedily forming valid subarrays as soon as one is found is optimal."
] | /**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var maxNonOverlapping = function(nums, target) {
}; | Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.
Example 1:
Input: nums = [1,1,1,1,1], target = 2
Output: 2
Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).
Example 2:
Input: nums = [-1,3,5,1,4,2,-9], target = 6
Output: 2
Explanation: There are 3 subarrays with sum equal to 6.
([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
0 <= target <= 106
| Medium | [
"array",
"hash-table",
"greedy",
"prefix-sum"
] | [
"const maxNonOverlapping = function(nums, target) {\n if(nums == null || nums.length === 0) return 0\n let sum = 0, res = 0\n const n = nums.length\n const m = {0: 0}\n \n for(let i = 0; i < n; i++) {\n sum += nums[i]\n if(m[sum - target] != null) {\n res = Math.max(res, m[sum - target] + 1)\n }\n m[sum] = res\n }\n return res\n};"
] |
|
1,547 | minimum-cost-to-cut-a-stick | [
"Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j.",
"When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them."
] | /**
* @param {number} n
* @param {number[]} cuts
* @return {number}
*/
var minCost = function(n, cuts) {
}; | Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows:
Given an integer array cuts where cuts[i] denotes a position you should perform a cut at.
You should perform the cuts in order, you can change the order of the cuts as you wish.
The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.
Return the minimum total cost of the cuts.
Example 1:
Input: n = 7, cuts = [1,3,4,5]
Output: 16
Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:
The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.
Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).
Example 2:
Input: n = 9, cuts = [5,6,1,4,2]
Output: 22
Explanation: If you try the given cuts ordering the cost will be 25.
There are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.
Constraints:
2 <= n <= 106
1 <= cuts.length <= min(n - 1, 100)
1 <= cuts[i] <= n - 1
All the integers in cuts array are distinct.
| Hard | [
"array",
"dynamic-programming",
"sorting"
] | [
"const minCost = function(n, cuts) {\n const x = 100 + 2\n const dp = Array.from({ length: x }, () => Array(x).fill(0))\n cuts.push(0, n)\n cuts.sort((a, b) => a - b)\n const res = dfs(0, cuts.length - 1)\n return res\n function dfs(i, j) {\n if(j - i <= 1) return 0\n if(!dp[i][j]) {\n dp[i][j] = Number.MAX_VALUE\n for(let k = i + 1; k < j; k++) {\n dp[i][j] = Math.min(dp[i][j], cuts[j] - cuts[i] + dfs(i, k) + dfs(k, j))\n }\n }\n return dp[i][j]\n }\n};",
"const minCost = function (n, cuts) {\n cuts.push(0, n)\n cuts.sort((a, b) => a - b)\n const N = cuts.length,\n dp = Array.from({ length: N }, () => Array(N).fill(Infinity))\n for(let i = 1; i < N; i++) dp[i - 1][i] = 0\n for(let i = 2; i < N; i++) dp[i - 2][i] = cuts[i] - cuts[i - 2]\n for (let l = 4; l <= N; l++) {\n for (let i = 0; i <= N - l; i++) {\n const j = i + l - 1\n for (let k = i + 1; k < j; k++) {\n dp[i][j] = Math.min(dp[i][j], cuts[j] - cuts[i] + dp[i][k] + dp[k][j])\n }\n }\n }\n return dp[0][N - 1]\n}"
] |
|
1,550 | three-consecutive-odds | [
"Check every three consecutive numbers in the array for parity."
] | /**
* @param {number[]} arr
* @return {boolean}
*/
var threeConsecutiveOdds = function(arr) {
}; | Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.
Example 1:
Input: arr = [2,6,4,1]
Output: false
Explanation: There are no three consecutive odds.
Example 2:
Input: arr = [1,2,34,3,4,5,7,23,12]
Output: true
Explanation: [5,7,23] are three consecutive odds.
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
| Easy | [
"array"
] | [
"const threeConsecutiveOdds = function(arr) {\n for(let i = 1, n = arr.length; i < n - 1; i++) {\n if(arr[i] & 1 === 1 && arr[i - 1] & 1 === 1 && arr[i + 1] & 1 === 1) return true\n }\n return false\n};"
] |
|
1,551 | minimum-operations-to-make-array-equal | [
"Build the array arr using the given formula, define target = sum(arr) / n",
"What is the number of operations needed to convert arr so that all elements equal target ?"
] | /**
* @param {number} n
* @return {number}
*/
var minOperations = function(n) {
}; | You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n).
In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.
Given an integer n, the length of the array, return the minimum number of operations needed to make all the elements of arr equal.
Example 1:
Input: n = 3
Output: 2
Explanation: arr = [1, 3, 5]
First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]
In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].
Example 2:
Input: n = 6
Output: 9
Constraints:
1 <= n <= 104
| Medium | [
"math"
] | [
"var minOperations = function(n) {\n let l = 1, r = 2 * (n - 1) + 1\n \n // [1, 3]\n // [1, 3, 5, 7]\n \n // [1]\n // [1, 3, 5]\n // [1, 3, 5, 7, 9]\n const target = l + (r - l) / 2\n let res = 0\n const num = ~~((n + 1) / 2)\n for(let i = 1; i <= num; i++) {\n res += target - (2 * (i -1) + 1)\n }\n \n return res\n};"
] |
|
1,552 | magnetic-force-between-two-balls | [
"If you can place balls such that the answer is x then you can do it for y where y < x.",
"Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x.",
"Binary search on the answer and greedily see if it is possible."
] | /**
* @param {number[]} position
* @param {number} m
* @return {number}
*/
var maxDistance = function(position, m) {
}; | In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 105
1 <= position[i] <= 109
All integers in position are distinct.
2 <= m <= position.length
| Medium | [
"array",
"binary-search",
"sorting"
] | [
"const maxDistance = function(position, m) {\n position.sort((a, b) => a - b)\n const n = position.length\n let l = Infinity, r = 1\n for (let i = 1; i < n; i++) {\n if (position[i] - position[i - 1] < l) l = position[i] - position[i - 1]\n }\n r = position[n - 1] - position[0]\n while(l < r) {\n const mid = r - Math.floor((r - l) / 2)\n if(valid(mid)) l = mid\n else r = mid - 1\n }\n return l\n\n function valid(mid) {\n let res = 1, cur = 0\n for (let i = 1; i < n; i++) {\n const delta = position[i] - position[i - 1]\n cur += delta\n if (cur >= mid) {\n res++\n cur = 0\n }\n if(res === m) return true\n }\n return false\n }\n};"
] |
|
1,553 | minimum-number-of-days-to-eat-n-oranges | [
"In each step, choose between 2 options:\r\nminOranges = 1 + min( (n%2) + f(n/2), (n%3) + f(n/3) )\r\nwhere f(n) is the minimum number of days to eat n oranges."
] | /**
* @param {number} n
* @return {number}
*/
var minDays = function(n) {
}; | There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:
Eat one orange.
If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.
If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges.
You can only choose one of the actions per day.
Given the integer n, return the minimum number of days to eat n oranges.
Example 1:
Input: n = 10
Output: 4
Explanation: You have 10 oranges.
Day 1: Eat 1 orange, 10 - 1 = 9.
Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)
Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1.
Day 4: Eat the last orange 1 - 1 = 0.
You need at least 4 days to eat the 10 oranges.
Example 2:
Input: n = 6
Output: 3
Explanation: You have 6 oranges.
Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).
Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)
Day 3: Eat the last orange 1 - 1 = 0.
You need at least 3 days to eat the 6 oranges.
Constraints:
1 <= n <= 2 * 109
| Hard | [
"dynamic-programming",
"memoization"
] | [
"const minDays = function (n, dp = {}) {\n if (n <= 1) return n\n if (dp[n] == null)\n dp[n] =\n 1 +\n Math.min(\n (n % 2) + minDays((n / 2) >> 0, dp),\n (n % 3) + minDays((n / 3) >> 0, dp)\n )\n return dp[n]\n}"
] |
|
1,556 | thousand-separator | [
"Scan from the back of the integer and use dots to connect blocks with length 3 except the last block."
] | /**
* @param {number} n
* @return {string}
*/
var thousandSeparator = function(n) {
}; | Given an integer n, add a dot (".") as the thousands separator and return it in string format.
Example 1:
Input: n = 987
Output: "987"
Example 2:
Input: n = 1234
Output: "1.234"
Constraints:
0 <= n <= 231 - 1
| Easy | [
"string"
] | null | [] |
1,557 | minimum-number-of-vertices-to-reach-all-nodes | [
"A node that does not have any incoming edge can only be reached by itself.",
"Any other node with incoming edges can be reached from some other node.",
"We only have to count the number of nodes with zero incoming edges."
] | /**
* @param {number} n
* @param {number[][]} edges
* @return {number[]}
*/
var findSmallestSetOfVertices = function(n, edges) {
}; | Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi.
Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
Example 1:
Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]
Output: [0,3]
Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].
Example 2:
Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]
Output: [0,2,3]
Explanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
Constraints:
2 <= n <= 10^5
1 <= edges.length <= min(10^5, n * (n - 1) / 2)
edges[i].length == 2
0 <= fromi, toi < n
All pairs (fromi, toi) are distinct.
| Medium | [
"graph"
] | [
"var findSmallestSetOfVertices = function(n, edges) {\n const indegree = Array(n).fill(0)\n for(const [from, to] of edges) {\n indegree[to]++\n }\n let res = []\n for(let i = 0; i <n; i++) {\n const e = indegree[i]\n if(e === 0) res.push(i)\n }\n \n return res\n};"
] |
|
1,558 | minimum-numbers-of-function-calls-to-make-target-array | [
"Work backwards: try to go from nums to arr.",
"You should try to divide by 2 as much as possible, but you can only divide by 2 if everything is even."
] | /**
* @param {number[]} nums
* @return {number}
*/
var minOperations = function(nums) {
}; | You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function:
You want to use the modify function to convert arr to nums using the minimum number of calls.
Return the minimum number of function calls to make nums from arr.
The test cases are generated so that the answer fits in a 32-bit signed integer.
Example 1:
Input: nums = [1,5]
Output: 5
Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).
Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).
Increment by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations).
Total of operations: 1 + 2 + 2 = 5.
Example 2:
Input: nums = [2,2]
Output: 3
Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).
Double all the elements: [1, 1] -> [2, 2] (1 operation).
Total of operations: 2 + 1 = 3.
Example 3:
Input: nums = [4,2,5]
Output: 6
Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
| Medium | [
"array",
"greedy",
"bit-manipulation"
] | null | [] |
1,559 | detect-cycles-in-2d-grid | [
"Keep track of the parent (previous position) to avoid considering an invalid path.",
"Use DFS or BFS and keep track of visited cells to see if there is a cycle."
] | /**
* @param {character[][]} grid
* @return {boolean}
*/
var containsCycle = function(grid) {
}; | Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.
A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.
Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.
Return true if any cycle of the same value exists in grid, otherwise, return false.
Example 1:
Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]
Output: true
Explanation: There are two valid cycles shown in different colors in the image below:
Example 2:
Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]
Output: true
Explanation: There is only one valid cycle highlighted in the image below:
Example 3:
Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]]
Output: false
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 500
grid consists only of lowercase English letters.
| Medium | [
"array",
"depth-first-search",
"breadth-first-search",
"union-find",
"matrix"
] | [
"const containsCycle = function (grid) {\n const dirs = [\n [1, 0],\n [-1, 0],\n [0, 1],\n [0, -1],\n ]\n const rows = grid.length\n const cols = (grid[0] || []).length\n const vis = Array.from({ length: rows }, () => Array(cols).fill(false))\n let res = false\n const dfs = (i, j, prevR, prevC, char) => {\n vis[i][j] = true\n for (let d of dirs) {\n const r = i + d[0]\n const c = j + d[1]\n if (r >= 0 && r < rows && c >= 0 && c < cols) {\n if (!(r == prevR && c === prevC)) {\n if (grid[r][c] === char) {\n if (!vis[r][c]) {\n if (dfs(r, c, i, j, char)) return true\n } else {\n if (prevR !== -1 && prevC !== -1) return true\n }\n }\n }\n }\n }\n return false\n }\n\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n if (!vis[i][j]) {\n res |= dfs(i, j, -1, -1, grid[i][j])\n }\n if (res) return true\n }\n }\n return res\n}",
"const containsCycle = function (grid) {\n const wholePath = (r, c, letter, component, last = [-1, -1]) => {\n const dirs = [\n [0, -1],\n [0, 1],\n [-1, 0],\n [1, 0],\n ]\n const tmp = grid[r][c]\n grid[r][c] = component\n const nextSteps = dirs\n .map((x) => [x[0] + r, x[1] + c])\n .filter(\n (x) =>\n x[0] >= 0 && x[0] < grid.length && x[1] >= 0 && x[1] < grid[0].length\n )\n for (let step of nextSteps) {\n if (step[0] === last[0] && last[1] === step[1]) {\n continue\n }\n if (grid[step[0]][step[1]] === component) {\n return true\n }\n if (grid[step[0]][step[1]] === letter) {\n let outcome = wholePath(step[0], step[1], letter, component, [r, c])\n if (outcome) {\n return true\n }\n }\n }\n return false\n }\n\n let component = 1\n for (let r = 0; r < grid.length; r++) {\n for (let c = 0; c < grid[0].length; c++) {\n const letter = grid[r][c]\n if (typeof letter === 'string') {\n grid[r][c] = component\n const outcome = wholePath(r, c, letter, component)\n if (outcome) {\n return true\n }\n component++\n }\n }\n }\n return false\n}"
] |
|
1,560 | most-visited-sector-in-a-circular-track | [
"For each round increment the visits of the sectors visited during the marathon with 1.",
"Determine the max number of visits, and return any sector visited the max number of visits."
] | /**
* @param {number} n
* @param {number[]} rounds
* @return {number[]}
*/
var mostVisited = function(n, rounds) {
}; | Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1]
Return an array of the most visited sectors sorted in ascending order.
Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).
Example 1:
Input: n = 4, rounds = [1,3,1,2]
Output: [1,2]
Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows:
1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)
We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.
Example 2:
Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2]
Output: [2]
Example 3:
Input: n = 7, rounds = [1,3,5,7]
Output: [1,2,3,4,5,6,7]
Constraints:
2 <= n <= 100
1 <= m <= 100
rounds.length == m + 1
1 <= rounds[i] <= n
rounds[i] != rounds[i + 1] for 0 <= i < m
| Easy | [
"array",
"simulation"
] | [
"const mostVisited = function(n, rounds) {\n const arr = Array(n + 1).fill(0)\n for(let i = 1, m = rounds.length; i < m; i++) {\n let start = rounds[i - 1], end = rounds[i]\n\n if(i == 1) arr[start]++\n while(start !== end) {\n start += 1\n if (start === n + 1) start = 1\n arr[start]++\n }\n }\n const max = Math.max(...arr)\n const res = []\n for(let i = 1; i <= n; i++) {\n if(arr[i] === max) res.push(i)\n }\n return res\n};"
] |
|
1,561 | maximum-number-of-coins-you-can-get | [
"Which pile of coins will you never be able to pick up?",
"Bob is forced to take the last pile of coins, no matter what it is. Which pile should you give to him?"
] | /**
* @param {number[]} piles
* @return {number}
*/
var maxCoins = function(piles) {
}; | There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:
In each step, you will choose any 3 piles of coins (not necessarily consecutive).
Of your choice, Alice will pick the pile with the maximum number of coins.
You will pick the next pile with the maximum number of coins.
Your friend Bob will pick the last pile.
Repeat until there are no more piles of coins.
Given an array of integers piles where piles[i] is the number of coins in the ith pile.
Return the maximum number of coins that you can have.
Example 1:
Input: piles = [2,4,1,2,7,8]
Output: 9
Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one.
Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one.
The maximum number of coins which you can have are: 7 + 2 = 9.
On the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal.
Example 2:
Input: piles = [2,4,5]
Output: 4
Example 3:
Input: piles = [9,8,7,6,5,1,2,3,4]
Output: 18
Constraints:
3 <= piles.length <= 105
piles.length % 3 == 0
1 <= piles[i] <= 104
| Medium | [
"array",
"math",
"greedy",
"sorting",
"game-theory"
] | [
"const maxCoins = function(piles) {\n piles.sort((a, b) => a - b)\n let coins = 0, n = piles.length\n for(let j = 0, i = n - 2, hi = Math.floor(n / 3); j < hi; j++, i -= 2) {\n coins += piles[i]\n }\n \n return coins\n};"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.