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,961 | check-if-string-is-a-prefix-of-array | [
"There are only words.length prefix strings.",
"Create all of them and see if s is one of them."
] | /**
* @param {string} s
* @param {string[]} words
* @return {boolean}
*/
var isPrefixString = function(s, words) {
}; | Given a string s and an array of strings words, determine whether s is a prefix string of words.
A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length.
Return true if s is a prefix string of words, or false otherwise.
Example 1:
Input: s = "iloveleetcode", words = ["i","love","leetcode","apples"]
Output: true
Explanation:
s can be made by concatenating "i", "love", and "leetcode" together.
Example 2:
Input: s = "iloveleetcode", words = ["apples","i","love","leetcode"]
Output: false
Explanation:
It is impossible to make s using a prefix of arr.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 20
1 <= s.length <= 1000
words[i] and s consist of only lowercase English letters.
| Easy | [
"array",
"string"
] | [
"const isPrefixString = function(s, words) {\n let tmp = ''\n for(let w of words) {\n tmp += w\n if(tmp === s) return true\n }\n return false\n};"
] |
|
1,962 | remove-stones-to-minimize-the-total | [
"Choose the pile with the maximum number of stones each time.",
"Use a data structure that helps you find the mentioned pile each time efficiently.",
"One such data structure is a Priority Queue."
] | /**
* @param {number[]} piles
* @param {number} k
* @return {number}
*/
var minStoneSum = function(piles, k) {
}; | You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:
Choose any piles[i] and remove floor(piles[i] / 2) stones from it.
Notice that you can apply the operation on the same pile more than once.
Return the minimum possible total number of stones remaining after applying the k operations.
floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).
Example 1:
Input: piles = [5,4,9], k = 2
Output: 12
Explanation: Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are [5,4,5].
- Apply the operation on pile 0. The resulting piles are [3,4,5].
The total number of stones in [3,4,5] is 12.
Example 2:
Input: piles = [4,3,6,7], k = 3
Output: 12
Explanation: Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are [4,3,3,7].
- Apply the operation on pile 3. The resulting piles are [4,3,3,4].
- Apply the operation on pile 0. The resulting piles are [2,3,3,4].
The total number of stones in [2,3,3,4] is 12.
Constraints:
1 <= piles.length <= 105
1 <= piles[i] <= 104
1 <= k <= 105
| Medium | [
"array",
"heap-priority-queue"
] | [
"const minStoneSum = function(piles, k) {\n const pq = new PriorityQueue((a, b) => a > b)\n for(let e of piles) pq.push(e)\n while(k > 0) {\n const tmp = pq.pop()\n const e = tmp - (~~(tmp / 2))\n pq.push(e)\n k--\n }\n let res = 0\n while(!pq.isEmpty()) {\n res += pq.pop()\n }\n return res\n};\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}"
] |
|
1,963 | minimum-number-of-swaps-to-make-the-string-balanced | [
"Iterate over the string and keep track of the number of opening and closing brackets on each step.",
"If the number of closing brackets is ever larger, you need to make a swap.",
"Swap it with the opening bracket closest to the end of s."
] | /**
* @param {string} s
* @return {number}
*/
var minSwaps = function(s) {
}; | You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.
A string is called balanced if and only if:
It is the empty string, or
It can be written as AB, where both A and B are balanced strings, or
It can be written as [C], where C is a balanced string.
You may swap the brackets at any two indices any number of times.
Return the minimum number of swaps to make s balanced.
Example 1:
Input: s = "][]["
Output: 1
Explanation: You can make the string balanced by swapping index 0 with index 3.
The resulting string is "[[]]".
Example 2:
Input: s = "]]][[["
Output: 2
Explanation: You can do the following to make the string balanced:
- Swap index 0 with index 4. s = "[]][][".
- Swap index 1 with index 5. s = "[[][]]".
The resulting string is "[[][]]".
Example 3:
Input: s = "[]"
Output: 0
Explanation: The string is already balanced.
Constraints:
n == s.length
2 <= n <= 106
n is even.
s[i] is either '[' or ']'.
The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.
| Medium | [
"two-pointers",
"string",
"stack",
"greedy"
] | [
"const minSwaps = function(s) {\n const stk = []\n for (let e of s) {\n if(e === '[') stk.push(e)\n else {\n if(stk.length) {\n stk.pop()\n } else stk.push(e)\n }\n }\n return Math.ceil(stk.length / 2)\n};",
"const minSwaps = function(s) {\n const stack = []\n let num = 0\n for(let e of s) {\n if(e === '[') {\n stack.push(e)\n num++\n }\n if(e === ']') {\n if(stack[stack.length - 1] === '[') {\n stack.pop()\n num--\n }\n }\n }\n // console.log(num)\n return Math.ceil(num / 2)\n};",
"const minSwaps = function(s) {\n let num = 0\n for(let e of s) {\n if(e === '[') {\n num++\n }\n if(e === ']') {\n if(num > 0) {\n num--\n }\n }\n }\n return Math.ceil(num / 2)\n};"
] |
|
1,964 | find-the-longest-valid-obstacle-course-at-each-position | [
"Can you keep track of the minimum height for each obstacle course length?",
"You can use binary search to find the longest previous obstacle course length that satisfies the conditions."
] | /**
* @param {number[]} obstacles
* @return {number[]}
*/
var longestObstacleCourseAtEachPosition = function(obstacles) {
}; | You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle.
For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that:
You choose any number of obstacles between 0 and i inclusive.
You must include the ith obstacle in the course.
You must put the chosen obstacles in the same order as they appear in obstacles.
Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it.
Return an array ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above.
Example 1:
Input: obstacles = [1,2,3,2]
Output: [1,2,3,3]
Explanation: The longest valid obstacle course at each position is:
- i = 0: [1], [1] has length 1.
- i = 1: [1,2], [1,2] has length 2.
- i = 2: [1,2,3], [1,2,3] has length 3.
- i = 3: [1,2,3,2], [1,2,2] has length 3.
Example 2:
Input: obstacles = [2,2,1]
Output: [1,2,1]
Explanation: The longest valid obstacle course at each position is:
- i = 0: [2], [2] has length 1.
- i = 1: [2,2], [2,2] has length 2.
- i = 2: [2,2,1], [1] has length 1.
Example 3:
Input: obstacles = [3,1,5,6,4,2]
Output: [1,1,2,3,2,2]
Explanation: The longest valid obstacle course at each position is:
- i = 0: [3], [3] has length 1.
- i = 1: [3,1], [1] has length 1.
- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid.
- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid.
- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid.
- i = 5: [3,1,5,6,4,2], [1,2] has length 2.
Constraints:
n == obstacles.length
1 <= n <= 105
1 <= obstacles[i] <= 107
| Hard | [
"array",
"binary-search",
"binary-indexed-tree"
] | [
"const longestObstacleCourseAtEachPosition = function(obstacles) {\n const n = obstacles.length, res = [], stk = []\n for (let i = 0; i < n; i++) {\n const cur = obstacles[i]\n let idx = chk(cur)\n if (idx === stk.length) {\n stk.push(cur)\n } else {\n stk[idx] = cur\n }\n res.push(++idx)\n }\n\n return res\n\n function chk(val) {\n let l = 0, r = stk.length\n while(l < r) {\n const mid = ~~((l + r) / 2)\n if(stk[mid] <= val) l = mid + 1\n else r = mid\n }\n return l\n }\n};",
"const longestObstacleCourseAtEachPosition = function(obstacles) {\n const n = obstacles.length\n const stack = [], res = []\n let len = 0\n \n for(let i = 0; i < n; i++) {\n const cur = obstacles[i]\n const idx = chk(cur)\n if(idx === len) {\n stack.push(cur)\n len++\n res.push(len)\n }else {\n stack[idx] = cur\n res.push(idx + 1)\n }\n }\n\n return res\n \n function chk(x) {\n if(len && stack[len - 1] <= x) return len\n let l = 0, r = len - 1\n while(l < r) {\n const mid = ~~((l + r) / 2)\n if(stack[mid] <= x) {\n l = mid + 1\n } else {\n r = mid\n }\n }\n return l\n }\n};",
"const longestObstacleCourseAtEachPosition = function(obstacles) {\n const n = obstacles.length\n const stack = [], res = Array(n).fill(0)\n let m = 0\n let j = 0;\n for (let x of obstacles) {\n let i = chk(x);\n if (i == m) {\n ++m;\n stack.push(x);\n } else {\n stack[i] = x;\n }\n res[j++] = i + 1;\n }\n return res;\n function chk(x) {\n if (m && stack[m - 1] <= x) return m;\n let l = 0, r = m - 1;\n while (l < r) {\n let m = (l + r) >> 1;\n if (stack[m] > x) {\n r = m;\n } else {\n l = m + 1;\n }\n }\n return l;\n }\n};"
] |
|
1,967 | number-of-strings-that-appear-as-substrings-in-word | [
"Deal with each of the patterns individually.",
"Use the built-in function in the language you are using to find if the pattern exists as a substring in <code>word</code>."
] | /**
* @param {string[]} patterns
* @param {string} word
* @return {number}
*/
var numOfStrings = function(patterns, word) {
}; | Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: patterns = ["a","abc","bc","d"], word = "abc"
Output: 3
Explanation:
- "a" appears as a substring in "abc".
- "abc" appears as a substring in "abc".
- "bc" appears as a substring in "abc".
- "d" does not appear as a substring in "abc".
3 of the strings in patterns appear as a substring in word.
Example 2:
Input: patterns = ["a","b","c"], word = "aaaaabbbbb"
Output: 2
Explanation:
- "a" appears as a substring in "aaaaabbbbb".
- "b" appears as a substring in "aaaaabbbbb".
- "c" does not appear as a substring in "aaaaabbbbb".
2 of the strings in patterns appear as a substring in word.
Example 3:
Input: patterns = ["a","a","a"], word = "ab"
Output: 3
Explanation: Each of the patterns appears as a substring in word "ab".
Constraints:
1 <= patterns.length <= 100
1 <= patterns[i].length <= 100
1 <= word.length <= 100
patterns[i] and word consist of lowercase English letters.
| Easy | [
"string"
] | null | [] |
1,968 | array-with-elements-not-equal-to-average-of-neighbors | [
"A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number.",
"We can put numbers smaller than the median on odd indices and the rest on even indices."
] | /**
* @param {number[]} nums
* @return {number[]}
*/
var rearrangeArray = function(nums) {
}; | You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.
More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i].
Return any rearrangement of nums that meets the requirements.
Example 1:
Input: nums = [1,2,3,4,5]
Output: [1,2,4,5,3]
Explanation:
When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
Example 2:
Input: nums = [6,2,0,9,7]
Output: [9,7,6,2,0]
Explanation:
When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.
Constraints:
3 <= nums.length <= 105
0 <= nums[i] <= 105
| Medium | [
"array",
"greedy",
"sorting"
] | null | [] |
1,969 | minimum-non-zero-product-of-the-array-elements | [
"Try to minimize each element by swapping bits with any of the elements after it.",
"If you swap out all the 1s in some element, this will lead to a product of zero."
] | /**
* @param {number} p
* @return {number}
*/
var minNonZeroProduct = function(p) {
}; | You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times:
Choose two elements x and y from nums.
Choose a bit in x and swap it with its corresponding bit in y. Corresponding bit refers to the bit that is in the same position in the other integer.
For example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001.
Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 109 + 7.
Note: The answer should be the minimum product before the modulo operation is done.
Example 1:
Input: p = 1
Output: 1
Explanation: nums = [1].
There is only one element, so the product equals that element.
Example 2:
Input: p = 2
Output: 6
Explanation: nums = [01, 10, 11].
Any swap would either make the product 0 or stay the same.
Thus, the array product of 1 * 2 * 3 = 6 is already minimized.
Example 3:
Input: p = 3
Output: 1512
Explanation: nums = [001, 010, 011, 100, 101, 110, 111]
- In the first operation we can swap the leftmost bit of the second and fifth elements.
- The resulting array is [001, 110, 011, 100, 001, 110, 111].
- In the second operation we can swap the middle bit of the third and fourth elements.
- The resulting array is [001, 110, 001, 110, 001, 110, 111].
The array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.
Constraints:
1 <= p <= 60
| Medium | [
"math",
"greedy",
"recursion"
] | [
"const minNonZeroProduct = function (p) {\n const MOD = BigInt(10 ** 9 + 7), bp = BigInt(p)\n const bpm = BigInt(1n << bp) - 1n, base = BigInt(1n << bp) - 2n, pow = BigInt(1n << (bp - 1n)) - 1n \n return Number((bpm % MOD) * fastPow(base, pow, MOD) % MOD)\n\n}\n\nfunction fastPow(base, power, mod) {\n if(power === 0n) return 1n\n base %= mod\n let res = fastPow(base, power / 2n, mod)\n res = (res * res) % mod\n if(power & 1n) res = (res * base) % mod\n return res\n}",
"const minNonZeroProduct = function (p) {\n const b = BigInt(p)\n const mod = BigInt(10 ** 9 + 7)\n\n return (\n (((BigInt(1n << b) - 1n) % mod) *\n pow(BigInt(1n << b) - 2n, BigInt(1n << (b - 1n)) - 1n)) %\n mod\n )\n\n function pow(a, n) {\n let r = 1n\n a %= mod\n while (n > 0n) {\n r = (r * a) % mod\n a = (a * a) % mod\n n /= 2n\n }\n return r\n }\n}"
] |
|
1,970 | last-day-where-you-can-still-cross | [
"What graph algorithm allows us to find whether a path exists?",
"Can we use binary search to help us solve the problem?"
] | /**
* @param {number} row
* @param {number} col
* @param {number[][]} cells
* @return {number}
*/
var latestDayToCross = function(row, col, cells) {
}; | There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.
Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1).
You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down).
Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.
Example 1:
Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]
Output: 2
Explanation: The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
Example 2:
Input: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]
Output: 1
Explanation: The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
Example 3:
Input: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]
Output: 3
Explanation: The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
Constraints:
2 <= row, col <= 2 * 104
4 <= row * col <= 2 * 104
cells.length == row * col
1 <= ri <= row
1 <= ci <= col
All the values of cells are unique.
| Hard | [
"array",
"binary-search",
"depth-first-search",
"breadth-first-search",
"union-find",
"matrix"
] | [
"const latestDayToCross = function (row, col, cells) {\n let l = 0,\n n = cells.length,\n r = n\n while (l < r) {\n const mid = r - (~~((r - l) / 2))\n if (canWalk(mid)) {\n l = mid\n } else {\n r = mid - 1\n }\n }\n\n return l + 1\n\n function canWalk(mid) {\n const grid = Array.from({ length: row }, () => Array(col).fill(0))\n const dirs = [\n [1, 0],\n [-1, 0],\n [0, 1],\n [0, -1],\n ]\n for (let i = 0; i <= mid; i++) {\n const [r, c] = cells[i]\n grid[r - 1][c - 1] = 1\n }\n\n let q = []\n\n for (let i = 0; i < col; i++) {\n if (grid[0][i] === 0) {\n q.push([0, i])\n grid[0][i] = 1\n }\n }\n\n while (q.length) {\n const size = q.length,\n tmp = []\n for (let i = 0; i < size; i++) {\n const [r, c] = q[i]\n if (r === row - 1) return true\n for (let [dr, dc] of dirs) {\n const nr = r + dr,\n nc = c + dc\n if (nr < 0 || nr >= row || nc < 0 || nc >= col || grid[nr][nc] === 1)\n continue\n tmp.push([nr, nc])\n grid[nr][nc] = 1\n }\n }\n q = tmp\n }\n\n return false\n }\n}"
] |
|
1,971 | find-if-path-exists-in-graph | [] | /**
* @param {number} n
* @param {number[][]} edges
* @param {number} source
* @param {number} destination
* @return {boolean}
*/
var validPath = function(n, edges, source, destination) {
}; | There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.
You want to determine if there is a valid path that exists from vertex source to vertex destination.
Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.
Example 1:
Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
Output: true
Explanation: There are two paths from vertex 0 to vertex 2:
- 0 → 1 → 2
- 0 → 2
Example 2:
Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
Output: false
Explanation: There is no path from vertex 0 to vertex 5.
Constraints:
1 <= n <= 2 * 105
0 <= edges.length <= 2 * 105
edges[i].length == 2
0 <= ui, vi <= n - 1
ui != vi
0 <= source, destination <= n - 1
There are no duplicate edges.
There are no self edges.
| Easy | [
"depth-first-search",
"breadth-first-search",
"union-find",
"graph"
] | [
"const validPath = function(n, edges, start, end) {\n const graph = {}\n for(const [u, v] of edges) {\n if(graph[u] == null) graph[u] = new Set()\n if(graph[v] == null) graph[v] = new Set()\n graph[u].add(v)\n graph[v].add(u)\n }\n const q = [start], visited = new Set()\n visited.add(start)\n while(q.length) {\n const cur = q.shift()\n if(cur === end) return true\n for(const next of graph[cur]) {\n if(visited.has(next)) continue\n q.push(next)\n visited.add(next)\n }\n }\n\n return false\n};"
] |
|
1,974 | minimum-time-to-type-word-using-special-typewriter | [
"There are only two possible directions you can go when you move to the next letter.",
"When moving to the next letter, you will always go in the direction that takes the least amount of time."
] | /**
* @param {string} word
* @return {number}
*/
var minTimeToType = function(word) {
}; | There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.
Each second, you may perform one of the following operations:
Move the pointer one character counterclockwise or clockwise.
Type the character the pointer is currently on.
Given a string word, return the minimum number of seconds to type out the characters in word.
Example 1:
Input: word = "abc"
Output: 5
Explanation:
The characters are printed as follows:
- Type the character 'a' in 1 second since the pointer is initially on 'a'.
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer clockwise to 'c' in 1 second.
- Type the character 'c' in 1 second.
Example 2:
Input: word = "bza"
Output: 7
Explanation:
The characters are printed as follows:
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer counterclockwise to 'z' in 2 seconds.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'a' in 1 second.
- Type the character 'a' in 1 second.
Example 3:
Input: word = "zjpc"
Output: 34
Explanation:
The characters are printed as follows:
- Move the pointer counterclockwise to 'z' in 1 second.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'j' in 10 seconds.
- Type the character 'j' in 1 second.
- Move the pointer clockwise to 'p' in 6 seconds.
- Type the character 'p' in 1 second.
- Move the pointer counterclockwise to 'c' in 13 seconds.
- Type the character 'c' in 1 second.
Constraints:
1 <= word.length <= 100
word consists of lowercase English letters.
| Easy | [
"string",
"greedy"
] | null | [] |
1,975 | maximum-matrix-sum | [
"Try to use the operation so that each row has only one negative number.",
"If you have only one negative element you cannot convert it to positive."
] | /**
* @param {number[][]} matrix
* @return {number}
*/
var maxMatrixSum = function(matrix) {
}; | You are given an n x n integer matrix. You can do the following operation any number of times:
Choose any two adjacent elements of matrix and multiply each of them by -1.
Two elements are considered adjacent if and only if they share a border.
Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.
Example 1:
Input: matrix = [[1,-1],[-1,1]]
Output: 4
Explanation: We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
Example 2:
Input: matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]
Output: 16
Explanation: We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
Constraints:
n == matrix.length == matrix[i].length
2 <= n <= 250
-105 <= matrix[i][j] <= 105
| Medium | [
"array",
"greedy",
"matrix"
] | null | [] |
1,976 | number-of-ways-to-arrive-at-destination | [
"First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x",
"Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp"
] | /**
* @param {number} n
* @param {number[][]} roads
* @return {number}
*/
var countPaths = function(n, roads) {
}; | You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.
You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time.
Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.
Example 1:
Input: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]
Output: 4
Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.
The four ways to get there in 7 minutes are:
- 0 ➝ 6
- 0 ➝ 4 ➝ 6
- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6
- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6
Example 2:
Input: n = 2, roads = [[1,0,10]]
Output: 1
Explanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.
Constraints:
1 <= n <= 200
n - 1 <= roads.length <= n * (n - 1) / 2
roads[i].length == 3
0 <= ui, vi <= n - 1
1 <= timei <= 109
ui != vi
There is at most one road connecting any two intersections.
You can reach any intersection from any other intersection.
| Medium | [
"dynamic-programming",
"graph",
"topological-sort",
"shortest-path"
] | [
"const countPaths = function(n, roads) {\n const graph = {}\n for(let r of roads) {\n const [u, v, t] = r\n if(graph[u] == null) graph[u] = []\n if(graph[v] == null) graph[v] = []\n graph[u].push([v, t])\n graph[v].push([u, t])\n }\n \n return dijkstra(graph, n, 0)\n\n function dijkstra(graph, n, src) {\n const dist = Array(n).fill(Infinity)\n const ways = Array(n).fill(0), mod = 1e9 + 7\n ways[src] = 1\n dist[src] = 0\n const pq = new PriorityQueue((a, b) => a[0] === b[0] ? a[1] < b[1] : a[0] < b[0])\n pq.push([0, 0])\n while(!pq.isEmpty()) {\n const [d, u] = pq.pop()\n if(d > dist[u]) continue\n if(graph[u] == null) graph[u] = []\n for(const [v, time] of graph[u]) {\n if(dist[v] > d + time) {\n ways[v] = ways[u]\n dist[v] = d + time\n pq.push([dist[v], v])\n } else if(dist[v] === d + time) {\n ways[v] = (ways[v] + ways[u]) % mod\n }\n }\n }\n return ways[n - 1]\n }\n \n};\n \nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}",
"const countPaths = function(n, roads) {\n const graph = {}, MOD = 1e9 + 7\n for(const [u, v, t] of roads) {\n if(graph[u] == null) graph[u] = {}\n if(graph[v] == null) graph[v] = {}\n graph[u][v] = t\n graph[v][u] = t\n }\n\n return dijkstra(graph, n, 0)\n\n function dijkstra(graph, n, src) {\n const dist = Array(n).fill(Infinity)\n const ways = Array(n).fill(0)\n ways[src] = 1\n dist[src] = 0\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n pq.push([0, 0])\n while(!pq.isEmpty()) {\n const [d, u] = pq.pop()\n if(d > dist[u]) continue\n for(const next of Object.keys(graph[u] || {})) {\n const val = graph[u][next]\n if(dist[next] > d + val) {\n dist[next] = d + val\n ways[next] = ways[u]\n pq.push([dist[next], next])\n } else if(dist[next] === d + val) {\n ways[next] = (ways[next] + ways[u]) % MOD\n }\n }\n }\n\n return ways[n - 1]\n }\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}"
] |
|
1,977 | number-of-ways-to-separate-numbers | [
"If we know the current number has d digits, how many digits can the previous number have?",
"Is there a quick way of calculating the number of possibilities for the previous number if we know that it must have less than or equal to d digits? Try to do some pre-processing."
] | /**
* @param {string} num
* @return {number}
*/
var numberOfCombinations = function(num) {
}; | You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros.
Return the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo 109 + 7.
Example 1:
Input: num = "327"
Output: 2
Explanation: You could have written down the numbers:
3, 27
327
Example 2:
Input: num = "094"
Output: 0
Explanation: No numbers can have leading zeros and all numbers must be positive.
Example 3:
Input: num = "0"
Output: 0
Explanation: No numbers can have leading zeros and all numbers must be positive.
Constraints:
1 <= num.length <= 3500
num consists of digits '0' through '9'.
| Hard | [
"string",
"dynamic-programming",
"suffix-array"
] | [
"function numberOfCombinations(num) {\n let dpArr = Array(3501).fill(0),\n dp = Array(3501).fill(0),\n prefix = Array(3501).fill(0),\n n = num.length,\n mod = 1e9 + 7\n for (let l = 1; l <= n; ++l) {\n dp[0] = 1\n for (let i = n; i - l > 0; --i)\n prefix[i - 1] = num[i - 1 - l] === num[i - 1] ? prefix[i] + 1 : 0\n for (let i = 0; i < n; ++i) {\n dpArr[i + 1] = dp[i + 1]\n if (l <= i + 1 && num[i + 1 - l] != '0') {\n if (\n i + 1 - 2 * l >= 0 &&\n (prefix[i + 1 - l] >= l ||\n num[i + 1 - l + prefix[i + 1 - l]] > num[i + 1 - 2 * l + prefix[i + 1 - l]])\n )\n dpArr[i + 1] = (dpArr[i + 1] + dpArr[i + 1 - l]) % mod\n else dpArr[i + 1] = (dpArr[i + 1] + dp[i + 1 - l]) % mod\n }\n }\n const tmp = dp\n dp = dpArr\n dpArr = tmp\n }\n return dp[n]\n}"
] |
|
1,979 | find-greatest-common-divisor-of-array | [
"Find the minimum and maximum in one iteration. Let them be mn and mx.",
"Try all the numbers in the range [1, mn] and check the largest number which divides both of them."
] | /**
* @param {number[]} nums
* @return {number}
*/
var findGCD = function(nums) {
}; | Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.
The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
Example 1:
Input: nums = [2,5,6,9,10]
Output: 2
Explanation:
The smallest number in nums is 2.
The largest number in nums is 10.
The greatest common divisor of 2 and 10 is 2.
Example 2:
Input: nums = [7,5,6,8,3]
Output: 1
Explanation:
The smallest number in nums is 3.
The largest number in nums is 8.
The greatest common divisor of 3 and 8 is 1.
Example 3:
Input: nums = [3,3]
Output: 3
Explanation:
The smallest number in nums is 3.
The largest number in nums is 3.
The greatest common divisor of 3 and 3 is 3.
Constraints:
2 <= nums.length <= 1000
1 <= nums[i] <= 1000
| Easy | [
"array",
"math",
"number-theory"
] | [
"const findGCD = function(nums) {\n let min = Math.min(...nums)\n let max = Math.max(...nums)\n return gcd(min, max)\n};\n\nfunction gcd(a, b) {\n return b === 0 ? a : gcd(b, a % b)\n}"
] |
|
1,980 | find-unique-binary-string | [
"We can convert the given strings into base 10 integers.",
"Can we use recursion to generate all possible strings?"
] | /**
* @param {string[]} nums
* @return {string}
*/
var findDifferentBinaryString = function(nums) {
}; | Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
Example 1:
Input: nums = ["01","10"]
Output: "11"
Explanation: "11" does not appear in nums. "00" would also be correct.
Example 2:
Input: nums = ["00","01"]
Output: "11"
Explanation: "11" does not appear in nums. "10" would also be correct.
Example 3:
Input: nums = ["111","011","001"]
Output: "101"
Explanation: "101" does not appear in nums. "000", "010", "100", and "110" would also be correct.
Constraints:
n == nums.length
1 <= n <= 16
nums[i].length == n
nums[i] is either '0' or '1'.
All the strings of nums are unique.
| Medium | [
"array",
"string",
"backtracking"
] | [
"const findDifferentBinaryString = function(nums) {\n const set = new Set(nums)\n const len = nums[0].length\n for(let i = 0, n = 1 << 17; i < n; i++) {\n const tmp = pad(bin(i), len)\n if(!set.has(tmp)) return tmp\n }\n return ''\n};\n\nfunction bin(num) {\n return (num >>> 0).toString(2)\n}\n\nfunction pad(str,n) {\n while(str.length < n) str = '0' + str\n return str\n}"
] |
|
1,981 | minimize-the-difference-between-target-and-chosen-elements | [
"The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row.",
"Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much."
] | /**
* @param {number[][]} mat
* @param {number} target
* @return {number}
*/
var minimizeTheDifference = function(mat, target) {
}; | You are given an m x n integer matrix mat and an integer target.
Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized.
Return the minimum absolute difference.
The absolute difference between two numbers a and b is the absolute value of a - b.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13
Output: 0
Explanation: One possible choice is to:
- Choose 1 from the first row.
- Choose 5 from the second row.
- Choose 7 from the third row.
The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.
Example 2:
Input: mat = [[1],[2],[3]], target = 100
Output: 94
Explanation: The best possible choice is to:
- Choose 1 from the first row.
- Choose 2 from the second row.
- Choose 3 from the third row.
The sum of the chosen elements is 6, and the absolute difference is 94.
Example 3:
Input: mat = [[1,2,9,8,7]], target = 6
Output: 1
Explanation: The best choice is to choose 7 from the first row.
The absolute difference is 1.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 70
1 <= mat[i][j] <= 70
1 <= target <= 800
| Medium | [
"array",
"dynamic-programming",
"matrix"
] | [
"const minimizeTheDifference = function(mat, target) {\n const m = mat.length, n = mat[0].length\n const dp = Array.from({length: m}, () => Array(70*70).fill(-1))\n return fn(0, 0)\n \n function fn(row, sum) {\n if(row === m) return Math.abs(target - sum)\n if(dp[row][sum] !== -1) return dp[row][sum]\n let res = Number.MAX_SAFE_INTEGER\n for(let j = 0; j < n; j++) {\n res = Math.min(res, fn(row + 1, sum + mat[row][j]))\n }\n return dp[row][sum] = res\n }\n};",
"const minimizeTheDifference = function(mat, target) {\n const m = mat.length, n = mat[0].length\n const memo = Array.from({ length: m }, () => Array())\n return dfs(0, 0)\n \n function dfs(row, sum) {\n if(row === m) return Math.abs(target - sum)\n if(memo[row][sum] != null) return memo[row][sum]\n let res = Number.MAX_SAFE_INTEGER\n for(let i = 0; i < n; i++) {\n res = Math.min(res, dfs(row + 1, sum + mat[row][i]))\n }\n \n return memo[row][sum] = res\n }\n};"
] |
|
1,982 | find-array-given-subset-sums | [
"What information do the two largest elements tell us?",
"Can we use recursion to check all possible states?"
] | /**
* @param {number} n
* @param {number[]} sums
* @return {number[]}
*/
var recoverArray = function(n, sums) {
}; | You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order).
Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them.
An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0.
Note: Test cases are generated such that there will always be at least one correct answer.
Example 1:
Input: n = 3, sums = [-3,-2,-1,0,0,1,2,3]
Output: [1,2,-3]
Explanation: [1,2,-3] is able to achieve the given subset sums:
- []: sum is 0
- [1]: sum is 1
- [2]: sum is 2
- [1,2]: sum is 3
- [-3]: sum is -3
- [1,-3]: sum is -2
- [2,-3]: sum is -1
- [1,2,-3]: sum is 0
Note that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.
Example 2:
Input: n = 2, sums = [0,0,0,0]
Output: [0,0]
Explanation: The only correct answer is [0,0].
Example 3:
Input: n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]
Output: [0,-1,4,5]
Explanation: [0,-1,4,5] is able to achieve the given subset sums.
Constraints:
1 <= n <= 15
sums.length == 2n
-104 <= sums[i] <= 104
| Hard | [
"array",
"divide-and-conquer"
] | [
"const recoverArray = function(n, sums) {\n const res = []\n sums.sort((a, b) => a - b)\n while(res.length < n) {\n const used = Array(sums.length).fill(false)\n const v0 = [], v1 = []\n let d = sums[1] - sums[0]\n for(let i = 0, j = 1; ;i++, j++) {\n while(i < sums.length && used[i]) i++\n if(i === sums.length) break\n while(j <= i || sums[j] !== sums[i] + d) j++\n v0.push(sums[i])\n v1.push(sums[j])\n used[i] = used[j] = true\n }\n \n if(bs(v0, 0)) {\n res.push(d)\n sums = v0\n }else {\n res.push(-d)\n sums = v1\n }\n }\n return res\n};\n\n\nfunction bs(arr, e) {\n let l = 0, r = arr.length - 1\n while(l < r) {\n const mid = ~~((l + r) / 2)\n if(arr[mid] < e) l = mid + 1\n else r = mid\n }\n \n return arr[l] === e\n}",
"const recoverArray = function(n, sums) {\n const res = []\n sums.sort((a, b) => a - b)\n \n while(res.length < n) {\n const visited = Array(sums.length).fill(false)\n const a1 = [], a2 = []\n const d = sums[1] - sums[0]\n for(let i = 0, j = 1; i < sums.length; i++, j++) {\n while(i < sums.length && visited[i]) i++\n if(i === sums.length) break\n while(j <= i || sums[j] !== sums[i] + d) j++\n a1.push(sums[i])\n a2.push(sums[j])\n visited[i] = visited[j] = true\n }\n \n if(bs(a1, 0)) {\n sums = a1\n res.push(d)\n } else {\n sums = a2\n res.push(-d)\n }\n }\n \n return res\n};\n\nfunction bs(arr, val) {\n let l = 0, r = arr.length - 1\n while(l < r) {\n const mid = ~~((l + r) / 2)\n if(arr[mid] < val) l = mid + 1\n else r = mid\n }\n \n return arr[l] === val\n}",
"const recoverArray = function(n, sums) {\n const res = []\n sums.sort((a, b) => a - b)\n \n while(res.length < n) {\n const m = sums.length, visited = Array(m).fill(false)\n let a1 = [], a2 = [], delta = sums[1] - sums[0]\n for(let i = 0, j = 1; i < m && j < m; i++, j++) {\n while(i < m && visited[i]) i++\n if(i === m) break\n while(i >= j || sums[j] !== sums[i] + delta) j++\n if(j === m) break\n a1.push(sums[i])\n a2.push(sums[j])\n visited[i] = visited[j] = true\n }\n if(binarySearch(a1, 0)) {\n sums = a1\n res.push(delta)\n } else {\n sums = a2\n res.push(-delta)\n }\n }\n return res\n \n function binarySearch(arr, val) {\n let l = 0, r = arr.length - 1\n while(l < r) {\n const mid = ~~((l + r) / 2)\n if(arr[mid] < val) l = mid + 1\n else r = mid\n }\n return arr[l] === val\n }\n};"
] |
|
1,984 | minimum-difference-between-highest-and-lowest-of-k-scores | [
"For the difference between the highest and lowest element to be minimized, the k chosen scores need to be as close to each other as possible.",
"What if the array was sorted?",
"After sorting the scores, any contiguous k scores are as close to each other as possible.",
"Apply a sliding window solution to iterate over each contiguous k scores, and find the minimum of the differences of all windows."
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var minimumDifference = function(nums, k) {
}; | You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k.
Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized.
Return the minimum possible difference.
Example 1:
Input: nums = [90], k = 1
Output: 0
Explanation: There is one way to pick score(s) of one student:
- [90]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
Example 2:
Input: nums = [9,4,1,7], k = 2
Output: 2
Explanation: There are six ways to pick score(s) of two students:
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.
- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.
- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.
- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
Constraints:
1 <= k <= nums.length <= 1000
0 <= nums[i] <= 105
| Easy | [
"array",
"sliding-window",
"sorting"
] | [
"const minimumDifference = function(nums, k) {\n nums.sort((a, b) => a - b)\n let res = Infinity\n for(let i = 0, n = nums.length; i < n - k + 1; i++) {\n res = Math.min(res, nums[i + k - 1] - nums[i])\n }\n \n return res\n \n};"
] |
|
1,985 | find-the-kth-largest-integer-in-the-array | [
"If two numbers have different lengths, which one will be larger?",
"The longer number is the larger number.",
"If two numbers have the same length, which one will be larger?",
"Compare the two numbers starting from the most significant digit. Once you have found the first digit that differs, the one with the larger digit is the larger number."
] | /**
* @param {string[]} nums
* @param {number} k
* @return {string}
*/
var kthLargestNumber = function(nums, k) {
}; | You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros.
Return the string that represents the kth largest integer in nums.
Note: Duplicate numbers should be counted distinctly. For example, if nums is ["1","2","2"], "2" is the first largest integer, "2" is the second-largest integer, and "1" is the third-largest integer.
Example 1:
Input: nums = ["3","6","7","10"], k = 4
Output: "3"
Explanation:
The numbers in nums sorted in non-decreasing order are ["3","6","7","10"].
The 4th largest integer in nums is "3".
Example 2:
Input: nums = ["2","21","12","1"], k = 3
Output: "2"
Explanation:
The numbers in nums sorted in non-decreasing order are ["1","2","12","21"].
The 3rd largest integer in nums is "2".
Example 3:
Input: nums = ["0","0"], k = 2
Output: "0"
Explanation:
The numbers in nums sorted in non-decreasing order are ["0","0"].
The 2nd largest integer in nums is "0".
Constraints:
1 <= k <= nums.length <= 104
1 <= nums[i].length <= 100
nums[i] consists of only digits.
nums[i] will not have any leading zeros.
| Medium | [
"array",
"string",
"divide-and-conquer",
"sorting",
"heap-priority-queue",
"quickselect"
] | [
"const kthLargestNumber = function(nums, k) {\n nums.sort((a, b) => BigInt(b) - BigInt(a) === 0n ? 0 : (BigInt(b) - BigInt(a) > 0n ? 1 : -1) )\n return nums[k - 1]\n};"
] |
|
1,986 | minimum-number-of-work-sessions-to-finish-the-tasks | [
"Try all possible ways of assignment.",
"If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way."
] | /**
* @param {number[]} tasks
* @param {number} sessionTime
* @return {number}
*/
var minSessions = function(tasks, sessionTime) {
}; | There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break.
You should finish the given tasks in a way that satisfies the following conditions:
If you start a task in a work session, you must complete it in the same work session.
You can start a new task immediately after finishing the previous one.
You may complete the tasks in any order.
Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above.
The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].
Example 1:
Input: tasks = [1,2,3], sessionTime = 3
Output: 2
Explanation: You can finish the tasks in two work sessions.
- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.
- Second work session: finish the third task in 3 hours.
Example 2:
Input: tasks = [3,1,3,1,1], sessionTime = 8
Output: 2
Explanation: You can finish the tasks in two work sessions.
- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.
- Second work session: finish the last task in 1 hour.
Example 3:
Input: tasks = [1,2,3,4,5], sessionTime = 15
Output: 1
Explanation: You can finish all the tasks in one work session.
Constraints:
n == tasks.length
1 <= n <= 14
1 <= tasks[i] <= 10
max(tasks[i]) <= sessionTime <= 15
| Medium | [
"array",
"dynamic-programming",
"backtracking",
"bit-manipulation",
"bitmask"
] | [
"const minSessions = function(tasks, sessionTime) {\n const n = tasks.length\n const limit = 1 << n\n \n const dp = Array(limit).fill(Infinity)\n dp[0] = 0\n for(let mask = 1; mask < limit; mask++) {\n for(let sub = mask; sub; sub = (sub - 1) & mask) {\n if(valid(sub)) {\n dp[mask] = Math.min(dp[mask], dp[mask - sub] + 1) \n }\n }\n }\n \n return dp[limit - 1]\n \n function valid(sub) {\n let sum = 0\n for(let i = 0; i < 14; i++) {\n if((sub >> i) & 1) sum += tasks[i]\n }\n \n return sum <= sessionTime\n }\n};",
"const minSessions = function(tasks, sessionTime) {\n const n = tasks.length\n const dp = Array.from({ length: 1 << 14 }, () => Array(16).fill(-1))\n return fn(0, 0)\n \n function fn(mask, consumed) {\n if (mask === (1 << n) - 1) {\n return consumed === 0 ? 0 : 1\n }\n if (dp[mask][consumed] !== -1) {\n return dp[mask][consumed];\n }\n\n let result = Number.MAX_VALUE;\n if (consumed > 0) {\n result = Math.min(result, 1 + fn(mask, 0));\n }\n for (let i = 0; i < n; i++) {\n if ((mask & (1 << i)) === 0 && consumed + tasks[i] <= sessionTime) {\n result = Math.min(result, fn(mask | (1 << i), consumed + tasks[i]));\n }\n }\n return dp[mask][consumed] = result;\n }\n};",
"function minSessions(tasks, sessionTime) {\n const n = tasks.length\n const memo = Array.from({ length: 1 << n }, () => Array(15))\n return helper((1 << n) - 1, 0)\n\n function helper(mask, remain) {\n if(mask === 0) return 0\n if(memo[mask][remain] != null) return memo[mask][remain]\n let res = n\n \n for(let i = 0; i < n; i++) {\n if((1 << i) & mask) {\n const newMask = mask & (~(1 << i))\n if(tasks[i] <= remain) {\n res = Math.min(res, helper(newMask, remain - tasks[i]))\n } else {\n res = Math.min(res, helper(newMask, sessionTime - tasks[i]) + 1)\n }\n }\n }\n\n return memo[mask][remain] = res\n }\n}"
] |
|
1,987 | number-of-unique-good-subsequences | [
"The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences.",
"Find the answer at each index based on the previous indexes' answers."
] | /**
* @param {string} binary
* @return {number}
*/
var numberOfUniqueGoodSubsequences = function(binary) {
}; | You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of "0").
Find the number of unique good subsequences of binary.
For example, if binary = "001", then all the good subsequences are ["0", "0", "1"], so the unique good subsequences are "0" and "1". Note that subsequences "00", "01", and "001" are not good because they have leading zeros.
Return the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 109 + 7.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: binary = "001"
Output: 2
Explanation: The good subsequences of binary are ["0", "0", "1"].
The unique good subsequences are "0" and "1".
Example 2:
Input: binary = "11"
Output: 2
Explanation: The good subsequences of binary are ["1", "1", "11"].
The unique good subsequences are "1" and "11".
Example 3:
Input: binary = "101"
Output: 5
Explanation: The good subsequences of binary are ["1", "0", "1", "10", "11", "101"].
The unique good subsequences are "0", "1", "10", "11", and "101".
Constraints:
1 <= binary.length <= 105
binary consists of only '0's and '1's.
| Hard | [
"string",
"dynamic-programming"
] | [
"const numberOfUniqueGoodSubsequences = function (binary) {\n const n = binary.length,\n P = 1e9 + 7\n let first1Position = -1,\n first0Position = -1\n for (let i = 0; i < binary.length; i++) {\n if (binary[i] === '0' && first0Position == -1) {\n first0Position = i\n }\n if (binary[i] === '1' && first1Position == -1) {\n first1Position = i\n }\n if(first0Position !== -1 && first1Position !== -1) break\n }\n if (first1Position === -1) return 1\n if (first0Position === -1) return n\n\n const next0 = new Array(n).fill(0)\n const next1 = new Array(n).fill(0)\n let nextZero = -1,\n nextOne = -1\n for (let i = binary.length - 1; i >= 0; i--) {\n next0[i] = nextZero\n next1[i] = nextOne\n if (binary[i] === '0') {\n nextZero = i\n } else {\n nextOne = i\n }\n }\n const dp = new Array(n).fill(-1)\n return (1 + fn(first1Position)) % P\n\n function fn(index) {\n if (index == n) return 0\n if (dp[index] !== -1) return dp[index]\n let result = 1\n if (next0[index] >= 0) {\n result += fn(next0[index])\n result %= P\n }\n if (next1[index] >= 0) {\n result += fn(next1[index])\n result %= P\n }\n return (dp[index] = result)\n }\n}",
"const numberOfUniqueGoodSubsequences = function (binary) {\n const n = binary.length,\n mod = 1e9 + 7\n let hasZero = 0, ends1 = 0, ends0 = 0\n for(let ch of binary) {\n if(ch === '1') {\n ends1 = (ends1 + ends0 + 1) % mod\n } else {\n ends0 = (ends1 + ends0) % mod\n hasZero = 1\n }\n }\n return (ends1 + ends0 + hasZero) % mod\n}"
] |
|
1,991 | find-the-middle-index-in-array | [
"Could we go from left to right and check to see if an index is a middle index?",
"Do we need to sum every number to the left and right of an index each time?",
"Use a prefix sum array where prefix[i] = nums[0] + nums[1] + ... + nums[i]."
] | /**
* @param {number[]} nums
* @return {number}
*/
var findMiddleIndex = function(nums) {
}; | Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).
A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].
If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.
Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.
Example 1:
Input: nums = [2,3,-1,8,4]
Output: 3
Explanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4
Example 2:
Input: nums = [1,-1,4]
Output: 2
Explanation: The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0
Example 3:
Input: nums = [2,5]
Output: -1
Explanation: There is no valid middleIndex.
Constraints:
1 <= nums.length <= 100
-1000 <= nums[i] <= 1000
Note: This question is the same as 724: https://leetcode.com/problems/find-pivot-index/
| Easy | [
"array",
"prefix-sum"
] | [
"const findMiddleIndex = function(nums) {\n const n = nums.length\n const sum = nums.reduce((ac, e) => ac + e, 0) \n \n let res, leftSum = 0\n for(let i = 0; i < n; i++) {\n if(leftSum === sum - leftSum - nums[i]) {\n res = i\n break\n }\n leftSum += nums[i]\n }\n\n return res == null ? -1 : res\n};"
] |
|
1,992 | find-all-groups-of-farmland | [
"Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group.",
"Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group.",
"Use DFS to traverse through different groups of farmlands and keep track of the smallest and largest x-coordinate and y-coordinates you have seen in each group."
] | /**
* @param {number[][]} land
* @return {number[][]}
*/
var findFarmland = function(land) {
}; | You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group.
land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2].
Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.
Example 1:
Input: land = [[1,0,0],[0,1,1],[0,1,1]]
Output: [[0,0,0,0],[1,1,2,2]]
Explanation:
The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].
The second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].
Example 2:
Input: land = [[1,1],[1,1]]
Output: [[0,0,1,1]]
Explanation:
The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].
Example 3:
Input: land = [[0]]
Output: []
Explanation:
There are no groups of farmland.
Constraints:
m == land.length
n == land[i].length
1 <= m, n <= 300
land consists of only 0's and 1's.
Groups of farmland are rectangular in shape.
| Medium | [
"array",
"depth-first-search",
"breadth-first-search",
"matrix"
] | null | [] |
1,993 | operations-on-tree | [
"How can we use the small constraints to help us solve the problem?",
"How can we traverse the ancestors and descendants of a node?"
] | /**
* @param {number[]} parent
*/
var LockingTree = function(parent) {
};
/**
* @param {number} num
* @param {number} user
* @return {boolean}
*/
LockingTree.prototype.lock = function(num, user) {
};
/**
* @param {number} num
* @param {number} user
* @return {boolean}
*/
LockingTree.prototype.unlock = function(num, user) {
};
/**
* @param {number} num
* @param {number} user
* @return {boolean}
*/
LockingTree.prototype.upgrade = function(num, user) {
};
/**
* Your LockingTree object will be instantiated and called as such:
* var obj = new LockingTree(parent)
* var param_1 = obj.lock(num,user)
* var param_2 = obj.unlock(num,user)
* var param_3 = obj.upgrade(num,user)
*/ | 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 the ith node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
Lock: Locks the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
Unlock: Unlocks the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
Upgrade: Locks the given node for the given user and unlocks all of its descendants regardless of who locked it. You may only upgrade a node if all 3 conditions are true:
The node is unlocked,
It has at least one locked descendant (by any user), and
It does not have any locked ancestors.
Implement the LockingTree class:
LockingTree(int[] parent) initializes the data structure with the parent array.
lock(int num, int user) returns true if it is possible for the user with id user to lock the node num, or false otherwise. If it is possible, the node num will become locked by the user with id user.
unlock(int num, int user) returns true if it is possible for the user with id user to unlock the node num, or false otherwise. If it is possible, the node num will become unlocked.
upgrade(int num, int user) returns true if it is possible for the user with id user to upgrade the node num, or false otherwise. If it is possible, the node num will be upgraded.
Example 1:
Input
["LockingTree", "lock", "unlock", "unlock", "lock", "upgrade", "lock"]
[[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]]
Output
[null, true, false, true, true, true, false]
Explanation
LockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]);
lockingTree.lock(2, 2); // return true because node 2 is unlocked.
// Node 2 will now be locked by user 2.
lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.
lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.
// Node 2 will now be unlocked.
lockingTree.lock(4, 5); // return true because node 4 is unlocked.
// Node 4 will now be locked by user 5.
lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).
// Node 0 will now be locked by user 1 and node 4 will now be unlocked.
lockingTree.lock(0, 1); // return false because node 0 is already locked.
Constraints:
n == parent.length
2 <= n <= 2000
0 <= parent[i] <= n - 1 for i != 0
parent[0] == -1
0 <= num <= n - 1
1 <= user <= 104
parent represents a valid tree.
At most 2000 calls in total will be made to lock, unlock, and upgrade.
| Medium | [
"hash-table",
"tree",
"depth-first-search",
"breadth-first-search",
"design"
] | null | [] |
1,994 | the-number-of-good-subsets | [
"Consider only the numbers which have a good prime factorization.",
"Use brute force to find all possible good subsets and then calculate its frequency in nums."
] | /**
* @param {number[]} nums
* @return {number}
*/
var numberOfGoodSubsets = function(nums) {
}; | You are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers.
For example, if nums = [1, 2, 3, 4]:
[2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 respectively.
[1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively.
Return the number of different good subsets in nums modulo 109 + 7.
A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.
Example 1:
Input: nums = [1,2,3,4]
Output: 6
Explanation: The good subsets are:
- [1,2]: product is 2, which is the product of distinct prime 2.
- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.
- [1,3]: product is 3, which is the product of distinct prime 3.
- [2]: product is 2, which is the product of distinct prime 2.
- [2,3]: product is 6, which is the product of distinct primes 2 and 3.
- [3]: product is 3, which is the product of distinct prime 3.
Example 2:
Input: nums = [4,2,3,15]
Output: 5
Explanation: The good subsets are:
- [2]: product is 2, which is the product of distinct prime 2.
- [2,3]: product is 6, which is the product of distinct primes 2 and 3.
- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.
- [3]: product is 3, which is the product of distinct prime 3.
- [15]: product is 15, which is the product of distinct primes 3 and 5.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 30
| Hard | [
"array",
"math",
"dynamic-programming",
"bit-manipulation",
"bitmask"
] | [
"const numberOfGoodSubsets = function (nums) {\n const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n const n = nums.length,\n cnt = {},\n mod = BigInt(1e9 + 7)\n const bm = []\n for (let num of nums) {\n cnt[num] = (cnt[num] || 0n) + 1n\n }\n for (let i = 0; i < 31; i++) {\n let tmp = 0\n for (let j = 0, m = primes.length; j < m; j++) {\n const p = primes[j]\n if (i % p === 0) tmp += 1 << j\n }\n bm[i] = tmp\n }\n const bad = new Set([4, 8, 9, 12, 16, 18, 20, 24, 25, 27, 28])\n const memo = {}\n\n function dp(mask, num) {\n if (num === 1) return 1n\n if (memo[mask] && memo[mask][num] != null) return memo[mask][num]\n let res = dp(mask, num - 1)\n if (!bad.has(num) && (mask | bm[num]) === mask) {\n res += dp(mask ^ bm[num], num - 1) * (cnt[num] || 0n)\n }\n if (memo[mask] == null) memo[mask] = {}\n return (memo[mask][num] = res % mod)\n }\n\n return ((dp(1023, 30) - 1n) * pow(2n, cnt[1] || 0n, mod)) % mod\n}\n\nfunction pow(base, exp, mod) {\n if (exp === 0n) return 1n\n // console.log(base, mod)\n base %= mod\n let res = pow(base, exp / 2n, mod)\n res = (res * res) % mod\n if (exp & 1n) res = (res * base) % mod\n return res\n}\n\nconst numberOfGoodSubsets = function (nums) {\n const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n const n = nums.length,\n cnt = {},\n mod = BigInt(1e9 + 7)\n const bm = []\n for (let num of nums) {\n cnt[num] = (cnt[num] || 0n) + 1n\n }\n for (let i = 0; i < 31; i++) {\n let tmp = 0\n for (let j = 0, m = primes.length; j < m; j++) {\n const p = primes[j]\n if (i % p === 0) tmp += 1 << j\n }\n bm[i] = tmp\n }\n const bad = new Set([4, 8, 9, 12, 16, 18, 20, 24, 25, 27, 28])\n const memo = {}\n\n function dp(mask, num) {\n if (num === 1) return 1n\n if (memo[mask] && memo[mask][num] != null) return memo[mask][num]\n let res = dp(mask, num - 1)\n if (!bad.has(num) && (mask | bm[num]) === mask) {\n res += dp(mask ^ bm[num], num - 1) * (cnt[num] || 0n)\n }\n if (memo[mask] == null) memo[mask] = {}\n return (memo[mask][num] = res % mod)\n }\n\n return ((dp(1023, 30) - 1n) * pow(2n, cnt[1] || 0n, mod)) % mod\n}\n\nfunction pow(base, exp, mod) {\n if (exp === 0n) return 1n\n // console.log(base, mod)\n base %= mod\n let res = pow(base, exp / 2n, mod)\n res = (res * res) % mod\n if (exp & 1n) res = (res * base) % mod\n return res\n}"
] |
|
1,995 | count-special-quadruplets | [
"N is very small, how can we use that?",
"Can we check every possible quadruplet?"
] | /**
* @param {number[]} nums
* @return {number}
*/
var countQuadruplets = function(nums) {
}; | Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:
nums[a] + nums[b] + nums[c] == nums[d], and
a < b < c < d
Example 1:
Input: nums = [1,2,3,6]
Output: 1
Explanation: The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.
Example 2:
Input: nums = [3,3,6,4,5]
Output: 0
Explanation: There are no such quadruplets in [3,3,6,4,5].
Example 3:
Input: nums = [1,1,1,3,5]
Output: 4
Explanation: The 4 quadruplets that satisfy the requirement are:
- (0, 1, 2, 3): 1 + 1 + 1 == 3
- (0, 1, 3, 4): 1 + 1 + 3 == 5
- (0, 2, 3, 4): 1 + 1 + 3 == 5
- (1, 2, 3, 4): 1 + 1 + 3 == 5
Constraints:
4 <= nums.length <= 50
1 <= nums[i] <= 100
| Easy | [
"array",
"enumeration"
] | [
"const countQuadruplets = function(nums) {\n let res = 0\n for(let a = 0, n = nums.length; a < n - 3; a++) {\n for(let b = a + 1; b < n - 2; b++) {\n for(let c = b + 1; c < n - 1; c++) {\n for(let d = c + 1; d < n; d++) {\n if(nums[a] + nums[b] + nums[c] === nums[d]) res++\n }\n }\n }\n }\n \n \n return res\n \n};"
] |
|
1,996 | the-number-of-weak-characters-in-the-game | [
"Sort the array on the basis of the attack values and group characters with the same attack together. How can you use these groups?",
"Characters in one group will always have a lesser attack value than the characters of the next group. Hence, we will only need to check if there is a higher defense value present in the next groups."
] | /**
* @param {number[][]} properties
* @return {number}
*/
var numberOfWeakCharacters = function(properties) {
}; | You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game.
A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei.
Return the number of weak characters.
Example 1:
Input: properties = [[5,5],[6,3],[3,6]]
Output: 0
Explanation: No character has strictly greater attack and defense than the other.
Example 2:
Input: properties = [[2,2],[3,3]]
Output: 1
Explanation: The first character is weak because the second character has a strictly greater attack and defense.
Example 3:
Input: properties = [[1,5],[10,4],[4,3]]
Output: 1
Explanation: The third character is weak because the second character has a strictly greater attack and defense.
Constraints:
2 <= properties.length <= 105
properties[i].length == 2
1 <= attacki, defensei <= 105
| Medium | [
"array",
"stack",
"greedy",
"sorting",
"monotonic-stack"
] | [
"const numberOfWeakCharacters = function(properties) {\n const props = properties, n = props.length, maxDefFromRight = Array(n)\n props.sort((a, b) => a[0] - b[0])\n for(let max = 0, i = n - 1; i >= 0; i--) {\n max = Math.max(max, props[i][1])\n maxDefFromRight[i] = max\n }\n let res = 0\n \n for(let i = 0; i < n; i++) {\n const cur = props[i]\n let l = i, r = n\n while(l < r) {\n const mid = l + Math.floor((r - l) / 2)\n if(props[mid][0] > props[i][0]) r = mid\n else l = mid + 1\n }\n \n if(l < n && maxDefFromRight[l] > props[i][1]) {\n res++ \n }\n }\n \n return res\n};",
"const numberOfWeakCharacters = function(properties) {\n properties.sort((a, b) => a[0] - b[0] || b[1] - a[1])\n let stack = [], res = 0\n\n for(let i = 0, n = properties.length; i < n; i++) {\n while(stack.length && stack[stack.length - 1] < properties[i][1]) {\n stack.pop()\n res++\n }\n stack.push(properties[i][1])\n }\n \n return res\n};",
"const numberOfWeakCharacters = function(properties) {\n if (properties == null || properties.length == 0) {\n return 0;\n }\n properties.sort((o1, o2) => {\n if (o1[0] == o2[0]) {\n return o1[1] - o2[1];\n }\n return o1[0] - o2[0];\n });\n const { max } = Math\n let mmax = Array(1e5 + 10).fill( 0);\n let ans = 0;\n let n = properties.length;\n for (let i = n - 1; i >= 0; i--) mmax[properties[i][0]] = max(properties[i][1], mmax[properties[i][0]]);\n for (let i = 1e5; i >= 1; i--) mmax[i] = max(mmax[i], mmax[i + 1]);\n for (let i = 0; i < n; i++) {\n if (mmax[properties[i][0] + 1] > properties[i][1]) ans++;\n }\n return ans;\n};",
"const numberOfWeakCharacters = function(properties) {\n properties.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])\n let max = -Infinity, res = 0\n for(let n = properties.length, i = n - 1; i >= 0; i--) {\n const [a, d] = properties[i]\n if(d < max) res++\n max = Math.max(max, d)\n }\n \n return res\n};"
] |
|
1,997 | first-day-where-you-have-been-in-all-the-rooms | [
"The only way to get to room i+1 is when you are visiting room i and room i has been visited an even number of times.",
"After visiting room i an odd number of times, you are required to visit room nextVisit[i] where nextVisit[i] <= i. It takes a fixed amount of days for you to come back from room nextVisit[i] to room i. Then, you have visited room i even number of times.nextVisit[i]",
"Can you use Dynamic Programming to avoid recomputing the number of days it takes to visit room i from room nextVisit[i]?"
] | /**
* @param {number[]} nextVisit
* @return {number}
*/
var firstDayBeenInAllRooms = function(nextVisit) {
}; | There are n rooms you need to visit, labeled from 0 to n - 1. Each day is labeled, starting from 0. You will go in and visit one room a day.
Initially on day 0, you visit room 0. The order you visit the rooms for the coming days is determined by the following rules and a given 0-indexed array nextVisit of length n:
Assuming that on a day, you visit room i,
if you have been in room i an odd number of times (including the current visit), on the next day you will visit a room with a lower or equal room number specified by nextVisit[i] where 0 <= nextVisit[i] <= i;
if you have been in room i an even number of times (including the current visit), on the next day you will visit room (i + 1) mod n.
Return the label of the first day where you have been in all the rooms. It can be shown that such a day exists. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: nextVisit = [0,0]
Output: 2
Explanation:
- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.
On the next day you will visit room nextVisit[0] = 0
- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.
On the next day you will visit room (0 + 1) mod 2 = 1
- On day 2, you visit room 1. This is the first day where you have been in all the rooms.
Example 2:
Input: nextVisit = [0,0,2]
Output: 6
Explanation:
Your room visiting order for each day is: [0,0,1,0,0,1,2,...].
Day 6 is the first day where you have been in all the rooms.
Example 3:
Input: nextVisit = [0,1,2,0]
Output: 6
Explanation:
Your room visiting order for each day is: [0,0,1,1,2,2,3,...].
Day 6 is the first day where you have been in all the rooms.
Constraints:
n == nextVisit.length
2 <= n <= 105
0 <= nextVisit[i] <= i
| Medium | [
"array",
"dynamic-programming"
] | [
"const firstDayBeenInAllRooms = function(nextVisit) {\n const P = 1e9+7;\n const n = nextVisit.length;\n const f = Array(n).fill(0) ;\n f[0] = 0;\n\n for (let i = 1; i < n; i++) {\n f[i] = ((\n (2 * f[i - 1]) % P\n + P - f[nextVisit[i - 1]]) % P + 2) % P;\n }\n\n return f[n - 1];\n};",
"const firstDayBeenInAllRooms = function(nextVisit) {\n const mod = 1e9 + 7\n const n = nextVisit.length\n const dp = Array(n).fill(0)\n for(let i = 1; i < n; i++) {\n // i - 1 ---> nextVisit[i - 1] ---> i - 1 ---> i\n dp[i] = (dp[i - 1] + 1 + dp[i - 1] - dp[nextVisit[i - 1]] + 1 + mod) % mod\n }\n \n return dp[n - 1]\n};"
] |
|
1,998 | gcd-sort-of-an-array | [
"Can we build a graph with all the prime numbers and the original array?",
"We can use union-find to determine which indices are connected (i.e., which indices can be swapped)."
] | /**
* @param {number[]} nums
* @return {boolean}
*/
var gcdSort = function(nums) {
}; | You are given an integer array nums, and you can perform the following operation any number of times on nums:
Swap the positions of two elements nums[i] and nums[j] if gcd(nums[i], nums[j]) > 1 where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j].
Return true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise.
Example 1:
Input: nums = [7,21,3]
Output: true
Explanation: We can sort [7,21,3] by performing the following operations:
- Swap 7 and 21 because gcd(7,21) = 7. nums = [21,7,3]
- Swap 21 and 3 because gcd(21,3) = 3. nums = [3,7,21]
Example 2:
Input: nums = [5,2,6,2]
Output: false
Explanation: It is impossible to sort the array because 5 cannot be swapped with any other element.
Example 3:
Input: nums = [10,5,9,3,15]
Output: true
We can sort [10,5,9,3,15] by performing the following operations:
- Swap 10 and 15 because gcd(10,15) = 5. nums = [15,5,9,3,10]
- Swap 15 and 3 because gcd(15,3) = 3. nums = [3,5,9,15,10]
- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,10,15]
Constraints:
1 <= nums.length <= 3 * 104
2 <= nums[i] <= 105
| Hard | [
"array",
"math",
"union-find",
"sorting",
"number-theory"
] | [
"const gcdSort = function(nums) {\n const spf = Array(nums.length).fill(0)\n let maxNum = Math.max(...nums);\n sieve(maxNum);\n\n const uf = new UnionFind(maxNum+1);\n for (let x of nums) {\n for (let f of getFactors(x)) uf.union(f, x); \n }\n\n\n const sortedArr = nums.slice();\n sortedArr.sort((a, b) => a - b)\n\n for (let i = 0; i < nums.length; ++i) {\n let pu = uf.find(sortedArr[i]);\n let pv = uf.find(nums[i]);\n if (pu != pv) return false; // can't swap nums[i] with sortedArr[i]\n }\n return true;\n \n function sieve( n) { // O(Nlog(logN)) ~ O(N)\n for (let i = 2; i <= n; ++i) spf[i] = i;\n for (let i = 2; i * i <= n; i++) {\n if (spf[i] != i) continue; // skip if `i` is not a prime number\n for (let j = i * i; j <= n; j += i) {\n if (spf[j] == j) { // marking spf[j] if it is not previously marked\n spf[j] = i;\n }\n }\n }\n }\n \n function getFactors(n) { // O(logN)\n const factors = [];\n while (n > 1) {\n factors.push(spf[n]);\n n = ~~(n /spf[n]);\n }\n return factors;\n }\n};\n\nfunction gcd( x, y) {\n return y == 0 ? x : gcd(y, x % y);\n}\n\nclass UnionFind {\n constructor(n) {\n this.parent = [];\n for (let i = 0; i < n; i++) this.parent[i] = i;\n }\n find(x) {\n if (x == this.parent[x]) return x;\n return this.parent[x] = this.find(this.parent[x]); // Path compression\n }\n union( u, v) {\n let pu = this.find(u), pv = this.find(v);\n if (pu != pv) this.parent[pu] = pv;\n }\n};"
] |
|
2,000 | reverse-prefix-of-word | [
"Find the first index where ch appears.",
"Find a way to reverse a substring of word."
] | /**
* @param {string} word
* @param {character} ch
* @return {string}
*/
var reversePrefix = function(word, ch) {
}; | Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.
For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".
Return the resulting string.
Example 1:
Input: word = "abcdefd", ch = "d"
Output: "dcbaefd"
Explanation: The first occurrence of "d" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".
Example 2:
Input: word = "xyxzxe", ch = "z"
Output: "zxyxxe"
Explanation: The first and only occurrence of "z" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".
Example 3:
Input: word = "abcd", ch = "z"
Output: "abcd"
Explanation: "z" does not exist in word.
You should not do any reverse operation, the resulting string is "abcd".
Constraints:
1 <= word.length <= 250
word consists of lowercase English letters.
ch is a lowercase English letter.
| Easy | [
"two-pointers",
"string"
] | [
"const reversePrefix = function(word, ch) {\n const arr = word.split('')\n let idx = -1\n for(let i = 0; i < arr.length; i++) {\n if(arr[i] === ch) {\n idx = i\n break\n }\n }\n if(idx !== -1) {\n const pre = arr.slice(0, idx + 1)\n const remain = arr.slice(idx + 1)\n return pre.reverse().concat(remain).join('')\n }\n return word\n};"
] |
|
2,001 | number-of-pairs-of-interchangeable-rectangles | [
"Store the rectangle height and width ratio in a hashmap.",
"Traverse the ratios, and for each ratio, use the frequency of the ratio to add to the total pair count."
] | /**
* @param {number[][]} rectangles
* @return {number}
*/
var interchangeableRectangles = function(rectangles) {
}; | You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle.
Two rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division).
Return the number of pairs of interchangeable rectangles in rectangles.
Example 1:
Input: rectangles = [[4,8],[3,6],[10,20],[15,30]]
Output: 6
Explanation: The following are the interchangeable pairs of rectangles by index (0-indexed):
- Rectangle 0 with rectangle 1: 4/8 == 3/6.
- Rectangle 0 with rectangle 2: 4/8 == 10/20.
- Rectangle 0 with rectangle 3: 4/8 == 15/30.
- Rectangle 1 with rectangle 2: 3/6 == 10/20.
- Rectangle 1 with rectangle 3: 3/6 == 15/30.
- Rectangle 2 with rectangle 3: 10/20 == 15/30.
Example 2:
Input: rectangles = [[4,5],[7,8]]
Output: 0
Explanation: There are no interchangeable pairs of rectangles.
Constraints:
n == rectangles.length
1 <= n <= 105
rectangles[i].length == 2
1 <= widthi, heighti <= 105
| Medium | [
"array",
"hash-table",
"math",
"counting",
"number-theory"
] | [
"const interchangeableRectangles = function(rectangles) {\n const count = new Map()\n\n for (const [w, h] of rectangles) {\n count.set( w / h, 1 + (count.get( w / h) || 0))\n }\n\n let res = 0\n for (let c of count.values()) {\n if(c > 1) res += ((c * (c - 1)) / 2)\n }\n return res \n};"
] |
|
2,002 | maximum-product-of-the-length-of-two-palindromic-subsequences | [
"Could you generate all possible pairs of disjoint subsequences?",
"Could you find the maximum length palindrome in each subsequence for a pair of disjoint subsequences?"
] | /**
* @param {string} s
* @return {number}
*/
var maxProduct = function(s) {
}; | Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index.
Return the maximum possible product of the lengths of the two palindromic subsequences.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.
Example 1:
Input: s = "leetcodecom"
Output: 9
Explanation: An optimal solution is to choose "ete" for the 1st subsequence and "cdc" for the 2nd subsequence.
The product of their lengths is: 3 * 3 = 9.
Example 2:
Input: s = "bb"
Output: 1
Explanation: An optimal solution is to choose "b" (the first character) for the 1st subsequence and "b" (the second character) for the 2nd subsequence.
The product of their lengths is: 1 * 1 = 1.
Example 3:
Input: s = "accbcaxxcxx"
Output: 25
Explanation: An optimal solution is to choose "accca" for the 1st subsequence and "xxcxx" for the 2nd subsequence.
The product of their lengths is: 5 * 5 = 25.
Constraints:
2 <= s.length <= 12
s consists of lowercase English letters only.
| Medium | [
"string",
"dynamic-programming",
"backtracking",
"bit-manipulation",
"bitmask"
] | [
"var maxProduct = function(s) {\n const n = s.length;\n let max = 0;\n for (let i = 0; i < (1 << n); i++) {\n let n0 = palindromic(i, s, true);\n if (n0 === 0) continue;\n for (let j = 0; j < (1 << n); j++) {\n if ((i & j) > 0) continue;\n max = Math.max(palindromic(j, s) * n0, max);\n }\n }\n return max; \n};\nfunction palindromic( i, s) {\n const n = s.length;\n let sub = \"\";\n for (let x = 0; x < n; x++) {\n if (i & (1 << x)) sub += s[x]\n }\n let len = sub.length;\n for (let i = 0; i < len; i++) {\n if (sub[i] !== sub[len - i - 1]) return 0;\n }\n return len;\n}",
"const maxProduct = function(s) {\n const s1 = [], s2 = [], n = s.length\n let res = 0\n dfs(0)\n return res\n \n function dfs(idx) {\n if(idx === n) {\n if(isPalindromic(s1) && isPalindromic(s2)) {\n res = Math.max(res, s1.length * s2.length)\n }\n return\n }\n const ch = s[idx]\n s1.push(ch)\n dfs(idx + 1)\n s1.pop()\n \n s2.push(ch)\n dfs(idx + 1)\n s2.pop()\n \n dfs(idx + 1)\n }\n function isPalindromic(arr) {\n let l = 0, r = arr.length - 1\n while(l < r) {\n if(arr[l] === arr[r]) {\n l++\n r--\n } else {\n return false\n }\n }\n return true\n }\n};"
] |
|
2,003 | smallest-missing-genetic-value-in-each-subtree | [
"If the subtree doesn't contain 1, then the missing value will always be 1.",
"What data structure allows us to dynamically update the values that are currently not present?"
] | /**
* @param {number[]} parents
* @param {number[]} nums
* @return {number[]}
*/
var smallestMissingValueSubtree = function(parents, nums) {
}; | There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1.
There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i.
Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i.
The subtree rooted at a node x contains node x and all of its descendant nodes.
Example 1:
Input: parents = [-1,0,0,2], nums = [1,2,3,4]
Output: [5,1,1,1]
Explanation: The answer for each subtree is calculated as follows:
- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.
- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.
- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.
- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.
Example 2:
Input: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]
Output: [7,1,1,4,2,1]
Explanation: The answer for each subtree is calculated as follows:
- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.
- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.
- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.
- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.
- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.
- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.
Example 3:
Input: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]
Output: [1,1,1,1,1,1,1]
Explanation: The value 1 is missing from all the subtrees.
Constraints:
n == parents.length == nums.length
2 <= n <= 105
0 <= parents[i] <= n - 1 for i != 0
parents[0] == -1
parents represents a valid tree.
1 <= nums[i] <= 105
Each nums[i] is distinct.
| Hard | [
"dynamic-programming",
"tree",
"depth-first-search",
"union-find"
] | [
"const smallestMissingValueSubtree = function(parents, nums) {\n let n = parents.length;\n const ans = new Array(n).fill(0);\n const fn = new Array(100010).fill(0);\n const tree = [];\n const nums1 = nums;\n for(let idx=0;idx<n;idx++) {\n tree.push([]);\n }\n for (let idx=1;idx<n;idx++) {\n tree[parents[idx]].push(idx);\n }\n let nodeIdx = 0;\n search(0,0);\n return ans;\n \n function search( root, rec) {\n let pos = 1;\n for(let next of tree[root]) {\n pos = Math.max(pos, search(next, nodeIdx));\n }\n nodeIdx++;\n fn[nums1[root]] = nodeIdx;\n while(fn[pos]!=0 && fn[pos]>rec && fn[pos]<=nodeIdx) {\n pos++;\n }\n ans[root] = pos;\n return pos;\n }\n};"
] |
|
2,006 | count-number-of-pairs-with-absolute-difference-k | [
"Can we check every possible pair?",
"Can we use a nested for loop to solve this problem?"
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var countKDifference = function(nums, k) {
}; | Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.
The value of |x| is defined as:
x if x >= 0.
-x if x < 0.
Example 1:
Input: nums = [1,2,2,1], k = 1
Output: 4
Explanation: The pairs with an absolute difference of 1 are:
- [1,2,2,1]
- [1,2,2,1]
- [1,2,2,1]
- [1,2,2,1]
Example 2:
Input: nums = [1,3], k = 3
Output: 0
Explanation: There are no pairs with an absolute difference of 3.
Example 3:
Input: nums = [3,2,1,5,4], k = 2
Output: 3
Explanation: The pairs with an absolute difference of 2 are:
- [3,2,1,5,4]
- [3,2,1,5,4]
- [3,2,1,5,4]
Constraints:
1 <= nums.length <= 200
1 <= nums[i] <= 100
1 <= k <= 99
| Easy | [
"array",
"hash-table",
"counting"
] | [
"const countKDifference = function(nums, k) {\n const hash = {}\n let res = 0\n for(let i = 0; i < nums.length; i++) {\n const cur = nums[i]\n if(hash[cur + k]) res += hash[cur + k]\n if(hash[cur - k]) res += hash[cur - k]\n\n if(hash[cur] == null) hash[cur] = 0\n hash[cur]++\n } \n return res\n};"
] |
|
2,007 | find-original-array-from-doubled-array | [
"If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty.",
"Which element is guaranteed to not be a doubled value? It is the smallest element.",
"After removing the smallest element and its double from changed, is there another number that is guaranteed to not be a doubled value?"
] | /**
* @param {number[]} changed
* @return {number[]}
*/
var findOriginalArray = function(changed) {
}; | An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array.
Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.
Example 1:
Input: changed = [1,3,4,2,6,8]
Output: [1,3,4]
Explanation: One possible original array could be [1,3,4]:
- Twice the value of 1 is 1 * 2 = 2.
- Twice the value of 3 is 3 * 2 = 6.
- Twice the value of 4 is 4 * 2 = 8.
Other original arrays could be [4,3,1] or [3,1,4].
Example 2:
Input: changed = [6,3,0,1]
Output: []
Explanation: changed is not a doubled array.
Example 3:
Input: changed = [1]
Output: []
Explanation: changed is not a doubled array.
Constraints:
1 <= changed.length <= 105
0 <= changed[i] <= 105
| Medium | [
"array",
"hash-table",
"greedy",
"sorting"
] | [
" const findOriginalArray = function(changed) {\n const n = changed.length, res = [], { abs } = Math\n if(n % 2 === 1 || n === 0) return res\n const hash = {}\n for(let e of changed) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n const keys = Object.keys(hash)\n keys.sort((a, b) => abs(a) - abs(b))\n\n for(let k of keys) {\n if(hash[k] > (hash[k * 2] || 0)) return []\n for(let i = 0; i < hash[k]; i++) {\n res.push(k)\n hash[2 * k]--\n }\n }\n\n return res\n};",
" const findOriginalArray = function(changed) {\n const n = changed.length, res = []\n if(n % 2 === 1 || n === 0) return res\n const hash = {}\n for(let e of changed) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n changed.sort((a, b) => a - b)\n\n for(let i = 0, len = n; i < len; i++) {\n const cur = changed[i], dVal = cur * 2\n if (cur === 0 && hash[cur] % 2 === 1) continue\n if(hash[dVal] && hash[cur]) {\n res.push(cur)\n hash[dVal]--\n hash[cur]--\n }\n }\n return res.length === n / 2 ? res : []\n};"
] |
|
2,008 | maximum-earnings-from-taxi | [
"Can we sort the array to help us solve the problem?",
"We can use dynamic programming to keep track of the maximum at each position."
] | /**
* @param {number} n
* @param {number[][]} rides
* @return {number}
*/
var maxTaxiEarnings = function(n, rides) {
}; | There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi.
The passengers are represented by a 0-indexed 2D integer array rides, where rides[i] = [starti, endi, tipi] denotes the ith passenger requesting a ride from point starti to point endi who is willing to give a tipi dollar tip.
For each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive at most one passenger at a time.
Given n and rides, return the maximum number of dollars you can earn by picking up the passengers optimally.
Note: You may drop off a passenger and pick up a different passenger at the same point.
Example 1:
Input: n = 5, rides = [[2,5,4],[1,5,1]]
Output: 7
Explanation: We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars.
Example 2:
Input: n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]
Output: 20
Explanation: We will pick up the following passengers:
- Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars.
- Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars.
- Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars.
We earn 9 + 5 + 6 = 20 dollars in total.
Constraints:
1 <= n <= 105
1 <= rides.length <= 3 * 104
rides[i].length == 3
1 <= starti < endi <= n
1 <= tipi <= 105
| Medium | [
"array",
"binary-search",
"dynamic-programming",
"sorting"
] | [
"const maxTaxiEarnings = function(n, rides) {\n const { max } = Math\n const rideStartAt = Array.from({length: n}, () => []);\n for (let ride of rides) {\n let s = ride[0], e = ride[1], t = ride[2];\n rideStartAt[s].push([e, e - s + t]); // [end, dollar]\n }\n const dp = Array(n+1).fill(0);\n for (let i = n-1; i >= 1; --i) {\n for (let [e, d] of rideStartAt[i]) {\n dp[i] = max(dp[i], dp[e] + d);\n }\n dp[i] = max(dp[i], dp[i + 1]);\n }\n return dp[1];\n};",
"const maxTaxiEarnings = function(n, rides) {\n const size = rides.length\n rides.sort((a, b) => a[1] - b[1])\n const dp = [[0,0]]\n for(const [s, e, t] of rides) {\n const cur = bs(dp, s) + (e - s + t)\n if(cur > dp[dp.length - 1][1]) {\n dp.push([e, cur])\n }\n }\n return dp[dp.length - 1][1]\n\n function bs(arr, t) {\n let l = 0, r = arr.length - 1\n while(l < r) {\n const mid = r - ((r - l) >> 1)\n if(arr[mid][0] > t) r = mid - 1\n else l = mid\n }\n // console.log(arr, t, l)\n return arr[l][1]\n }\n};"
] |
|
2,009 | minimum-number-of-operations-to-make-array-continuous | [
"Sort the array.",
"For every index do a binary search to get the possible right end of the window and calculate the possible answer."
] | /**
* @param {number[]} nums
* @return {number}
*/
var minOperations = function(nums) {
}; | You are given an integer array nums. In one operation, you can replace any element in nums with any integer.
nums is considered continuous if both of the following conditions are fulfilled:
All elements in nums are unique.
The difference between the maximum element and the minimum element in nums equals nums.length - 1.
For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous.
Return the minimum number of operations to make nums continuous.
Example 1:
Input: nums = [4,2,5,3]
Output: 0
Explanation: nums is already continuous.
Example 2:
Input: nums = [1,2,3,5,6]
Output: 1
Explanation: One possible solution is to change the last element to 4.
The resulting array is [1,2,3,5,4], which is continuous.
Example 3:
Input: nums = [1,10,100,1000]
Output: 3
Explanation: One possible solution is to:
- Change the second element to 2.
- Change the third element to 3.
- Change the fourth element to 4.
The resulting array is [1,2,3,4], which is continuous.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
| Hard | [
"array",
"binary-search"
] | [
"const minOperations = function(nums) {\n const N = nums.length;\n if(N === 1) return 0;\n nums.sort((a, b) => a - b)\n let M = 1;\n for(let i = 1; i < N; i++) {\n if(nums[i] != nums[i-1]) nums[M++] = nums[i];\n }\n \n let j = 0;\n let res = N;\n for(let i = 0; i < M; i++) {\n // let `j` point to the first element that is out of range -- `> nums[i] + N - 1`.\n while(j < M && nums[j] <= N + nums[i] - 1) j++;\n // The length of this subarray is `j - i`. \n // We need to replace `N - (j - i)` elements to make it continuous.\n res = Math.min(res, N - (j - i));\n }\n \n return res;\n};"
] |
|
2,011 | final-value-of-variable-after-performing-operations | [
"There are only two operations to keep track of.",
"Use a variable to store the value after each operation."
] | /**
* @param {string[]} operations
* @return {number}
*/
var finalValueAfterOperations = function(operations) {
}; | There is a programming language with only four operations and one variable X:
++X and X++ increments the value of the variable X by 1.
--X and X-- decrements the value of the variable X by 1.
Initially, the value of X is 0.
Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.
Example 1:
Input: operations = ["--X","X++","X++"]
Output: 1
Explanation: The operations are performed as follows:
Initially, X = 0.
--X: X is decremented by 1, X = 0 - 1 = -1.
X++: X is incremented by 1, X = -1 + 1 = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
Example 2:
Input: operations = ["++X","++X","X++"]
Output: 3
Explanation: The operations are performed as follows:
Initially, X = 0.
++X: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
X++: X is incremented by 1, X = 2 + 1 = 3.
Example 3:
Input: operations = ["X++","++X","--X","X--"]
Output: 0
Explanation: The operations are performed as follows:
Initially, X = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
--X: X is decremented by 1, X = 2 - 1 = 1.
X--: X is decremented by 1, X = 1 - 1 = 0.
Constraints:
1 <= operations.length <= 100
operations[i] will be either "++X", "X++", "--X", or "X--".
| Easy | [
"array",
"string",
"simulation"
] | [
"const finalValueAfterOperations = function(operations) {\n let res = 0\n for(let op of operations) {\n if(op.indexOf('++') !== -1) res++\n else res--\n }\n \n return res\n};"
] |
|
2,012 | sum-of-beauty-in-the-array | [
"Use suffix/prefix arrays.",
"prefix[i] records the maximum value in range (0, i - 1) inclusive.",
"suffix[i] records the minimum value in range (i + 1, n - 1) inclusive."
] | /**
* @param {number[]} nums
* @return {number}
*/
var sumOfBeauties = function(nums) {
}; | You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals:
2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1.
1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not satisfied.
0, if none of the previous conditions holds.
Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.
Example 1:
Input: nums = [1,2,3]
Output: 2
Explanation: For each index i in the range 1 <= i <= 1:
- The beauty of nums[1] equals 2.
Example 2:
Input: nums = [2,4,6,4]
Output: 1
Explanation: For each index i in the range 1 <= i <= 2:
- The beauty of nums[1] equals 1.
- The beauty of nums[2] equals 0.
Example 3:
Input: nums = [3,2,1]
Output: 0
Explanation: For each index i in the range 1 <= i <= 1:
- The beauty of nums[1] equals 0.
Constraints:
3 <= nums.length <= 105
1 <= nums[i] <= 105
| Medium | [
"array"
] | [
"const sumOfBeauties = function(nums) {\n const n = nums.length\n const maxArr = Array(n).fill(0), minArr = Array(n).fill(0)\n let max = -Infinity, min = Infinity\n for(let i = 0; i < n; i++) {\n const tmp = Math.max(max, nums[i])\n if(tmp > max) max = tmp\n maxArr[i] = max\n }\n \n for(let i = n - 1; i >= 0; i--) {\n const tmp = Math.min(min, nums[i])\n if(tmp < min) min = tmp\n minArr[i] = min\n }\n let res = 0\n \n for(let i = 1; i < n - 1; i++) {\n if(nums[i] > maxArr[i - 1] && nums[i] < minArr[i + 1]) res += 2\n else if(nums[i] > nums[i - 1] && nums[i] < nums[i + 1]) res += 1\n }\n \n return res\n};"
] |
|
2,013 | detect-squares | [
"Maintain the frequency of all the points in a hash map.",
"Traverse the hash map and if any point has the same y-coordinate as the query point, consider this point and the query point to form one of the horizontal lines of the square."
] |
var DetectSquares = function() {
};
/**
* @param {number[]} point
* @return {void}
*/
DetectSquares.prototype.add = function(point) {
};
/**
* @param {number[]} point
* @return {number}
*/
DetectSquares.prototype.count = function(point) {
};
/**
* Your DetectSquares object will be instantiated and called as such:
* var obj = new DetectSquares()
* obj.add(point)
* var param_2 = obj.count(point)
*/ | You are given a stream of points on the X-Y plane. Design an algorithm that:
Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points.
Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area.
An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis.
Implement the DetectSquares class:
DetectSquares() Initializes the object with an empty data structure.
void add(int[] point) Adds a new point point = [x, y] to the data structure.
int count(int[] point) Counts the number of ways to form axis-aligned squares with point point = [x, y] as described above.
Example 1:
Input
["DetectSquares", "add", "add", "add", "count", "count", "add", "count"]
[[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]]
Output
[null, null, null, null, 1, 0, null, 2]
Explanation
DetectSquares detectSquares = new DetectSquares();
detectSquares.add([3, 10]);
detectSquares.add([11, 2]);
detectSquares.add([3, 2]);
detectSquares.count([11, 10]); // return 1. You can choose:
// - The first, second, and third points
detectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure.
detectSquares.add([11, 2]); // Adding duplicate points is allowed.
detectSquares.count([11, 10]); // return 2. You can choose:
// - The first, second, and third points
// - The first, third, and fourth points
Constraints:
point.length == 2
0 <= x, y <= 1000
At most 3000 calls in total will be made to add and count.
| Medium | [
"array",
"hash-table",
"design",
"counting"
] | [
"const DetectSquares = function() {\n this.pts = []\n this.ptsCnt = {}\n};\n\n\nDetectSquares.prototype.add = function(point) {\n this.pts.push(point)\n const key = `${point[0]},${point[1]}`\n this.ptsCnt[key] = (this.ptsCnt[key] || 0) + 1\n};\n\n\nDetectSquares.prototype.count = function(point) {\n let res = 0\n const [px, py] = point\n for(const [x, y] of this.pts) {\n if(px === x || py === y || Math.abs(px - x) !== Math.abs(py - y)) {\n continue\n }\n res += (this.ptsCnt[`${px},${y}`] || 0) * (this.ptsCnt[`${x},${py}`] || 0)\n }\n \n return res\n};",
"var DetectSquares = function() {\n this.xMap = new Map();\n this.yMap = new Map();\n};\n\n\nDetectSquares.prototype.add = function(point) {\n const [ x, y ] = point;\n\n // X-map\n if (this.xMap.has(x)) {\n const xMap = this.xMap.get(x);\n\n if (xMap.has(y)) {\n xMap.set(y, xMap.get(y) + 1);\n } else {\n xMap.set(y, 1);\n }\n } else {\n const countMap = new Map();\n countMap.set(y, 1);\n this.xMap.set(x, countMap);\n }\n\n // Y-map\n if (this.yMap.has(y)) {\n const yMap = this.yMap.get(y);\n\n if (yMap.has(x)) {\n yMap.set(x, yMap.get(x) + 1);\n } else {\n yMap.set(x, 1);\n }\n } else {\n const countMap = new Map();\n countMap.set(x, 1);\n this.yMap.set(y, countMap);\n }\n};\n\n\nDetectSquares.prototype.count = function(point) {\n const [ x, y ] = point;\n let ans = 0;\n\n if (this.xMap.has(x) && this.yMap.has(y)) {\n for (const y2 of this.xMap.get(x).keys()) {\n if (y === y2) {\n continue;\n }\n\n // Find parallel\n const sideLen = Math.abs(y - y2);\n const possibleX = [ x - sideLen, x + sideLen];\n\n for (const px of possibleX) {\n if (this.yMap.get(y).has(px) && this.xMap.has(px) && this.xMap.get(px).has(y2)) {\n ans += this.xMap.get(x).get(y2) * this.yMap.get(y).get(px)\n * this.xMap.get(px).get(y2);\n }\n }\n }\n }\n\n return ans;\n};"
] |
|
2,014 | longest-subsequence-repeated-k-times | [
"The length of the longest subsequence does not exceed n/k. Do you know why?",
"Find the characters that could be included in the potential answer. A character occurring more than or equal to k times can be used in the answer up to (count of the character / k) times.",
"Try all possible candidates in reverse lexicographic order, and check the string for the subsequence condition."
] | /**
* @param {string} s
* @param {number} k
* @return {string}
*/
var longestSubsequenceRepeatedK = function(s, k) {
}; | You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times.
For example, "bba" is repeated 2 times in the string "bababcba", because the string "bbabba", constructed by concatenating "bba" 2 times, is a subsequence of the string "bababcba".
Return the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.
Example 1:
Input: s = "letsleetcode", k = 2
Output: "let"
Explanation: There are two longest subsequences repeated 2 times: "let" and "ete".
"let" is the lexicographically largest one.
Example 2:
Input: s = "bb", k = 2
Output: "b"
Explanation: The longest subsequence repeated 2 times is "b".
Example 3:
Input: s = "ab", k = 2
Output: ""
Explanation: There is no subsequence repeated 2 times. Empty string is returned.
Constraints:
n == s.length
2 <= n, k <= 2000
2 <= n < k * 8
s consists of lowercase English letters.
| Hard | [
"string",
"backtracking",
"greedy",
"counting",
"enumeration"
] | [
"const longestSubsequenceRepeatedK = function(s, k) {\n const n = s.length, a = 'a'.charCodeAt(0)\n \n let res = ''\n const q = ['']\n \n while(q.length) {\n const size = q.length\n for(let i = 0; i < size; i++) {\n const cur = q.shift()\n for(let j = 0; j < 26; j++) {\n const next = cur + String.fromCharCode(a + j)\n if(isSub(s, next, k)) {\n res = next\n q.push(next)\n }\n }\n \n }\n }\n \n return res\n \n \n function isSub(s, p, k) {\n let repeated = 0\n for(let i = 0, j = 0, n = s.length, m = p.length; i < n; i++) {\n if(s[i] === p[j]) {\n j++\n if(j === m) {\n repeated++\n j = 0\n if(repeated === k) {\n return true\n }\n }\n }\n }\n \n return false\n }\n};",
"var longestSubsequenceRepeatedK = function(s, k) {\n // Max length of the subsequence can be determined by the length of the string and k\n const maxLen = Math.floor(s.length / k);\n\n // Find all possible characters that can appear in the subsequence (characters must appear at\n // least k times in s)\n const charCount = new Map();\n const possibleChars = []\n\n for (const char of s) {\n if (charCount.has(char)) {\n charCount.set(char, charCount.get(char) + 1);\n } else {\n charCount.set(char, 1);\n }\n }\n\n for (const char of charCount.keys()) {\n if (charCount.get(char) >= k) {\n possibleChars.push(char);\n }\n }\n\n // Test possibilities\n let ans = \"\";\n dfs(\"\");\n\n return ans;\n\n // Recursive function, tests if the given subsequence repeats k times in s\n function dfs(seq) {\n // Does not have enough repeats, return\n if (countRepeats(seq) < k) {\n return;\n }\n\n // Update our answer if the new subsequence is better\n if (seq.length > ans.length || (seq.length === ans.length && seq > ans)) {\n ans = seq;\n }\n\n // Append possible characters to the subsequence and test again\n if (seq.length < maxLen) {\n for (const char of possibleChars) {\n dfs(seq + char);\n }\n }\n }\n\n // Counts the number of times the given subsequence repeats in s (up to k)\n function countRepeats(seq) {\n\n // Empty string, return k\n if (!seq) {\n return k;\n }\n\n let repeats = 0;\n let seqIdx = 0;\n\n for (const char of s) {\n if (char === seq[seqIdx]) {\n seqIdx += 1;\n\n if (seqIdx >= seq.length) {\n seqIdx = 0;\n repeats += 1;\n\n if (repeats >= k) {\n break;\n }\n }\n }\n }\n\n return repeats;\n } \n};"
] |
|
2,016 | maximum-difference-between-increasing-elements | [
"Could you keep track of the minimum element visited while traversing?",
"We have a potential candidate for the answer if the prefix min is lesser than nums[i]."
] | /**
* @param {number[]} nums
* @return {number}
*/
var maximumDifference = function(nums) {
}; | Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].
Return the maximum difference. If no such i and j exists, return -1.
Example 1:
Input: nums = [7,1,5,4]
Output: 4
Explanation:
The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.
Note that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid.
Example 2:
Input: nums = [9,4,3,2]
Output: -1
Explanation:
There is no i and j such that i < j and nums[i] < nums[j].
Example 3:
Input: nums = [1,5,2,10]
Output: 9
Explanation:
The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9.
Constraints:
n == nums.length
2 <= n <= 1000
1 <= nums[i] <= 109
| Easy | [
"array"
] | null | [] |
2,017 | grid-game | [
"There are n choices for when the first robot moves to the second row.",
"Can we use prefix sums to help solve this problem?"
] | /**
* @param {number[][]} grid
* @return {number}
*/
var gridGame = function(grid) {
}; | You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix.
Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)).
At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another.
The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.
Example 1:
Input: grid = [[2,5,4],[1,5,1]]
Output: 4
Explanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
The cells visited by the first robot are set to 0.
The second robot will collect 0 + 0 + 4 + 0 = 4 points.
Example 2:
Input: grid = [[3,3,1],[8,5,2]]
Output: 4
Explanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
The cells visited by the first robot are set to 0.
The second robot will collect 0 + 3 + 1 + 0 = 4 points.
Example 3:
Input: grid = [[1,3,1,15],[1,3,3,1]]
Output: 7
Explanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
The cells visited by the first robot are set to 0.
The second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points.
Constraints:
grid.length == 2
n == grid[r].length
1 <= n <= 5 * 104
1 <= grid[r][c] <= 105
| Medium | [
"array",
"matrix",
"prefix-sum"
] | null | [] |
2,018 | check-if-word-can-be-placed-in-crossword | [
"Check all possible placements for the word.",
"There is a limited number of places where a word can start."
] | /**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var placeWordInCrossword = function(board, word) {
}; | You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells.
A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if:
It does not occupy a cell containing the character '#'.
The cell each letter is placed in must either be ' ' (empty) or match the letter already on the board.
There must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally.
There must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically.
Given a string word, return true if word can be placed in board, or false otherwise.
Example 1:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", "c", " "]], word = "abc"
Output: true
Explanation: The word "abc" can be placed as shown above (top to bottom).
Example 2:
Input: board = [[" ", "#", "a"], [" ", "#", "c"], [" ", "#", "a"]], word = "ac"
Output: false
Explanation: It is impossible to place the word because there will always be a space/letter above or below it.
Example 3:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", " ", "c"]], word = "ca"
Output: true
Explanation: The word "ca" can be placed as shown above (right to left).
Constraints:
m == board.length
n == board[i].length
1 <= m * n <= 2 * 105
board[i][j] will be ' ', '#', or a lowercase English letter.
1 <= word.length <= max(m, n)
word will contain only lowercase English letters.
| Medium | [
"array",
"matrix",
"enumeration"
] | [
"const placeWordInCrossword = function(board, word) {\n for (let state of [board, getRotated(board)])\n for (let chars of state)\n for (let token of chars.join('').split(\"#\"))\n for (let letters of [word, word.split('').reverse().join('')])\n if (letters.length == token.length)\n if (canFit(letters, token))\n return true;\n return false;\n}\n\nfunction getRotated(board) {\n const m = board.length;\n const n = board[0].length;\n\n const rotated = Array.from({length: n}, () => Array(m));\n for (let i = 0; i < m; ++i)\n for (let j = 0; j < n; ++j)\n rotated[j][i] = board[i][j];\n return rotated;\n}\n\nfunction canFit(letters, token) {\n for (let i = 0; i < letters.length; ++i)\n if (token.charAt(i) != ' ' && token.charAt(i) != letters.charAt(i))\n return false;\n return true;\n}"
] |
|
2,019 | the-score-of-students-solving-math-expression | [
"The number of operators in the equation is less. Could you find the right answer then generate all possible answers using different orders of operations?",
"Divide the equation into blocks separated by the operators, and use memoization on the results of blocks for optimization.",
"Use set and the max limit of the answer for further optimization."
] | /**
* @param {string} s
* @param {number[]} answers
* @return {number}
*/
var scoreOfStudents = function(s, answers) {
}; | You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations:
Compute multiplication, reading from left to right; Then,
Compute addition, reading from left to right.
You are given an integer array answers of length n, which are the submitted answers of the students in no particular order. You are asked to grade the answers, by following these rules:
If an answer equals the correct answer of the expression, this student will be rewarded 5 points;
Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic, this student will be rewarded 2 points;
Otherwise, this student will be rewarded 0 points.
Return the sum of the points of the students.
Example 1:
Input: s = "7+3*1*2", answers = [20,13,42]
Output: 7
Explanation: As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]
A student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]
The points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.
Example 2:
Input: s = "3+5*2", answers = [13,0,10,13,13,16,16]
Output: 19
Explanation: The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]
A student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]
The points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.
Example 3:
Input: s = "6+0*1", answers = [12,9,6,4,8,6]
Output: 10
Explanation: The correct answer of the expression is 6.
If a student had incorrectly done (6+0)*1, the answer would also be 6.
By the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.
The points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.
Constraints:
3 <= s.length <= 31
s represents a valid expression that contains only digits 0-9, '+', and '*' only.
All the integer operands in the expression are in the inclusive range [0, 9].
1 <= The count of all operators ('+' and '*') in the math expression <= 15
Test data are generated such that the correct answer of the expression is in the range of [0, 1000].
n == answers.length
1 <= n <= 104
0 <= answers[i] <= 1000
| Hard | [
"array",
"math",
"string",
"dynamic-programming",
"stack",
"memoization"
] | [
"const op = {\n '+': ((a, b) => Number(a) + Number(b)),\n '*':((a, b) => a * b),\n}\nlet dp = {};\nconst dfs = (s) => {\n if(s.length == 0) return {};\n if(s.length == 1) return { [s[0]] : 1};\n const dps = dp[s];\n if(dps) return dps;\n const res = {};\n for(let i = 0; i < s.length - 2; i += 2) {\n const l = dfs(s.substr(0, i + 1))\n const r = dfs(s.substr(i + 2, s.length - i - 2));\n for(let x in l) {\n for(let y in r) {\n const z = op[s[i + 1]](x, y);\n if(z > 1000) continue;\n res[z] = 1;\n }\n }\n \n }\n dp[s] = res;\n return res;\n}\n\nconst scoreOfStudents = function(s, answers) {\n const correct = eval(s);\n dp = {};\n const allAns = dfs(s);\n let ans = 0;\n answers.forEach(x => {\n if( x == correct) ans += 5;\n else if(allAns[x]) ans += 2;\n })\n return ans;\n};"
] |
|
2,022 | convert-1d-array-into-2d-array | [
"When is it possible to convert original into a 2D array and when is it impossible?",
"It is possible if and only if m * n == original.length",
"If it is possible to convert original to a 2D array, keep an index i such that original[i] is the next element to add to the 2D array."
] | /**
* @param {number[]} original
* @param {number} m
* @param {number} n
* @return {number[][]}
*/
var construct2DArray = function(original, m, n) {
}; | You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original.
The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on.
Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.
Example 1:
Input: original = [1,2,3,4], m = 2, n = 2
Output: [[1,2],[3,4]]
Explanation: The constructed 2D array should contain 2 rows and 2 columns.
The first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.
The second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.
Example 2:
Input: original = [1,2,3], m = 1, n = 3
Output: [[1,2,3]]
Explanation: The constructed 2D array should contain 1 row and 3 columns.
Put all three elements in original into the first row of the constructed 2D array.
Example 3:
Input: original = [1,2], m = 1, n = 1
Output: []
Explanation: There are 2 elements in original.
It is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.
Constraints:
1 <= original.length <= 5 * 104
1 <= original[i] <= 105
1 <= m, n <= 4 * 104
| Easy | [
"array",
"matrix",
"simulation"
] | null | [] |
2,023 | number-of-pairs-of-strings-with-concatenation-equal-to-target | [
"Try to concatenate every two different strings from the list.",
"Count the number of pairs with concatenation equals to target."
] | /**
* @param {string[]} nums
* @param {string} target
* @return {number}
*/
var numOfPairs = function(nums, target) {
}; | Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.
Example 1:
Input: nums = ["777","7","77","77"], target = "7777"
Output: 4
Explanation: Valid pairs are:
- (0, 1): "777" + "7"
- (1, 0): "7" + "777"
- (2, 3): "77" + "77"
- (3, 2): "77" + "77"
Example 2:
Input: nums = ["123","4","12","34"], target = "1234"
Output: 2
Explanation: Valid pairs are:
- (0, 1): "123" + "4"
- (2, 3): "12" + "34"
Example 3:
Input: nums = ["1","1","1"], target = "11"
Output: 6
Explanation: Valid pairs are:
- (0, 1): "1" + "1"
- (1, 0): "1" + "1"
- (0, 2): "1" + "1"
- (2, 0): "1" + "1"
- (1, 2): "1" + "1"
- (2, 1): "1" + "1"
Constraints:
2 <= nums.length <= 100
1 <= nums[i].length <= 100
2 <= target.length <= 100
nums[i] and target consist of digits.
nums[i] and target do not have leading zeros.
| Medium | [
"array",
"string"
] | [
"const numOfPairs = function(nums, target) {\n let res = 0\n \n const n = nums.length\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < n; j++) {\n if(i !== j && nums[i] + nums[j] === target) res++\n }\n }\n \n return res\n};"
] |
|
2,024 | maximize-the-confusion-of-an-exam | [
"Can we use the maximum length at the previous position to help us find the answer for the current position?",
"Can we use binary search to find the maximum consecutive same answer at every position?"
] | /**
* @param {string} answerKey
* @param {number} k
* @return {number}
*/
var maxConsecutiveAnswers = function(answerKey, k) {
}; | A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).
You are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation:
Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F').
Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.
Example 1:
Input: answerKey = "TTFF", k = 2
Output: 4
Explanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT".
There are four consecutive 'T's.
Example 2:
Input: answerKey = "TFFT", k = 1
Output: 3
Explanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT".
Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF".
In both cases, there are three consecutive 'F's.
Example 3:
Input: answerKey = "TTFTTFTT", k = 1
Output: 5
Explanation: We can replace the first 'F' to make answerKey = "TTTTTFTT"
Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT".
In both cases, there are five consecutive 'T's.
Constraints:
n == answerKey.length
1 <= n <= 5 * 104
answerKey[i] is either 'T' or 'F'
1 <= k <= n
| Medium | [
"string",
"binary-search",
"sliding-window",
"prefix-sum"
] | [
"const maxConsecutiveAnswers = function(answerKey, k) {\n const helper = (str, transT) => {\n let res = 0, l = 0, r = 0, num = 0\n const n = str.length\n const target = transT === 1 ? 'T' : 'F'\n while(r < n) {\n if(str[r] === target) num++\n while(num > k) {\n if(str[l] === target) num--\n l++\n }\n res = Math.max(res, r - l + 1)\n r++\n }\n return res\n }\n \n return Math.max(helper(answerKey, 0), helper(answerKey, 1))\n};",
"const maxConsecutiveAnswers = function(answerKey, k) {\n let s = answerKey\n const freq = Array(26).fill(0), n = s.length, A = 'A'.charCodeAt(0)\n let res = 0, l = 0, r = 0, maxFreq = 0\n while(r < n) {\n maxFreq = Math.max(maxFreq, ++freq[s.charCodeAt(r) - A])\n if(r - l + 1 - maxFreq > k) {\n freq[s.charCodeAt(l) - A]--\n l++\n }\n res = Math.max(res, r - l + 1)\n r++\n }\n \n return res\n};"
] |
|
2,025 | maximum-number-of-ways-to-partition-an-array | [
"A pivot point splits the array into equal prefix and suffix. If no change is made to the array, the goal is to find the number of pivot p such that prefix[p-1] == suffix[p].",
"Consider how prefix and suffix will change when we change a number nums[i] to k.",
"When sweeping through each element, can you find the total number of pivots where the difference of prefix and suffix happens to equal to the changes of k-nums[i]."
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var waysToPartition = function(nums, k) {
}; | You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions:
1 <= pivot < n
nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]
You are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged.
Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.
Example 1:
Input: nums = [2,-1,2], k = 3
Output: 1
Explanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].
There is one way to partition the array:
- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.
Example 2:
Input: nums = [0,0,0], k = 1
Output: 2
Explanation: The optimal approach is to leave the array unchanged.
There are two ways to partition the array:
- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.
- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.
Example 3:
Input: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33
Output: 4
Explanation: One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14].
There are four ways to partition the array.
Constraints:
n == nums.length
2 <= n <= 105
-105 <= k, nums[i] <= 105
| Hard | [
"array",
"hash-table",
"counting",
"enumeration",
"prefix-sum"
] | [
"const waysToPartition = function (nums, k) {\n const n = nums.length, pre = Array(n).fill(0), suf = Array(n).fill(0)\n pre[0] = nums[0], suf[n - 1] = nums[n - 1]\n for(let i = 1; i < n; i++) {\n pre[i] = pre[i - 1] + nums[i]\n suf[n - 1 - i] = suf[n - i] + nums[n - 1 - i]\n }\n const sum = nums.reduce((ac, e) => ac + e, 0)\n let res = 0\n for(let i = 0; i < n - 1; i++) {\n if(pre[i] === suf[i + 1]) res++\n }\n const cnt = new Map()\n const arr = Array(n).fill(0)\n for(let i = 0; i < n; i++) {\n const newSum = sum - nums[i] + k\n if(newSum % 2 === 0) arr[i] += (cnt.get(newSum / 2) || 0)\n cnt.set(pre[i], (cnt.get(pre[i]) || 0) + 1)\n }\n cnt.clear()\n for(let i = n - 1; i >= 0; i--) {\n const newSum = sum - nums[i] + k\n if(newSum % 2 === 0) arr[i] += (cnt.get(newSum / 2) || 0)\n cnt.set(suf[i], (cnt.get(suf[i]) || 0) + 1)\n }\n \n for(let e of arr) {\n if(e > res) res = e\n }\n \n return res\n}",
"const waysToPartition = function (nums, k) {\n const n = nums.length\n const pref = Array(n).fill(0),\n suff = Array(n).fill(0)\n pref[0] = nums[0]\n suff[n - 1] = nums[n - 1]\n for (let i = 1; i < n; ++i) {\n pref[i] = pref[i - 1] + nums[i]\n suff[n - 1 - i] = suff[n - i] + nums[n - 1 - i]\n }\n let ans = 0\n const left = {},\n right = {}\n\n for (let i = 0; i < n - 1; ++i) {\n const delta = pref[i] - suff[i + 1]\n if (right[delta] == null) right[delta] = 0\n right[delta]++\n }\n\n if (right[0]) ans = right[0]\n for (let i = 0; i < n; ++i) {\n //find the number of pivot indexes when nums[i] is changed to k\n let curr = 0,\n diff = k - nums[i]\n if (left[diff]) curr += left[diff]\n if (right[-diff]) curr += right[-diff]\n\n //update answer\n ans = Math.max(ans, curr)\n\n //transfer the current element from right to left\n if (i < n - 1) {\n let dd = pref[i] - suff[i + 1]\n if(left[dd] == null) left[dd] = 0\n if(right[dd] == null) right[dd] = 0\n left[dd]++\n right[dd]--\n if (right[dd] == 0) delete right[dd]\n }\n }\n return ans\n}"
] |
|
2,027 | minimum-moves-to-convert-string | [
"Find the smallest substring you need to consider at a time.",
"Try delaying a move as long as possible."
] | /**
* @param {string} s
* @return {number}
*/
var minimumMoves = function(s) {
}; | You are given a string s consisting of n characters which are either 'X' or 'O'.
A move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same.
Return the minimum number of moves required so that all the characters of s are converted to 'O'.
Example 1:
Input: s = "XXX"
Output: 1
Explanation: XXX -> OOO
We select all the 3 characters and convert them in one move.
Example 2:
Input: s = "XXOX"
Output: 2
Explanation: XXOX -> OOOX -> OOOO
We select the first 3 characters in the first move, and convert them to 'O'.
Then we select the last 3 characters and convert them so that the final string contains all 'O's.
Example 3:
Input: s = "OOOO"
Output: 0
Explanation: There are no 'X's in s to convert.
Constraints:
3 <= s.length <= 1000
s[i] is either 'X' or 'O'.
| Easy | [
"string",
"greedy"
] | null | [] |
2,028 | find-missing-observations | [
"What should the sum of the n rolls be?",
"Could you generate an array of size n such that each element is between 1 and 6?"
] | /**
* @param {number[]} rolls
* @param {number} mean
* @param {number} n
* @return {number[]}
*/
var missingRolls = function(rolls, mean, n) {
}; | You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls.
You are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n.
Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array.
The average value of a set of k numbers is the sum of the numbers divided by k.
Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m.
Example 1:
Input: rolls = [3,2,4,3], mean = 4, n = 2
Output: [6,6]
Explanation: The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.
Example 2:
Input: rolls = [1,5,6], mean = 3, n = 4
Output: [2,3,2,2]
Explanation: The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.
Example 3:
Input: rolls = [1,2,3,4], mean = 6, n = 4
Output: []
Explanation: It is impossible for the mean to be 6 no matter what the 4 missing rolls are.
Constraints:
m == rolls.length
1 <= n, m <= 105
1 <= rolls[i], mean <= 6
| Medium | [
"array",
"math",
"simulation"
] | null | [] |
2,029 | stone-game-ix | [
"There are limited outcomes given the current sum and the stones remaining.",
"Can we greedily simulate starting with taking a stone with remainder 1 or 2 divided by 3?"
] | /**
* @param {number[]} stones
* @return {boolean}
*/
var stoneGameIX = function(stones) {
}; | Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone.
Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice's turn).
Assuming both players play optimally, return true if Alice wins and false if Bob wins.
Example 1:
Input: stones = [2,1]
Output: true
Explanation: The game will be played as follows:
- Turn 1: Alice can remove either stone.
- Turn 2: Bob removes the remaining stone.
The sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game.
Example 2:
Input: stones = [2]
Output: false
Explanation: Alice will remove the only stone, and the sum of the values on the removed stones is 2.
Since all the stones are removed and the sum of values is not divisible by 3, Bob wins the game.
Example 3:
Input: stones = [5,1,2,4,3]
Output: false
Explanation: Bob will always win. One possible way for Bob to win is shown below:
- Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1.
- Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4.
- Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8.
- Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10.
- Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15.
Alice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.
Constraints:
1 <= stones.length <= 105
1 <= stones[i] <= 104
| Medium | [
"array",
"math",
"greedy",
"counting",
"game-theory"
] | [
"const stoneGameIX = function(stones) {\n const cnt = Array(3).fill(0), { abs } = Math \n for (let a of stones) cnt[a % 3]++;\n if (cnt[0] % 2 == 0) return cnt[1] && cnt[2]\n return abs(cnt[1] - cnt[2]) >= 3\n};"
] |
|
2,030 | smallest-k-length-subsequence-with-occurrences-of-a-letter | [
"Use stack. For every character to be appended, decide how many character(s) from the stack needs to get popped based on the stack length and the count of the required character.",
"Pop the extra characters out from the stack and return the characters in the stack (reversed)."
] | /**
* @param {string} s
* @param {number} k
* @param {character} letter
* @param {number} repetition
* @return {string}
*/
var smallestSubsequence = function(s, k, letter, repetition) {
}; | You are given a string s, an integer k, a letter letter, and an integer repetition.
Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Example 1:
Input: s = "leet", k = 3, letter = "e", repetition = 1
Output: "eet"
Explanation: There are four subsequences of length 3 that have the letter 'e' appear at least 1 time:
- "lee" (from "leet")
- "let" (from "leet")
- "let" (from "leet")
- "eet" (from "leet")
The lexicographically smallest subsequence among them is "eet".
Example 2:
Input: s = "leetcode", k = 4, letter = "e", repetition = 2
Output: "ecde"
Explanation: "ecde" is the lexicographically smallest subsequence of length 4 that has the letter "e" appear at least 2 times.
Example 3:
Input: s = "bb", k = 2, letter = "b", repetition = 2
Output: "bb"
Explanation: "bb" is the only subsequence of length 2 that has the letter "b" appear at least 2 times.
Constraints:
1 <= repetition <= k <= s.length <= 5 * 104
s consists of lowercase English letters.
letter is a lowercase English letter, and appears in s at least repetition times.
| Hard | [
"string",
"stack",
"greedy",
"monotonic-stack"
] | [
"const smallestSubsequence = function (s, k, letter, repetition) {\n let n_letters = 0\n for (let i = 0; i < s.length; i++) if (s.charAt(i) == letter) n_letters++\n const stack = []\n for (let i = 0; i < s.length; i++) {\n let c = s.charAt(i)\n while (\n stack.length &&\n stack[stack.length - 1] > c &&\n s.length - i + stack.length > k &&\n (stack[stack.length - 1] != letter || n_letters > repetition)\n ) {\n if (stack.pop() == letter) repetition++\n }\n if (stack.length < k) {\n if (c == letter) {\n stack.push(c)\n repetition--\n } else if (k - stack.length > repetition) {\n stack.push(c)\n }\n }\n if (c == letter) n_letters--\n }\n\n let sb = ''\n for (let c of stack) sb += c\n return sb\n}"
] |
|
2,032 | two-out-of-three | [
"What data structure can we use to help us quickly find whether an element belongs in an array?",
"Can we count the frequencies of the elements in each array?"
] | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number[]} nums3
* @return {number[]}
*/
var twoOutOfThree = function(nums1, nums2, nums3) {
}; | Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order.
Example 1:
Input: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]
Output: [3,2]
Explanation: The values that are present in at least two arrays are:
- 3, in all three arrays.
- 2, in nums1 and nums2.
Example 2:
Input: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]
Output: [2,3,1]
Explanation: The values that are present in at least two arrays are:
- 2, in nums2 and nums3.
- 3, in nums1 and nums2.
- 1, in nums1 and nums3.
Example 3:
Input: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]
Output: []
Explanation: No value is present in at least two arrays.
Constraints:
1 <= nums1.length, nums2.length, nums3.length <= 100
1 <= nums1[i], nums2[j], nums3[k] <= 100
| Easy | [
"array",
"hash-table"
] | [
"const twoOutOfThree = function(nums1, nums2, nums3) {\n const res = []\n const hash = {}\n for(let e of new Set(nums1)) {\n if(hash[e] == null) hash[e] = 0\n hash[e] = 1\n }\n\n for(let e of new Set(nums2)) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n \n\n for(let e of new Set(nums3)) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n \n Object.keys(hash).forEach(k => {\n if(hash[k] > 1) res.push(k)\n })\n\n \n return res\n};"
] |
|
2,033 | minimum-operations-to-make-a-uni-value-grid | [
"Is it possible to make two integers a and b equal if they have different remainders dividing by x?",
"If it is possible, which number should you select to minimize the number of operations?",
"What if the elements are sorted?"
] | /**
* @param {number[][]} grid
* @param {number} x
* @return {number}
*/
var minOperations = function(grid, x) {
}; | You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid.
A uni-value grid is a grid where all the elements of it are equal.
Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1.
Example 1:
Input: grid = [[2,4],[6,8]], x = 2
Output: 4
Explanation: We can make every element equal to 4 by doing the following:
- Add x to 2 once.
- Subtract x from 6 once.
- Subtract x from 8 twice.
A total of 4 operations were used.
Example 2:
Input: grid = [[1,5],[2,3]], x = 1
Output: 5
Explanation: We can make every element equal to 3.
Example 3:
Input: grid = [[1,2],[3,4]], x = 2
Output: -1
Explanation: It is impossible to make every element equal.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
1 <= x, grid[i][j] <= 104
| Medium | [
"array",
"math",
"sorting",
"matrix"
] | [
"const minOperations = function (grid, x) {\n const arr = [],\n m = grid.length,\n n = grid[0].length\n const len = m * n\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n arr.push(grid[i][j])\n }\n }\n arr.sort((a, b) => a - b)\n const mid = arr[~~(len / 2)], { abs } = Math\n let res = 0\n for(const e of arr) {\n if(abs(mid - e) % x !== 0) return -1\n res += abs(mid - e) / x\n }\n\n return res\n}",
"const minOperations = function(grid, x) {\n const arr = []\n const m = grid.length, n = grid[0].length\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n arr.push(grid[i][j])\n }\n }\n arr.sort((a, b) => a - b)\n \n for(let i = 1; i < m * n; i++) {\n if((arr[i] - arr[i - 1]) % x !== 0) return -1\n }\n const sum = arr.reduce((ac, e) => ac + e, 0)\n const pre = []\n pre.push(arr[0])\n for(let i = 1; i < m * n; i++) {\n pre[i] = pre[i - 1] + arr[i]\n }\n \n let res = 0, num = 0, min = sum - arr[0] * m * n, idx = 0\n for(let i = 1; i < m * n; i++) {\n const cur = (i + 1) * arr[i] - pre[i] + (sum - pre[i] - arr[i] * (m * n - i - 1))\n // console.log(cur, (i + 1) * arr[i] - pre[i], sum - pre[i] - arr[i] * (m * n - i - 1))\n // const cur = sum - arr[i] * (m * n - i)\n if(cur < min) {\n idx = i\n min = cur\n }\n }\n \n // console.log(idx)\n \n for(let i = 0; i < m * n; i++) {\n if(i === idx) continue\n res += Math.abs(arr[i] - arr[idx]) / x\n }\n \n return res\n};\n// 20 - 6 - 4 * 2\n// 2 4 6 8\n// 1 2 3 5",
"const minOperations = function(grid, x) {\n const arr = [], m = grid.length, n = grid[0].length\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n arr.push(grid[i][j])\n }\n }\n arr.sort((a, b) => a - b)\n const mid = arr[~~((m * n) / 2)]\n let res = 0\n\n for(let e of arr) {\n if (e !== mid) {\n const cur = Math.abs(e - mid)\n if(cur % x !== 0) return -1\n res += cur / x\n }\n }\n return res\n};",
"function minOperations(grid, x) {\n const m = grid.length, n = grid[0].length, mn = m * n, arr = []\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n arr.push(grid[i][j])\n }\n }\n arr.sort((a, b) => a - b)\n const mid = arr[~~(mn / 2)]\n let res = 0\n\n for(let e of arr) {\n if(e !== mid) {\n const delta = Math.abs(e - mid)\n if(delta % x !== 0) return -1\n res += delta / x\n }\n }\n\n return res\n};"
] |
|
2,034 | stock-price-fluctuation | [
"How would you solve the problem for offline queries (all queries given at once)?",
"Think about which data structure can help insert and delete the most optimal way."
] |
var StockPrice = function() {
};
/**
* @param {number} timestamp
* @param {number} price
* @return {void}
*/
StockPrice.prototype.update = function(timestamp, price) {
};
/**
* @return {number}
*/
StockPrice.prototype.current = function() {
};
/**
* @return {number}
*/
StockPrice.prototype.maximum = function() {
};
/**
* @return {number}
*/
StockPrice.prototype.minimum = function() {
};
/**
* Your StockPrice object will be instantiated and called as such:
* var obj = new StockPrice()
* obj.update(timestamp,price)
* var param_2 = obj.current()
* var param_3 = obj.maximum()
* var param_4 = obj.minimum()
*/ | You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp.
Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record.
Design an algorithm that:
Updates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp.
Finds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded.
Finds the maximum price the stock has been based on the current records.
Finds the minimum price the stock has been based on the current records.
Implement the StockPrice class:
StockPrice() Initializes the object with no price records.
void update(int timestamp, int price) Updates the price of the stock at the given timestamp.
int current() Returns the latest price of the stock.
int maximum() Returns the maximum price of the stock.
int minimum() Returns the minimum price of the stock.
Example 1:
Input
["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"]
[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]
Output
[null, null, null, 5, 10, null, 5, null, 2]
Explanation
StockPrice stockPrice = new StockPrice();
stockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].
stockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5].
stockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5.
stockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1.
stockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3.
// Timestamps are [1,2] with corresponding prices [3,5].
stockPrice.maximum(); // return 5, the maximum price is 5 after the correction.
stockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2].
stockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4.
Constraints:
1 <= timestamp, price <= 109
At most 105 calls will be made in total to update, current, maximum, and minimum.
current, maximum, and minimum will be called only after update has been called at least once.
| Medium | [
"hash-table",
"design",
"heap-priority-queue",
"data-stream",
"ordered-set"
] | [
"const StockPrice = function () {\n this.timeToPrice = new Map()\n this.lastTime = 0\n this.minPrices = new MinPriorityQueue({ priority: (stock) => stock.price })\n this.maxPrices = new MaxPriorityQueue({ priority: (stock) => stock.price })\n}\n\n\nStockPrice.prototype.update = function (timestamp, price) {\n this.timeToPrice.set(timestamp, price)\n this.lastTime = Math.max(this.lastTime, timestamp)\n this.minPrices.enqueue({ timestamp, price })\n this.maxPrices.enqueue({ timestamp, price })\n}\n\n\nStockPrice.prototype.current = function () {\n return this.timeToPrice.get(this.lastTime)\n}\n\n\nStockPrice.prototype.maximum = function () {\n while (\n this.maxPrices.front().element.price !==\n this.timeToPrice.get(this.maxPrices.front().element.timestamp)\n ) {\n this.maxPrices.dequeue()\n }\n\n return this.maxPrices.front().element.price\n}\n\n\nStockPrice.prototype.minimum = function () {\n while (\n this.minPrices.front().element.price !==\n this.timeToPrice.get(this.minPrices.front().element.timestamp)\n ) {\n this.minPrices.dequeue()\n }\n\n return this.minPrices.front().element.price\n}"
] |
|
2,035 | partition-array-into-two-arrays-to-minimize-sum-difference | [
"The target sum for the two partitions is sum(nums) / 2.",
"Could you reduce the time complexity if you arbitrarily divide nums into two halves (two arrays)? Meet-in-the-Middle?",
"For both halves, pre-calculate a 2D array where the kth index will store all possible sum values if only k elements from this half are added.",
"For each sum of k elements in the first half, find the best sum of n-k elements in the second half such that the two sums add up to a value closest to the target sum from hint 1. These two subsets will form one array of the partition."
] | /**
* @param {number[]} nums
* @return {number}
*/
var minimumDifference = function(nums) {
}; | You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays.
Return the minimum possible absolute difference.
Example 1:
Input: nums = [3,9,7,3]
Output: 2
Explanation: One optimal partition is: [3,9] and [7,3].
The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.
Example 2:
Input: nums = [-36,36]
Output: 72
Explanation: One optimal partition is: [-36] and [36].
The absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.
Example 3:
Input: nums = [2,-1,0,4,-2,-9]
Output: 0
Explanation: One optimal partition is: [2,4,-9] and [-1,0,-2].
The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.
Constraints:
1 <= n <= 15
nums.length == 2 * n
-107 <= nums[i] <= 107
| Hard | [
"array",
"two-pointers",
"binary-search",
"dynamic-programming",
"bit-manipulation",
"ordered-set",
"bitmask"
] | [
"const mi = Math.min,\n abs = Math.abs\nconst minimumDifference = (nums) => {\n let m = nums.length,\n n = m >> 1\n let a = initializeGraph(n + 1)\n let b = initializeGraph(n + 1)\n for (let i = 0; i < 1 << n; i++) {\n // mask\n let sum = 0,\n cnt = 0\n for (let j = 0; j < n; j++) {\n if (i & (1 << j)) {\n // bit of 1's\n sum += nums[j]\n cnt++ // bit count\n } else {\n sum -= nums[j]\n }\n }\n a[cnt].push(sum)\n ;(sum = 0), (cnt = 0)\n for (let j = 0; j < n; j++) {\n if (i & (1 << j)) {\n sum += nums[n + j]\n cnt++\n } else {\n sum -= nums[n + j]\n }\n }\n b[cnt].push(sum)\n }\n for (let i = 0; i < n; i++) {\n a[i].sort((x, y) => x - y)\n b[i].sort((x, y) => x - y)\n }\n let res = Number.MAX_SAFE_INTEGER\n let bi = new Bisect()\n for (let i = 0; i <= n; i++) {\n for (const x of a[i]) {\n let idx = bi.bisect_left(b[n - i], -x) // binary search lower_bound\n if (idx != b[n - i].length) res = mi(res, abs(x + b[n - i][idx]))\n if (idx != 0) {\n idx--\n res = mi(res, abs(x + b[n - i][idx]))\n }\n }\n }\n return res\n}\n\n//////////////////////////////////////// Template ////////////////////////////////////////////////////////\nfunction Bisect() {\n return { insort_right, insort_left, bisect_left, bisect_right }\n function insort_right(a, x, lo = 0, hi = null) {\n lo = bisect_right(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_right(a, x, lo = 0, hi = null) {\n // > upper_bound\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = (lo + hi) >> 1\n x < a[mid] ? (hi = mid) : (lo = mid + 1)\n }\n return lo\n }\n function insort_left(a, x, lo = 0, hi = null) {\n lo = bisect_left(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_left(a, x, lo = 0, hi = null) {\n // >= lower_bound\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = (lo + hi) >> 1\n a[mid] < x ? (lo = mid + 1) : (hi = mid)\n }\n return lo\n }\n}\n\nconst initializeGraph = (n) => {\n let G = []\n for (let i = 0; i < n; i++) {\n G.push([])\n }\n return G\n}\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////"
] |
|
2,037 | minimum-number-of-moves-to-seat-everyone | [
"Can we sort the arrays to help solve the problem?",
"Can we greedily match each student to a seat?",
"The smallest positioned student will go to the smallest positioned chair, and then the next smallest positioned student will go to the next smallest positioned chair, and so on."
] | /**
* @param {number[]} seats
* @param {number[]} students
* @return {number}
*/
var minMovesToSeat = function(seats, students) {
}; | There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student.
You may perform the following move any number of times:
Increase or decrease the position of the ith student by 1 (i.e., moving the ith student from position x to x + 1 or x - 1)
Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat.
Note that there may be multiple seats or students in the same position at the beginning.
Example 1:
Input: seats = [3,1,5], students = [2,7,4]
Output: 4
Explanation: The students are moved as follows:
- The first student is moved from from position 2 to position 1 using 1 move.
- The second student is moved from from position 7 to position 5 using 2 moves.
- The third student is moved from from position 4 to position 3 using 1 move.
In total, 1 + 2 + 1 = 4 moves were used.
Example 2:
Input: seats = [4,1,5,9], students = [1,3,2,6]
Output: 7
Explanation: The students are moved as follows:
- The first student is not moved.
- The second student is moved from from position 3 to position 4 using 1 move.
- The third student is moved from from position 2 to position 5 using 3 moves.
- The fourth student is moved from from position 6 to position 9 using 3 moves.
In total, 0 + 1 + 3 + 3 = 7 moves were used.
Example 3:
Input: seats = [2,2,6,6], students = [1,3,2,6]
Output: 4
Explanation: Note that there are two seats at position 2 and two seats at position 6.
The students are moved as follows:
- The first student is moved from from position 1 to position 2 using 1 move.
- The second student is moved from from position 3 to position 6 using 3 moves.
- The third student is not moved.
- The fourth student is not moved.
In total, 1 + 3 + 0 + 0 = 4 moves were used.
Constraints:
n == seats.length == students.length
1 <= n <= 100
1 <= seats[i], students[j] <= 100
| Easy | [
"array",
"sorting"
] | [
"const minMovesToSeat = function(seats, students) {\n let res = 0\n seats.sort((a, b) => a - b)\n students.sort((a, b) => a - b)\n \n for(let i = 0; i < students.length; i++) {\n res += Math.abs(seats[i] - students[i])\n }\n \n return res\n};"
] |
|
2,038 | remove-colored-pieces-if-both-neighbors-are-the-same-color | [
"Does the number of moves a player can make depend on what the other player does? No",
"How many moves can Alice make if colors == \"AAAAAA\"",
"If a group of n consecutive pieces has the same color, the player can take n - 2 of those pieces if n is greater than or equal to 3"
] | /**
* @param {string} colors
* @return {boolean}
*/
var winnerOfGame = function(colors) {
}; | There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.
Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.
Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'.
Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'.
Alice and Bob cannot remove pieces from the edge of the line.
If a player cannot make a move on their turn, that player loses and the other player wins.
Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.
Example 1:
Input: colors = "AAABABB"
Output: true
Explanation:
AAABABB -> AABABB
Alice moves first.
She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.
Now it's Bob's turn.
Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.
Thus, Alice wins, so return true.
Example 2:
Input: colors = "AA"
Output: false
Explanation:
Alice has her turn first.
There are only two 'A's and both are on the edge of the line, so she cannot move on her turn.
Thus, Bob wins, so return false.
Example 3:
Input: colors = "ABBBBBBBAAA"
Output: false
Explanation:
ABBBBBBBAAA -> ABBBBBBBAA
Alice moves first.
Her only option is to remove the second to last 'A' from the right.
ABBBBBBBAA -> ABBBBBBAA
Next is Bob's turn.
He has many options for which 'B' piece to remove. He can pick any.
On Alice's second turn, she has no more pieces that she can remove.
Thus, Bob wins, so return false.
Constraints:
1 <= colors.length <= 105
colors consists of only the letters 'A' and 'B'
| Medium | [
"math",
"string",
"greedy",
"game-theory"
] | [
"const winnerOfGame = function(colors) {\n let ac = 0, bc = 0\n for(let i = 1, n = colors.length; i < n - 1; i++) {\n if(colors[i] === 'A' && colors[i - 1] === 'A' && colors[i + 1] === 'A') ac++\n if(colors[i] === 'B' && colors[i - 1] === 'B' && colors[i + 1] === 'B') bc++\n }\n return ac > bc\n};"
] |
|
2,039 | the-time-when-the-network-becomes-idle | [
"What method can you use to find the shortest time taken for a message from a data server to reach the master server? How can you use this value and the server's patience value to determine the time at which the server sends its last message?",
"What is the time when the last message sent from a server gets back to the server?",
"For each data server, by the time the server receives the first returned messages, how many messages has the server sent?"
] | /**
* @param {number[][]} edges
* @param {number[]} patience
* @return {number}
*/
var networkBecomesIdle = function(edges, patience) {
}; | There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n.
All servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels.
The server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through.
At the beginning of second 0, each data server sends its message to be processed. Starting from second 1, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server:
If it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server.
Otherwise, no more resending will occur from this server.
The network becomes idle when there are no messages passing between servers or arriving at servers.
Return the earliest second starting from which the network becomes idle.
Example 1:
Input: edges = [[0,1],[1,2]], patience = [0,2,1]
Output: 8
Explanation:
At (the beginning of) second 0,
- Data server 1 sends its message (denoted 1A) to the master server.
- Data server 2 sends its message (denoted 2A) to the master server.
At second 1,
- Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back.
- Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message.
- Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B).
At second 2,
- The reply 1A arrives at server 1. No more resending will occur from server 1.
- Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back.
- Server 2 resends the message (denoted 2C).
...
At second 4,
- The reply 2A arrives at server 2. No more resending will occur from server 2.
...
At second 7, reply 2D arrives at server 2.
Starting from the beginning of the second 8, there are no messages passing between servers or arriving at servers.
This is the time when the network becomes idle.
Example 2:
Input: edges = [[0,1],[0,2],[1,2]], patience = [0,10,10]
Output: 3
Explanation: Data servers 1 and 2 receive a reply back at the beginning of second 2.
From the beginning of the second 3, the network becomes idle.
Constraints:
n == patience.length
2 <= n <= 105
patience[0] == 0
1 <= patience[i] <= 105 for 1 <= i < n
1 <= edges.length <= min(105, n * (n - 1) / 2)
edges[i].length == 2
0 <= ui, vi < n
ui != vi
There are no duplicate edges.
Each server can directly or indirectly reach another server.
| Medium | [
"array",
"breadth-first-search",
"graph"
] | null | [] |
2,040 | kth-smallest-product-of-two-sorted-arrays | [
"Can we split this problem into four cases depending on the sign of the numbers?",
"Can we binary search the value?"
] | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number} k
* @return {number}
*/
var kthSmallestProduct = function(nums1, nums2, k) {
}; | Given two sorted 0-indexed integer arrays nums1 and nums2 as well as an integer k, return the kth (1-based) smallest product of nums1[i] * nums2[j] where 0 <= i < nums1.length and 0 <= j < nums2.length.
Example 1:
Input: nums1 = [2,5], nums2 = [3,4], k = 2
Output: 8
Explanation: The 2 smallest products are:
- nums1[0] * nums2[0] = 2 * 3 = 6
- nums1[0] * nums2[1] = 2 * 4 = 8
The 2nd smallest product is 8.
Example 2:
Input: nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6
Output: 0
Explanation: The 6 smallest products are:
- nums1[0] * nums2[1] = (-4) * 4 = -16
- nums1[0] * nums2[0] = (-4) * 2 = -8
- nums1[1] * nums2[1] = (-2) * 4 = -8
- nums1[1] * nums2[0] = (-2) * 2 = -4
- nums1[2] * nums2[0] = 0 * 2 = 0
- nums1[2] * nums2[1] = 0 * 4 = 0
The 6th smallest product is 0.
Example 3:
Input: nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3
Output: -6
Explanation: The 3 smallest products are:
- nums1[0] * nums2[4] = (-2) * 5 = -10
- nums1[0] * nums2[3] = (-2) * 4 = -8
- nums1[4] * nums2[0] = 2 * (-3) = -6
The 3rd smallest product is -6.
Constraints:
1 <= nums1.length, nums2.length <= 5 * 104
-105 <= nums1[i], nums2[j] <= 105
1 <= k <= nums1.length * nums2.length
nums1 and nums2 are sorted.
| Hard | [
"array",
"binary-search"
] | [
"const kthSmallestProduct = function(nums1, nums2, k) {\n const neg = nums1.filter(e => e < 0) \n const pos = nums1.filter(e => e >= 0)\n const negRev = neg.slice(), posRev = pos.slice()\n negRev.reverse()\n posRev.reverse()\n\n let l = - (10 ** 10), r = 10 ** 10\n while(l < r) {\n const mid = l + Math.floor((r - l) / 2)\n if(fn(mid) < k) l = mid + 1\n else r = mid\n } \n\n return l\n\n function fn(val) {\n let res = 0, n = nums2.length\n let l = 0, r = n - 1\n const list = val >= 0 ? negRev.concat(pos) : neg.concat(posRev)\n for(let e of list) {\n if(e < 0) {\n while(l < n && e * nums2[l] > val) l++\n res += n - l\n } else if (e === 0) {\n if(val >= 0) res += n\n } else {\n while(r >= 0 && e * nums2[r] > val) r--\n res += r + 1\n }\n }\n return res\n }\n};"
] |
|
2,042 | check-if-numbers-are-ascending-in-a-sentence | [
"Use string tokenization of your language to extract all the tokens of the string easily.",
"For each token extracted, how can you tell if it is a number? Does the first letter being a digit mean something?",
"Compare the number with the previously occurring number to check if ascending order is maintained."
] | /**
* @param {string} s
* @return {boolean}
*/
var areNumbersAscending = function(s) {
}; | A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters.
For example, "a puppy has 2 eyes 4 legs" is a sentence with seven tokens: "2" and "4" are numbers and the other tokens such as "puppy" are words.
Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s).
Return true if so, or false otherwise.
Example 1:
Input: s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles"
Output: true
Explanation: The numbers in s are: 1, 3, 4, 6, 12.
They are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.
Example 2:
Input: s = "hello world 5 x 5"
Output: false
Explanation: The numbers in s are: 5, 5. They are not strictly increasing.
Example 3:
Input: s = "sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s"
Output: false
Explanation: The numbers in s are: 7, 51, 50, 60. They are not strictly increasing.
Constraints:
3 <= s.length <= 200
s consists of lowercase English letters, spaces, and digits from 0 to 9, inclusive.
The number of tokens in s is between 2 and 100, inclusive.
The tokens in s are separated by a single space.
There are at least two numbers in s.
Each number in s is a positive number less than 100, with no leading zeros.
s contains no leading or trailing spaces.
| Easy | [
"string"
] | [
"const areNumbersAscending = function(s) {\n const arr =s.split(' ')\n const f = arr.filter(e => !Number.isNaN(+e)).map(e => +e)\n let res = true\n for(let i = 1; i < f.length; i++) {\n if(f[i] <= f[i - 1]) return false\n }\n \n return res\n};"
] |
|
2,043 | simple-bank-system | [
"How do you determine if a transaction will fail?",
"Simply apply the operations if the transaction is valid."
] | /**
* @param {number[]} balance
*/
var Bank = function(balance) {
};
/**
* @param {number} account1
* @param {number} account2
* @param {number} money
* @return {boolean}
*/
Bank.prototype.transfer = function(account1, account2, money) {
};
/**
* @param {number} account
* @param {number} money
* @return {boolean}
*/
Bank.prototype.deposit = function(account, money) {
};
/**
* @param {number} account
* @param {number} money
* @return {boolean}
*/
Bank.prototype.withdraw = function(account, money) {
};
/**
* Your Bank object will be instantiated and called as such:
* var obj = new Bank(balance)
* var param_1 = obj.transfer(account1,account2,money)
* var param_2 = obj.deposit(account,money)
* var param_3 = obj.withdraw(account,money)
*/ | You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initial balance of balance[i].
Execute all the valid transactions. A transaction is valid if:
The given account number(s) are between 1 and n, and
The amount of money withdrawn or transferred from is less than or equal to the balance of the account.
Implement the Bank class:
Bank(long[] balance) Initializes the object with the 0-indexed integer array balance.
boolean transfer(int account1, int account2, long money) Transfers money dollars from the account numbered account1 to the account numbered account2. Return true if the transaction was successful, false otherwise.
boolean deposit(int account, long money) Deposit money dollars into the account numbered account. Return true if the transaction was successful, false otherwise.
boolean withdraw(int account, long money) Withdraw money dollars from the account numbered account. Return true if the transaction was successful, false otherwise.
Example 1:
Input
["Bank", "withdraw", "transfer", "deposit", "transfer", "withdraw"]
[[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]]
Output
[null, true, true, true, false, false]
Explanation
Bank bank = new Bank([10, 100, 20, 50, 30]);
bank.withdraw(3, 10); // return true, account 3 has a balance of $20, so it is valid to withdraw $10.
// Account 3 has $20 - $10 = $10.
bank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to transfer $20.
// Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30.
bank.deposit(5, 20); // return true, it is valid to deposit $20 to account 5.
// Account 5 has $10 + $20 = $30.
bank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10,
// so it is invalid to transfer $15 from it.
bank.withdraw(10, 50); // return false, it is invalid because account 10 does not exist.
Constraints:
n == balance.length
1 <= n, account, account1, account2 <= 105
0 <= balance[i], money <= 1012
At most 104 calls will be made to each function transfer, deposit, withdraw.
| Medium | [
"array",
"hash-table",
"design",
"simulation"
] | [
"const Bank = function(balance) {\n this.n = balance.length\n balance.unshift(0)\n this.b = balance\n \n};\n\n\nBank.prototype.transfer = function(account1, account2, money) {\n let res = true\n if(account1 > this.n || account1 < 1) return false\n if(account2 > this.n || account2 < 1) return false\n if(this.b[account1]< money) return false\n this.b[account1] -= money\n this.b[account2] += money\n return true\n};\n\n\nBank.prototype.deposit = function(account, money) {\n if(account > this.n || account < 1) return false\n this.b[account] += money\n return true\n};\n\n\nBank.prototype.withdraw = function(account, money) {\n if(account > this.n || account < 1) return false\n if(this.b[account] < money) return false\n this.b[account] -= money\n return true\n};"
] |
|
2,044 | count-number-of-maximum-bitwise-or-subsets | [
"Can we enumerate all possible subsets?",
"The maximum bitwise-OR is the bitwise-OR of the whole array."
] | /**
* @param {number[]} nums
* @return {number}
*/
var countMaxOrSubsets = function(nums) {
}; | Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR.
An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different.
The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed).
Example 1:
Input: nums = [3,1]
Output: 2
Explanation: The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:
- [3]
- [3,1]
Example 2:
Input: nums = [2,2,2]
Output: 7
Explanation: All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets.
Example 3:
Input: nums = [3,2,1,5]
Output: 6
Explanation: The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:
- [3,5]
- [3,1,5]
- [3,2,5]
- [3,2,1,5]
- [2,5]
- [2,1,5]
Constraints:
1 <= nums.length <= 16
1 <= nums[i] <= 105
| Medium | [
"array",
"backtracking",
"bit-manipulation"
] | [
"const countMaxOrSubsets = function(nums) {\n let res = 0, max = 0, n = nums.length\n for(let num of nums) max |= num\n dfs(0, 0)\n dfs(0, nums[0])\n return res\n \n function dfs(i, cur) {\n if(i === n) return\n if(cur === max) return res += Math.pow(2, n - 1 - i)\n dfs(i + 1, cur)\n dfs(i + 1, cur | nums[i + 1])\n }\n};"
] |
|
2,045 | second-minimum-time-to-reach-destination | [
"How much is change actually necessary while calculating the required path?",
"How many extra edges do we need to add to the shortest path?"
] | /**
* @param {number} n
* @param {number[][]} edges
* @param {number} time
* @param {number} change
* @return {number}
*/
var secondMinimum = function(n, edges, time, change) {
}; | A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes.
Each vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time. You can enter a vertex at any time, but can leave a vertex only when the signal is green. You cannot wait at a vertex if the signal is green.
The second minimum value is defined as the smallest value strictly larger than the minimum value.
For example the second minimum value of [2, 3, 4] is 3, and the second minimum value of [2, 2, 4] is 4.
Given n, edges, time, and change, return the second minimum time it will take to go from vertex 1 to vertex n.
Notes:
You can go through any vertex any number of times, including 1 and n.
You can assume that when the journey starts, all signals have just turned green.
Example 1:
Input: n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5
Output: 13
Explanation:
The figure on the left shows the given graph.
The blue path in the figure on the right is the minimum time path.
The time taken is:
- Start at 1, time elapsed=0
- 1 -> 4: 3 minutes, time elapsed=3
- 4 -> 5: 3 minutes, time elapsed=6
Hence the minimum time needed is 6 minutes.
The red path shows the path to get the second minimum time.
- Start at 1, time elapsed=0
- 1 -> 3: 3 minutes, time elapsed=3
- 3 -> 4: 3 minutes, time elapsed=6
- Wait at 4 for 4 minutes, time elapsed=10
- 4 -> 5: 3 minutes, time elapsed=13
Hence the second minimum time is 13 minutes.
Example 2:
Input: n = 2, edges = [[1,2]], time = 3, change = 2
Output: 11
Explanation:
The minimum time path is 1 -> 2 with time = 3 minutes.
The second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.
Constraints:
2 <= n <= 104
n - 1 <= edges.length <= min(2 * 104, n * (n - 1) / 2)
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
There are no duplicate edges.
Each vertex can be reached directly or indirectly from every other vertex.
1 <= time, change <= 103
| Hard | [
"breadth-first-search",
"graph",
"shortest-path"
] | [
"const initializeGraph = (n) => {\n let G = []\n for (let i = 0; i < n; i++) {\n G.push([])\n }\n return G\n}\nconst addEdgeToG = (G, Edges) => {\n for (const [u, v] of Edges) {\n G[u].push(v)\n G[v].push(u)\n }\n}\n\nconst secondMinimum = (n, edges, time, change) => {\n let adj = initializeGraph(n + 1)\n addEdgeToG(adj, edges)\n let cost = initializeGraph(n + 1)\n let pq = new MinPriorityQueue({ priority: (x) => x[0] })\n pq.enqueue([0, 1])\n let green = 2 * change\n while (pq.size()) {\n let cur = pq.dequeue().element\n let [t, node] = cur\n if (cost[node].length == 2) continue\n let nextT =\n t % green < change ? t : (((t + green - 1) / green) >> 0) * green\n let cn = cost[node].length\n if (node == n) {\n if (cn == 0 || cost[node][cn - 1] != t) {\n cost[node].push(t)\n } else {\n continue\n }\n } else {\n if (cn == 0 || cost[node][cn - 1] != nextT) {\n cost[node].push(nextT)\n } else {\n continue\n }\n }\n for (const next_node of adj[node]) pq.enqueue([nextT + time, next_node])\n }\n return cost[n][1]\n}",
" var secondMinimum = function (n, edges, time, change) {\n const graph = new Map()\n for (let i = 1; i <= n; i++) graph.set(i, [])\n for (const [u, v] of edges) {\n graph.get(u).push(v)\n graph.get(v).push(u)\n }\n const first = Array(n + 1).fill(Infinity)\n const second = Array(n + 1).fill(Infinity)\n first[1] = 0\n\n const q = new MinPriorityQueue()\n q.enqueue(1, 0)\n\n while (q.size()) {\n let {element: node, priority: cur} = q.dequeue()\n cur += time // cur: arrival time\n let leave = cur\n if (~~(cur / change) & 1) leave += change - (cur % change)\n for (let nei of graph.get(node)) {\n if (second[nei] <= cur) continue\n if (first[nei] === cur) continue\n if (first[nei] > cur) {\n second[nei] = first[nei]\n first[nei] = cur\n } else {\n second[nei] = cur\n }\n q.enqueue(nei, leave)\n }\n }\n return second[n]\n}"
] |
|
2,047 | number-of-valid-words-in-a-sentence | [
"Iterate through the string to split it by spaces.",
"Count the number of characters of each type (letters, numbers, hyphens, and punctuations)."
] | /**
* @param {string} sentence
* @return {number}
*/
var countValidWords = function(sentence) {
}; | A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.
A token is a valid word if all three of the following are true:
It only contains lowercase letters, hyphens, and/or punctuation (no digits).
There is at most one hyphen '-'. If present, it must be surrounded by lowercase characters ("a-b" is valid, but "-ab" and "ab-" are not valid).
There is at most one punctuation mark. If present, it must be at the end of the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid).
Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!".
Given a string sentence, return the number of valid words in sentence.
Example 1:
Input: sentence = "cat and dog"
Output: 3
Explanation: The valid words in the sentence are "cat", "and", and "dog".
Example 2:
Input: sentence = "!this 1-s b8d!"
Output: 0
Explanation: There are no valid words in the sentence.
"!this" is invalid because it starts with a punctuation mark.
"1-s" and "b8d" are invalid because they contain digits.
Example 3:
Input: sentence = "alice and bob are playing stone-game10"
Output: 5
Explanation: The valid words in the sentence are "alice", "and", "bob", "are", and "playing".
"stone-game10" is invalid because it contains digits.
Constraints:
1 <= sentence.length <= 1000
sentence only contains lowercase English letters, digits, ' ', '-', '!', '.', and ','.
There will be at least 1 token.
| Easy | [
"string"
] | [
"const countValidWords = function(s) {\n const arr = s.split(' ')\n let res = 0\n for(const e of arr) {\n if(e.trim() && valid(e.trim())) res ++\n }\n return res\n};\n \nfunction valid(e) {\n const zi = '0'.charCodeAt(0), ni = '9'.charCodeAt(0)\n const len = e.length\n for(const el of e) {\n if(el.charCodeAt(0) >= zi && el.charCodeAt(0) <= ni) return false\n }\n const num = (p, n) => (p >= 'a' && p <= 'z') && (n >= 'a' && n <= 'z')\n const hi = e.indexOf('-')\n if(hi !== -1) {\n if(hi === 0 || hi === e.length - 1 || e.indexOf('-', hi + 1) !== -1 || !num(e[hi - 1], e[hi + 1])) return false\n }\n \n const p1 = e.indexOf('!')\n if(p1 !== -1) {\n if((len > 1 && p1 !== e.length - 1) || e.indexOf('-', p1 + 1) !== -1) return false\n }\n \n const p2 = e.indexOf('.')\n if(p2 !== -1) {\n if((len > 1 && p2 !== e.length - 1) || e.indexOf('-', p2 + 1) !== -1) return false\n }\n \n const p3 = e.indexOf(',')\n if(p3 !== -1) {\n if((len > 1 && p3 !== e.length - 1) || e.indexOf('-', p3 + 1) !== -1) return false\n }\n \n return true\n}"
] |
|
2,048 | next-greater-numerically-balanced-number | [
"How far away can the next greater numerically balanced number be from n?",
"With the given constraints, what is the largest numerically balanced number?"
] | /**
* @param {number} n
* @return {number}
*/
var nextBeautifulNumber = function(n) {
}; | An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x.
Given an integer n, return the smallest numerically balanced number strictly greater than n.
Example 1:
Input: n = 1
Output: 22
Explanation:
22 is numerically balanced since:
- The digit 2 occurs 2 times.
It is also the smallest numerically balanced number strictly greater than 1.
Example 2:
Input: n = 1000
Output: 1333
Explanation:
1333 is numerically balanced since:
- The digit 1 occurs 1 time.
- The digit 3 occurs 3 times.
It is also the smallest numerically balanced number strictly greater than 1000.
Note that 1022 cannot be the answer because 0 appeared more than 0 times.
Example 3:
Input: n = 3000
Output: 3133
Explanation:
3133 is numerically balanced since:
- The digit 1 occurs 1 time.
- The digit 3 occurs 3 times.
It is also the smallest numerically balanced number strictly greater than 3000.
Constraints:
0 <= n <= 106
| Medium | [
"math",
"backtracking",
"enumeration"
] | [
"const nextBeautifulNumber = function(n) {\n while (true) {\n ++n;\n if (balance(n)) return n;\n } \n function balance(n) {\n let cnt = Array(10).fill(0);\n while (n) {\n if (n % 10 == 0) return false; // no 0 allowed\n cnt[n % 10]++;\n n = ~~(n / 10);\n }\n for (let i = 1; i < 10; ++i) {\n if (cnt[i] && cnt[i] !== i) return false;\n }\n return true;\n }\n};"
] |
|
2,049 | count-nodes-with-the-highest-score | [
"For each node, you need to find the sizes of the subtrees rooted in each of its children. Maybe DFS?",
"How to determine the number of nodes in the rest of the tree? Can you subtract the size of the subtree rooted at the node from the total number of nodes of the tree?",
"Use these values to compute the score of the node. Track the maximum score, and how many nodes achieve such score."
] | /**
* @param {number[]} parents
* @return {number}
*/
var countHighestScoreNodes = function(parents) {
}; | There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1.
Each node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees.
Return the number of nodes that have the highest score.
Example 1:
Input: parents = [-1,2,0,2,0]
Output: 3
Explanation:
- The score of node 0 is: 3 * 1 = 3
- The score of node 1 is: 4 = 4
- The score of node 2 is: 1 * 1 * 2 = 2
- The score of node 3 is: 4 = 4
- The score of node 4 is: 4 = 4
The highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.
Example 2:
Input: parents = [-1,2,0]
Output: 2
Explanation:
- The score of node 0 is: 2 = 2
- The score of node 1 is: 2 = 2
- The score of node 2 is: 1 * 1 = 1
The highest score is 2, and two nodes (node 0 and node 1) have the highest score.
Constraints:
n == parents.length
2 <= n <= 105
parents[0] == -1
0 <= parents[i] <= n - 1 for i != 0
parents represents a valid binary tree.
| Medium | [
"array",
"tree",
"depth-first-search",
"binary-tree"
] | [
"const countHighestScoreNodes = function(parents) {\n const n = parents.length, graph = {}, hash = {}\n for(let i = 1; i < n; i++) {\n if(graph[parents[i]] == null) graph[parents[i]] = []\n graph[parents[i]].push(i)\n }\n dfs(0)\n \n function dfs(node) {\n let product = 1, num = 0\n for(let child of (graph[node] || [])) {\n const tmp = dfs(child)\n product *= tmp\n num += tmp\n }\n if(n - 1 - num > 0) product *= (n - 1 - num)\n hash[product] = (hash[product] || 0) + 1\n return num + 1\n }\n const maxKey = Math.max(...Object.keys(hash))\n return hash[maxKey]\n};",
"const countHighestScoreNodes = function(parents) {\n const n = parents.length, hash = {}, graph = {}\n for(let i = 1; i < n; i++) {\n if(graph[parents[i]] == null) graph[parents[i]] = []\n graph[parents[i]].push(i)\n }\n\n dfs(0)\n const mk = Math.max(...Object.keys(hash))\n return hash[mk]\n \n function dfs(i) {\n let num = 0, prod = 1\n for(const e of (graph[i] || []) ) {\n const tmp = dfs(e)\n num += tmp\n prod *= tmp\n }\n \n if(n - 1 - num > 0) prod *= (n - 1 - num)\n hash[prod] = (hash[prod] || 0) + 1\n\n return num + 1\n }\n};"
] |
|
2,050 | parallel-courses-iii | [
"What is the earliest time a course can be taken?",
"How would you solve the problem if all courses take equal time?",
"How would you generalize this approach?"
] | /**
* @param {number} n
* @param {number[][]} relations
* @param {number[]} time
* @return {number}
*/
var minimumTime = function(n, relations, time) {
}; | You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.
You must find the minimum number of months needed to complete all the courses following these rules:
You may start taking a course at any time if the prerequisites are met.
Any number of courses can be taken at the same time.
Return the minimum number of months needed to complete all the courses.
Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).
Example 1:
Input: n = 3, relations = [[1,3],[2,3]], time = [3,2,5]
Output: 8
Explanation: The figure above represents the given graph and the time required to complete each course.
We start course 1 and course 2 simultaneously at month 0.
Course 1 takes 3 months and course 2 takes 2 months to complete respectively.
Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.
Example 2:
Input: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]
Output: 12
Explanation: The figure above represents the given graph and the time required to complete each course.
You can start courses 1, 2, and 3 at month 0.
You can complete them after 1, 2, and 3 months respectively.
Course 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.
Course 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months.
Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.
Constraints:
1 <= n <= 5 * 104
0 <= relations.length <= min(n * (n - 1) / 2, 5 * 104)
relations[j].length == 2
1 <= prevCoursej, nextCoursej <= n
prevCoursej != nextCoursej
All the pairs [prevCoursej, nextCoursej] are unique.
time.length == n
1 <= time[i] <= 104
The given graph is a directed acyclic graph.
| Hard | [
"array",
"dynamic-programming",
"graph",
"topological-sort"
] | [
"const minimumTime = function (n, relations, time) {\n const inDegree = Array(n + 1).fill(0)\n const graph = {}, dist = Array(n + 1).fill(0)\n \n for(const [pre, nxt] of relations) {\n if(graph[pre] == null) graph[pre] = []\n graph[pre].push(nxt)\n inDegree[nxt]++\n }\n\n let q = []\n for(let i = 1;i <=n;i++) {\n if(inDegree[i]===0) {\n q.push(i)\n dist[i] = time[i - 1]\n }\n }\n while(q.length) {\n const size = q.length, nxt = []\n\n for(let i = 0; i < size; i++) {\n const cur = q[i]\n for(const e of (graph[cur] || [])) {\n dist[e] = Math.max(dist[e], dist[cur] + time[e - 1])\n inDegree[e]--\n if(inDegree[e] === 0) {\n nxt.push(e)\n }\n }\n }\n\n q = nxt\n }\n\n return Math.max(...dist)\n}",
"const minimumTime = function(n, relations, time) {\n const graph = {}, dist = Array(n).fill(0), inDegree = Array(n).fill(0)\n \n for(let [pre, next] of relations) {\n pre--, next--\n if(graph[pre] == null) graph[pre] = []\n graph[pre].push(next)\n inDegree[next]++\n }\n\n const q = []\n for(let i = 0; i < n; i++) {\n if(inDegree[i] === 0) {\n q.push(i)\n dist[i] = time[i]\n }\n }\n\n let res = 0\n while(q.length) {\n const cur = q.shift()\n for(const next of (graph[cur] || [])) {\n dist[next] = Math.max(dist[next], dist[cur] + time[next])\n inDegree[next]--\n if(inDegree[next] === 0) q.push(next)\n }\n }\n \n return Math.max(...dist)\n}",
"const minimumTime = function(n, relations, time) {\n const graph = {}, dist = Array(n).fill(0), inDegree = Array(n).fill(0)\n for(let [from, to] of relations) {\n from--, to--\n if (graph[from] == null) graph[from] = []\n graph[from].push(to)\n inDegree[to]++\n }\n const q = []\n for(let i = 0; i < n; i++) {\n if(inDegree[i] === 0) {\n q.push(i)\n dist[i] = time[i]\n }\n }\n\n while(q.length) {\n const u = q.shift()\n for(const v of (graph[u] || [])) {\n dist[v] = Math.max(dist[v], dist[u] + time[v])\n if(--inDegree[v] === 0) q.push(v)\n }\n }\n\n let res = 0\n for(let e of dist) {\n if(e > res) res = e\n }\n return res\n};"
] |
|
2,053 | kth-distinct-string-in-an-array | [
"Try 'mapping' the strings to check if they are unique or not."
] | /**
* @param {string[]} arr
* @param {number} k
* @return {string}
*/
var kthDistinct = function(arr, k) {
}; | A distinct string is a string that is present only once in an array.
Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string "".
Note that the strings are considered in the order in which they appear in the array.
Example 1:
Input: arr = ["d","b","c","b","c","a"], k = 2
Output: "a"
Explanation:
The only distinct strings in arr are "d" and "a".
"d" appears 1st, so it is the 1st distinct string.
"a" appears 2nd, so it is the 2nd distinct string.
Since k == 2, "a" is returned.
Example 2:
Input: arr = ["aaa","aa","a"], k = 1
Output: "aaa"
Explanation:
All strings in arr are distinct, so the 1st string "aaa" is returned.
Example 3:
Input: arr = ["a","b","a"], k = 3
Output: ""
Explanation:
The only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string "".
Constraints:
1 <= k <= arr.length <= 1000
1 <= arr[i].length <= 5
arr[i] consists of lowercase English letters.
| Easy | [
"array",
"hash-table",
"string",
"counting"
] | [
"const kthDistinct = function(arr, k) {\n let num = 0, hash = {}\n \n for(let str of arr) {\n if(hash[str] == null) hash[str] = 0\n hash[str]++ \n }\n for(let str of arr) {\n if(hash[str] > 1) continue\n num++\n if(num === k) return str\n }\n return ''\n};"
] |
|
2,054 | two-best-non-overlapping-events | [
"How can sorting the events on the basis of their start times help? How about end times?",
"How can we quickly get the maximum score of an interval not intersecting with the interval we chose?"
] | /**
* @param {number[][]} events
* @return {number}
*/
var maxTwoEvents = function(events) {
}; | You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei. You can choose at most two non-overlapping events to attend such that the sum of their values is maximized.
Return this maximum sum.
Note that the start time and end time is inclusive: that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t, the next event must start at or after t + 1.
Example 1:
Input: events = [[1,3,2],[4,5,2],[2,4,3]]
Output: 4
Explanation: Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.
Example 2:
Input: events = [[1,3,2],[4,5,2],[1,5,5]]
Output: 5
Explanation: Choose event 2 for a sum of 5.
Example 3:
Input: events = [[1,5,3],[1,5,1],[6,6,5]]
Output: 8
Explanation: Choose events 0 and 2 for a sum of 3 + 5 = 8.
Constraints:
2 <= events.length <= 105
events[i].length == 3
1 <= startTimei <= endTimei <= 109
1 <= valuei <= 106
| Medium | [
"array",
"binary-search",
"dynamic-programming",
"sorting",
"heap-priority-queue"
] | [
"const maxTwoEvents = function(events) {\n const n = events.length\n events.sort((a, b) => a[0] - b[0])\n const dp = Array.from({ length: n }, () => Array(3).fill(-1))\n\n return dfs(0, 0)\n\n function dfs(idx, cnt) {\n if(cnt === 2 || idx >= n) return 0\n if(dp[idx][cnt] === -1) {\n let end = events[idx][1]\n let lo = idx + 1, hi = n - 1;\n while (lo < hi) {\n const mid = lo + ((hi - lo) >> 1);\n if (events[mid][0] <= end) lo = mid + 1\n else hi = mid;\n }\n const include = events[idx][2] + (lo < n && events[lo][0] > end ? dfs(lo, cnt + 1) : 0);\n const exclude = dfs(idx + 1, cnt);\n dp[idx][cnt] = Math.max(include, exclude);\n }\n\n return dp[idx][cnt]\n }\n};",
"const maxTwoEvents = function(events) {\n const n = events.length, { max } = Math\n let res = 0, maxVal = 0;\n const pq = new PriorityQueue((a, b) => a[0] < b[0]);\n events.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])\n for (let e of events) {\n for(; !pq.isEmpty() && pq.peek()[0] < e[0]; pq.pop())\n maxVal = max(maxVal, pq.peek()[1]);\n res = max(res, maxVal + e[2]);\n pq.push([e[1], e[2]]);\n }\n return res;\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}"
] |
|
2,055 | plates-between-candles | [
"Can you find the indices of the most left and right candles for a given substring, perhaps by using binary search (or better) over an array of indices of all the bars?",
"Once the indices of the most left and right bars are determined, how can you efficiently count the number of plates within the range? Prefix sums?"
] | /**
* @param {string} s
* @param {number[][]} queries
* @return {number[]}
*/
var platesBetweenCandles = function(s, queries) {
}; | There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle.
You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes the substring s[lefti...righti] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring.
For example, s = "||**||**|*", and a query [3, 8] denotes the substring "*||**|". The number of plates between candles in this substring is 2, as each of the two plates has at least one candle in the substring to its left and right.
Return an integer array answer where answer[i] is the answer to the ith query.
Example 1:
Input: s = "**|**|***|", queries = [[2,5],[5,9]]
Output: [2,3]
Explanation:
- queries[0] has two plates between candles.
- queries[1] has three plates between candles.
Example 2:
Input: s = "***|**|*****|**||**|*", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]
Output: [9,0,0,0,0]
Explanation:
- queries[0] has nine plates between candles.
- The other queries have zero plates between candles.
Constraints:
3 <= s.length <= 105
s consists of '*' and '|' characters.
1 <= queries.length <= 105
queries[i].length == 2
0 <= lefti <= righti < s.length
| Medium | [
"array",
"string",
"binary-search",
"prefix-sum"
] | [
"const platesBetweenCandles = function (s, queries) {\n const candleIdxArr = []\n const n = s.length\n for(let i = 0; i < n; i++) {\n if(s[i] === '|') candleIdxArr.push(i)\n }\n // console.log(candleIdxArr)\n const res = []\n for(const [s, e] of queries) {\n const l = lower(candleIdxArr, s, e)\n const r = upper(candleIdxArr, s ,e)\n const tmp = (candleIdxArr[r] - candleIdxArr[l] + 1) - (r - l + 1)\n res.push(tmp >= 0 ? tmp : 0)\n }\n\n return res\n\n\n function lower(arr,s,e) {\n let l = 0, r = arr.length - 1\n while(l < r) {\n // console.log('lower',l, r)\n const mid = ~~(l + (r - l)/2)\n if(arr[mid] < s) l = mid + 1\n else r = mid\n }\n return l\n }\n\n function upper(arr,s, e) {\n let l = 0, r = arr.length - 1\n while(l < r) {\n\n const mid = r - ~~((r - l)/2)\n // console.log('upper', l, r, mid, e)\n if(arr[mid] > e) r = mid - 1\n else l = mid\n }\n return l\n }\n}",
"const platesBetweenCandles = function(s, queries) {\n const n = s.length,\n leftCandlePos = Array(n).fill(-1)\n rightCandlePos = Array(n).fill(-1)\n candleCnt = Array(n).fill(0)\n let pos = -1\n for(let i = 0; i < n; i++) {\n if(s[i] === '|') pos = i\n leftCandlePos[i] = pos\n }\n pos = -1\n for(let i = n - 1; i >= 0; i--) {\n if(s[i] === '|') pos = i\n rightCandlePos[i] = pos\n }\n for(let i = 0, cnt = 0; i < n; i++) {\n if(s[i] === '|') cnt++\n candleCnt[i] = cnt\n }\n\n const len = queries.length, res = Array(len).fill(0)\n\n for(let i = 0; i < len; i++) {\n const [left, right] = queries[i]\n const leftCandle = rightCandlePos[left], rightCandle = leftCandlePos[right]\n const delta = rightCandle - leftCandle\n if(leftCandle !== -1 && rightCandle !== -1 && delta > 1) {\n res[i] = delta + 1 - (candleCnt[rightCandle] - candleCnt[leftCandle] + 1)\n }\n }\n\n return res\n}",
"const platesBetweenCandles = function (s, queries) {\n const n = s.length\n const leftArr = Array(n).fill(-1),\n rightArr = Array(n).fill(n),\n candleCnt = Array(n).fill(0)\n let candle = -1\n for (let i = 0; i < n; i++) {\n if (s[i] === '|') candle = i\n leftArr[i] = candle\n }\n candle = n\n for (let i = n - 1; i >= 0; i--) {\n if (s[i] === '|') candle = i\n rightArr[i] = candle\n }\n let cnt = 0\n for (let i = 0; i < n; i++) {\n if (s[i] === '|') cnt++\n candleCnt[i] = cnt\n }\n // console.log(leftArr, rightArr)\n const res = []\n for (const [s, e] of queries) {\n const l = rightArr[s]\n const r = leftArr[e]\n const diff = r - l\n if (diff > 1) {\n const e = r - l + 1 - (candleCnt[r] - candleCnt[l] + 1)\n res.push(e)\n } else res.push(0)\n }\n\n return res\n}"
] |
|
2,056 | number-of-valid-move-combinations-on-chessboard | [
"N is small, we can generate all possible move combinations.",
"For each possible move combination, determine which ones are valid."
] | /**
* @param {string[]} pieces
* @param {number[][]} positions
* @return {number}
*/
var countCombinations = function(pieces, positions) {
}; | There is an 8 x 8 chessboard containing n pieces (rooks, queens, or bishops). You are given a string array pieces of length n, where pieces[i] describes the type (rook, queen, or bishop) of the ith piece. In addition, you are given a 2D integer array positions also of length n, where positions[i] = [ri, ci] indicates that the ith piece is currently at the 1-based coordinate (ri, ci) on the chessboard.
When making a move for a piece, you choose a destination square that the piece will travel toward and stop on.
A rook can only travel horizontally or vertically from (r, c) to the direction of (r+1, c), (r-1, c), (r, c+1), or (r, c-1).
A queen can only travel horizontally, vertically, or diagonally from (r, c) to the direction of (r+1, c), (r-1, c), (r, c+1), (r, c-1), (r+1, c+1), (r+1, c-1), (r-1, c+1), (r-1, c-1).
A bishop can only travel diagonally from (r, c) to the direction of (r+1, c+1), (r+1, c-1), (r-1, c+1), (r-1, c-1).
You must make a move for every piece on the board simultaneously. A move combination consists of all the moves performed on all the given pieces. Every second, each piece will instantaneously travel one square towards their destination if they are not already at it. All pieces start traveling at the 0th second. A move combination is invalid if, at a given time, two or more pieces occupy the same square.
Return the number of valid move combinations.
Notes:
No two pieces will start in the same square.
You may choose the square a piece is already on as its destination.
If two pieces are directly adjacent to each other, it is valid for them to move past each other and swap positions in one second.
Example 1:
Input: pieces = ["rook"], positions = [[1,1]]
Output: 15
Explanation: The image above shows the possible squares the piece can move to.
Example 2:
Input: pieces = ["queen"], positions = [[1,1]]
Output: 22
Explanation: The image above shows the possible squares the piece can move to.
Example 3:
Input: pieces = ["bishop"], positions = [[4,3]]
Output: 12
Explanation: The image above shows the possible squares the piece can move to.
Constraints:
n == pieces.length
n == positions.length
1 <= n <= 4
pieces only contains the strings "rook", "queen", and "bishop".
There will be at most one queen on the chessboard.
1 <= xi, yi <= 8
Each positions[i] is distinct.
| Hard | [
"array",
"string",
"backtracking",
"simulation"
] | null | [] |
2,057 | smallest-index-with-equal-value | [
"Starting with i=0, check the condition for each index. The first one you find to be true is the smallest index."
] | /**
* @param {number[]} nums
* @return {number}
*/
var smallestEqual = function(nums) {
}; | Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist.
x mod y denotes the remainder when x is divided by y.
Example 1:
Input: nums = [0,1,2]
Output: 0
Explanation:
i=0: 0 mod 10 = 0 == nums[0].
i=1: 1 mod 10 = 1 == nums[1].
i=2: 2 mod 10 = 2 == nums[2].
All indices have i mod 10 == nums[i], so we return the smallest index 0.
Example 2:
Input: nums = [4,3,2,1]
Output: 2
Explanation:
i=0: 0 mod 10 = 0 != nums[0].
i=1: 1 mod 10 = 1 != nums[1].
i=2: 2 mod 10 = 2 == nums[2].
i=3: 3 mod 10 = 3 != nums[3].
2 is the only index which has i mod 10 == nums[i].
Example 3:
Input: nums = [1,2,3,4,5,6,7,8,9,0]
Output: -1
Explanation: No index satisfies i mod 10 == nums[i].
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 9
| Easy | [
"array"
] | [
"var smallestEqual = function(nums) {\n const n = nums.length\n for(let i = 0; i < n; i++) {\n if(i % 10 === nums[i]) return i\n }\n return -1\n};"
] |
|
2,058 | find-the-minimum-and-maximum-number-of-nodes-between-critical-points | [
"The maximum distance must be the distance between the first and last critical point.",
"For each adjacent critical point, calculate the difference and check if it is the minimum distance."
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {number[]}
*/
var nodesBetweenCriticalPoints = function(head) {
}; | A critical point in a linked list is defined as either a local maxima or a local minima.
A node is a local maxima if the current node has a value strictly greater than the previous node and the next node.
A node is a local minima if the current node has a value strictly smaller than the previous node and the next node.
Note that a node can only be a local maxima/minima if there exists both a previous node and a next node.
Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1].
Example 1:
Input: head = [3,1]
Output: [-1,-1]
Explanation: There are no critical points in [3,1].
Example 2:
Input: head = [5,3,1,2,5,1,2]
Output: [1,3]
Explanation: There are three critical points:
- [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2.
- [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1.
- [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2.
The minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1.
The maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3.
Example 3:
Input: head = [1,3,2,2,3,2,2,2,7]
Output: [3,3]
Explanation: There are two critical points:
- [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2.
- [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2.
Both the minimum and maximum distances are between the second and the fifth node.
Thus, minDistance and maxDistance is 5 - 2 = 3.
Note that the last node is not considered a local maxima because it does not have a next node.
Constraints:
The number of nodes in the list is in the range [2, 105].
1 <= Node.val <= 105
| Medium | [
"linked-list"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const nodesBetweenCriticalPoints = function(head) {\n const arr = []\n let cur = head\n while(cur) {\n arr.push(cur.val)\n cur = cur.next\n }\n const idxArr = []\n const n = arr.length\n for(let i = 1; i < n - 1; i++) {\n if((arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) || (arr[i] < arr[i - 1] && arr[i] < arr[i + 1])) {\n idxArr.push(i)\n }\n }\n \n let min = Infinity, max = -1\n for(let i = 1; i < idxArr.length; i++) {\n if(idxArr[i] - idxArr[i - 1] < min) min = idxArr[i] - idxArr[i - 1]\n }\n if(idxArr.length > 1) max = idxArr[idxArr.length - 1] - idxArr[0]\n return [min === Infinity ? -1 : min, max]\n};"
] |
2,059 | minimum-operations-to-convert-number | [
"Once x drops below 0 or goes above 1000, is it possible to continue performing operations on x?",
"How can you use BFS to find the minimum operations?"
] | /**
* @param {number[]} nums
* @param {number} start
* @param {number} goal
* @return {number}
*/
var minimumOperations = function(nums, start, goal) {
}; | You are given a 0-indexed integer array nums containing distinct numbers, an integer start, and an integer goal. There is an integer x that is initially set to start, and you want to perform operations on x such that it is converted to goal. You can perform the following operation repeatedly on the number x:
If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x to any of the following:
x + nums[i]
x - nums[i]
x ^ nums[i] (bitwise-XOR)
Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward.
Return the minimum number of operations needed to convert x = start into goal, and -1 if it is not possible.
Example 1:
Input: nums = [2,4,12], start = 2, goal = 12
Output: 2
Explanation: We can go from 2 → 14 → 12 with the following 2 operations.
- 2 + 12 = 14
- 14 - 2 = 12
Example 2:
Input: nums = [3,5,7], start = 0, goal = -4
Output: 2
Explanation: We can go from 0 → 3 → -4 with the following 2 operations.
- 0 + 3 = 3
- 3 - 7 = -4
Note that the last operation sets x out of the range 0 <= x <= 1000, which is valid.
Example 3:
Input: nums = [2,8,16], start = 0, goal = 1
Output: -1
Explanation: There is no way to convert 0 into 1.
Constraints:
1 <= nums.length <= 1000
-109 <= nums[i], goal <= 109
0 <= start <= 1000
start != goal
All the integers in nums are distinct.
| Medium | [
"array",
"breadth-first-search"
] | [
"var minimumOperations = function (nums, start, goal) {\n const visited = Array(1001).fill(0)\n const q = []\n q.push([start, 0])\n visited[start] = 1\n while (q.length) {\n const [val, idx] = q.shift()\n if (val === goal) return idx\n for (let e of nums) {\n if (val + e === goal) return idx + 1\n if (val + e <= 1000 && val + e >= 0 && !visited[val + e]) {\n visited[val + e] = 1\n q.push([val + e, idx + 1])\n }\n if (val - e === goal) return idx + 1\n if (val - e <= 1000 && val - e >= 0 && !visited[val - e]) {\n visited[val - e] = 1\n q.push([val - e, idx + 1])\n }\n\n if ((val ^ e) === goal) return idx + 1\n if ((val ^ e) <= 1000 && (val ^ e) >= 0 && !visited[val ^ e]) {\n visited[val ^ e] = 1\n q.push([val ^ e, idx + 1])\n }\n }\n }\n\n return -1\n}"
] |
|
2,060 | check-if-an-original-string-exists-given-two-encoded-strings | [
"For s1 and s2, divide each into a sequence of single alphabet strings and digital strings. The problem now becomes comparing if two sequences are equal.",
"A single alphabet string has no variation, but a digital string has variations. For example: \"124\" can be interpreted as 1+2+4, 12+4, 1+24, and 124 wildcard characters.",
"There are four kinds of comparisons: a single alphabet vs another; a single alphabet vs a number, a number vs a single alphabet, and a number vs another number. In the case of a number vs another (a single alphabet or a number), can you decrease the number by the min length of both?",
"There is a recurrence relation in the search which ends when either a single alphabet != another, or one sequence ran out, or both sequences ran out."
] | /**
* @param {string} s1
* @param {string} s2
* @return {boolean}
*/
var possiblyEquals = function(s1, s2) {
}; | An original string, consisting of lowercase English letters, can be encoded by the following steps:
Arbitrarily split it into a sequence of some number of non-empty substrings.
Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).
Concatenate the sequence as the encoded string.
For example, one way to encode an original string "abcdefghijklmnop" might be:
Split it as a sequence: ["ab", "cdefghijklmn", "o", "p"].
Choose the second and third elements to be replaced by their lengths, respectively. The sequence becomes ["ab", "12", "1", "p"].
Concatenate the elements of the sequence to get the encoded string: "ab121p".
Given two encoded strings s1 and s2, consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2. Otherwise, return false.
Note: The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3.
Example 1:
Input: s1 = "internationalization", s2 = "i18n"
Output: true
Explanation: It is possible that "internationalization" was the original string.
- "internationalization"
-> Split: ["internationalization"]
-> Do not replace any element
-> Concatenate: "internationalization", which is s1.
- "internationalization"
-> Split: ["i", "nternationalizatio", "n"]
-> Replace: ["i", "18", "n"]
-> Concatenate: "i18n", which is s2
Example 2:
Input: s1 = "l123e", s2 = "44"
Output: true
Explanation: It is possible that "leetcode" was the original string.
- "leetcode"
-> Split: ["l", "e", "et", "cod", "e"]
-> Replace: ["l", "1", "2", "3", "e"]
-> Concatenate: "l123e", which is s1.
- "leetcode"
-> Split: ["leet", "code"]
-> Replace: ["4", "4"]
-> Concatenate: "44", which is s2.
Example 3:
Input: s1 = "a5b", s2 = "c5b"
Output: false
Explanation: It is impossible.
- The original string encoded as s1 must start with the letter 'a'.
- The original string encoded as s2 must start with the letter 'c'.
Constraints:
1 <= s1.length, s2.length <= 40
s1 and s2 consist of digits 1-9 (inclusive), and lowercase English letters only.
The number of consecutive digits in s1 and s2 does not exceed 3.
| Hard | [
"string",
"dynamic-programming"
] | [
"function possiblyEquals(s1, s2) {\n const n = s1.length, m = s2.length;\n const dp = Array.from({ length: n + 1 }, v => Array.from({ length: m + 1}, w => new Set()));\n dp[0][0].add(0);\n\n for (let i = 0; i <= n; i++) {\n for (let j = 0; j <= m; j++) {\n for (let delta of dp[i][j]) {\n // s1 is number\n let num = 0;\n if (delta <= 0) {\n for (let p = i; i < Math.min(i + 3, n); p++) {\n if (isDigit(s1[p])) {\n num = num * 10 + Number(s1[p]);\n dp[p + 1][j].add(delta + num);\n } else {\n break;\n }\n }\n }\n\n // s2 is number\n num = 0;\n if (delta >= 0) {\n for (let q = j; q < Math.min(j + 3, m); q++) {\n if (isDigit(s2[q])) {\n num = num * 10 + Number(s2[q]);\n dp[i][q + 1].add(delta - num);\n } else {\n break;\n }\n }\n }\n\n // match s1 non-digit character\n if (i < n && delta < 0 && !isDigit(s1[i])) {\n dp[i + 1][j].add(delta + 1);\n }\n\n // match s2 non-digit character\n if (j < m && delta > 0 && !isDigit(s2[j])) {\n dp[i][j + 1].add(delta - 1);\n }\n\n // two non-digit character match\n if (i < n && j < m && delta == 0 && s1[i] == s2[j]) {\n dp[i + 1][j + 1].add(0);\n }\n\n }\n }\n }\n return dp[n][m].has(0);\n};\n\nfunction isDigit(char) {\n return (/^\\d{1}$/g).test(char);\n}",
"const possiblyEquals = function(s1, s2) {\n const n = s1.length\n const m = s2.length\n const memo = Array.from({ length: n + 1 }, () =>\n Array.from({ length: m + 1 }, () => Array(1001).fill(null))\n )\n memo[0][0][1000] = true\n \n return dfs(0, 0, 0)\n\n function dfs(i, j, diff) {\n if(memo[i][j][diff] != null) return memo[i][j][diff]\n let res = false\n if (i == n && j == m) res = diff === 0\n else if (i < n && isDigit(s1[i])) {\n let ii = i\n while (ii < n && isDigit( s1[ii] )) ii += 1\n for (let x of helper(s1.slice(i, ii))) {\n if (dfs(ii, j, diff-x)) res = true \n }\n } else if (j < m && isDigit( s2[j] )) {\n let jj = j \n while (jj < m && isDigit( s2[jj] )) jj += 1\n for (let y of helper(s2.slice(j, jj))) {\n if (dfs(i, jj, diff+y)) res = true \n }\n } else if (diff == 0) {\n if (i < n && j < m && s1[i] == s2[j]) res = dfs(i+1, j+1, 0)\n } else if (diff > 0) {\n if (i < n) res = dfs(i+1, j, diff-1)\n } else {\n if (j < m) res = dfs(i, j+1, diff+1)\n }\n\n memo[i][j][diff] = res\n return res\n }\n\n function isDigit(ch) {\n return ch >= '0' && ch <= '9'\n }\n\n function helper(str) {\n const ans = new Set()\n ans.add(+str)\n for(let i = 1, len = str.length; i < len; i++) {\n const pre = helper(str.slice(0, i))\n const post = helper(str.slice(i))\n for(let p of pre) {\n for(let n of post) {\n ans.add(p + n)\n }\n }\n }\n return Array.from(ans)\n }\n};",
"var possiblyEquals = function (s1, s2) {\n let n = s1.length\n let m = s2.length\n const f = Array.from({ length: n + 1 }, () =>\n Array.from({ length: m + 1 }, () => Array(1001).fill(false))\n )\n f[0][0][1000] = true\n\n for (let i = 0; i <= n; i++)\n for (let j = 0; j <= m; j++)\n for (let k = 0; k < 2000; k++) {\n if (!f[i][j][k]) continue\n // if k==1000 means length diff is 0, so check both next charactors.\n if (i + 1 <= n && j + 1 <= m && k == 1000 && s1[i] == s2[j]) {\n f[i + 1][j + 1][k] = true\n }\n // if first string is longer or same length, extend second string.\n if (k >= 1000 && j + 1 <= m) {\n if (s2[j] >= 'a' && s2[j] <= 'z') {\n // do not extend to be a longer string using a-z.\n if (k > 1000) {\n f[i][j + 1][k - 1] = true\n }\n } else if (s2[j] > '0') {\n let cur = 0\n for (let r = j; r < m; r++) {\n if (s2[r] >= '0' && s2[r] <= '9') {\n cur = cur * 10 + (s2[r] - '0')\n f[i][r + 1][k - cur] = true\n } else break\n }\n }\n }\n // if second string is longer or same length, extend first string.\n if (k <= 1000 && i + 1 <= n) {\n if (s1[i] >= 'a' && s1[i] <= 'z') {\n if (k < 1000) {\n f[i + 1][j][k + 1] = true\n }\n } else if (s1[i] > '0') {\n let cur = 0\n for (let r = i; r < n; r++) {\n if (s1[r] >= '0' && s1[r] <= '9') {\n cur = cur * 10 + (s1[r] - '0')\n f[r + 1][j][k + cur] = true\n } else break\n }\n }\n }\n }\n return f[n][m][1000]\n}"
] |
|
2,062 | count-vowel-substrings-of-a-string | [
"While generating substrings starting at any index, do you need to continue generating larger substrings if you encounter a consonant?",
"Can you store the count of characters to avoid generating substrings altogether?"
] | /**
* @param {string} word
* @return {number}
*/
var countVowelSubstrings = function(word) {
}; | A substring is a contiguous (non-empty) sequence of characters within a string.
A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it.
Given a string word, return the number of vowel substrings in word.
Example 1:
Input: word = "aeiouu"
Output: 2
Explanation: The vowel substrings of word are as follows (underlined):
- "aeiouu"
- "aeiouu"
Example 2:
Input: word = "unicornarihan"
Output: 0
Explanation: Not all 5 vowels are present, so there are no vowel substrings.
Example 3:
Input: word = "cuaieuouac"
Output: 7
Explanation: The vowel substrings of word are as follows (underlined):
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
Constraints:
1 <= word.length <= 100
word consists of lowercase English letters only.
| Easy | [
"hash-table",
"string"
] | [
"const countVowelSubstrings = function(word) {\n let res = 0, n= word.length\n for(let i = 0; i < n - 1;i++) {\n for(let j = i + 1;j < n; j++) {\n if(valid(word, i, j)) res++\n }\n }\n \n return res\n \n function valid(s, i, j) {\n const set = new Set(['a', 'e', 'i', 'o','u'])\n const vis = new Set()\n for(let idx = i; idx <= j; idx++) {\n if(!set.has(s[idx])) return false\n else {\n vis.add(s[idx])\n }\n }\n // console.log(vis)\n return vis.size === 5\n }\n};"
] |
|
2,063 | vowels-of-all-substrings | [
"Since generating substrings is not an option, can we count the number of substrings a vowel appears in?",
"How much does each vowel contribute to the total sum?"
] | /**
* @param {string} word
* @return {number}
*/
var countVowels = function(word) {
}; | Given a string word, return the sum of the number of vowels ('a', 'e', 'i', 'o', and 'u') in every substring of word.
A substring is a contiguous (non-empty) sequence of characters within a string.
Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations.
Example 1:
Input: word = "aba"
Output: 6
Explanation:
All possible substrings are: "a", "ab", "aba", "b", "ba", and "a".
- "b" has 0 vowels in it
- "a", "ab", "ba", and "a" have 1 vowel each
- "aba" has 2 vowels in it
Hence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6.
Example 2:
Input: word = "abc"
Output: 3
Explanation:
All possible substrings are: "a", "ab", "abc", "b", "bc", and "c".
- "a", "ab", and "abc" have 1 vowel each
- "b", "bc", and "c" have 0 vowels each
Hence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.
Example 3:
Input: word = "ltcd"
Output: 0
Explanation: There are no vowels in any substring of "ltcd".
Constraints:
1 <= word.length <= 105
word consists of lowercase English letters.
| Medium | [
"math",
"string",
"dynamic-programming",
"combinatorics"
] | [
"const countVowels = function(word) {\n let res = 0n\n const n = BigInt(word.length)\n const set = new Set(['a', 'e', 'i', 'o', 'u'])\n const dp = Array(n + 1n).fill(0n)\n for(let i = 0n; i < n; i++) {\n const ch = word[i]\n if(set.has(ch)) dp[i + 1n] = dp[i] + (i + 1n)\n else dp[i + 1n] = dp[i]\n }\n \n for(const e of dp) res += e\n return res\n};"
] |
|
2,064 | minimized-maximum-of-products-distributed-to-any-store | [
"There exists a monotonic nature such that when x is smaller than some number, there will be no way to distribute, and when x is not smaller than that number, there will always be a way to distribute.",
"If you are given a number k, where the number of products given to any store does not exceed k, could you determine if all products can be distributed?",
"Implement a function canDistribute(k), which returns true if you can distribute all products such that any store will not be given more than k products, and returns false if you cannot. Use this function to binary search for the smallest possible k."
] | /**
* @param {number} n
* @param {number[]} quantities
* @return {number}
*/
var minimizedMaximum = function(n, quantities) {
}; | You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type.
You need to distribute all products to the retail stores following these rules:
A store can only be given at most one product type but can be given any amount of it.
After distribution, each store will have been given some number of products (possibly 0). Let x represent the maximum number of products given to any store. You want x to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store.
Return the minimum possible x.
Example 1:
Input: n = 6, quantities = [11,6]
Output: 3
Explanation: One optimal way is:
- The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3
- The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3
The maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.
Example 2:
Input: n = 7, quantities = [15,10,10]
Output: 5
Explanation: One optimal way is:
- The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5
- The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5
- The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5
The maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.
Example 3:
Input: n = 1, quantities = [100000]
Output: 100000
Explanation: The only optimal way is:
- The 100000 products of type 0 are distributed to the only store.
The maximum number of products given to any store is max(100000) = 100000.
Constraints:
m == quantities.length
1 <= m <= n <= 105
1 <= quantities[i] <= 105
| Medium | [
"array",
"binary-search"
] | [
"const minimizedMaximum = function(n, quantities) {\n const m = quantities.length\n let l = 0, r = Math.max(...quantities)\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 \n return l\n\n function valid(mid) {\n if(m > n) return false\n let res = 0\n for (let i = 0; i < m; i++) {\n res += Math.ceil(quantities[i] / mid)\n }\n return res <= n\n }\n};",
"var minimizedMaximum = function(n, quantities) {\n let MAX = 0;\n for (let x of quantities) MAX = Math.max(x, MAX);\n let l = 1, r = MAX;\n while (l < r) {\n let mid = Math.floor((l + r) / 2);\n if (valid(quantities, mid) <= n) r = mid;\n else l = mid + 1;\n }\n return l; \n};\n\n\n\n function valid(quantities, max) {\n let cnt = 0;\n for (let x of quantities) cnt += Math.floor(x / max) + ((x % max) ? 1 : 0);\n return cnt;\n }",
"const minimizedMaximum = function(n, quantities) {\n let MAX = 0;\n for (let x of quantities) MAX = Math.max(x, MAX);\n let l = 1, r = MAX;\n while (l < r) {\n let mid = Math.floor((l + r) / 2);\n if (valid(quantities, mid, n)) l = mid + 1;\n else r = mid;\n }\n return l; \n};\n\nfunction valid(quantities, max, n) {\n let cnt = 0;\n for (let x of quantities) cnt += Math.floor(x / max) + ((x % max) ? 1 : 0);\n return cnt > n;\n}"
] |
|
2,065 | maximum-path-quality-of-a-graph | [
"How many nodes can you visit within maxTime seconds?",
"Can you try every valid path?"
] | /**
* @param {number[]} values
* @param {number[][]} edges
* @param {number} maxTime
* @return {number}
*/
var maximalPathQuality = function(values, edges, maxTime) {
}; | There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes. Finally, you are given an integer maxTime.
A valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum).
Return the maximum quality of a valid path.
Note: There are at most four edges connected to each node.
Example 1:
Input: values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49
Output: 75
Explanation:
One possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49.
The nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75.
Example 2:
Input: values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30
Output: 25
Explanation:
One possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30.
The nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25.
Example 3:
Input: values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50
Output: 7
Explanation:
One possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50.
The nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.
Constraints:
n == values.length
1 <= n <= 1000
0 <= values[i] <= 108
0 <= edges.length <= 2000
edges[j].length == 3
0 <= uj < vj <= n - 1
10 <= timej, maxTime <= 100
All the pairs [uj, vj] are unique.
There are at most four edges connected to each node.
The graph may not be connected.
| Hard | [
"array",
"backtracking",
"graph"
] | [
"const maximalPathQuality = function(values, edges, maxTime) {\n const graph = {}, n = values.length\n for(const [u, v, t] of edges) {\n if(graph[u] == null) graph[u] = []\n if(graph[v] == null) graph[v] = []\n graph[u].push([v, t])\n graph[v].push([u, t])\n }\n let res = 0, visited = new Array(n).fill(0)\n visited[0] = 1\n bt(0, values[0], 0)\n return res\n\n function bt(i, val, time) {\n if(time > maxTime) return\n if(i === 0) res = Math.max(res, val)\n \n for(const [next, nextTime] of (graph[i] || [])) {\n const nextVal = visited[next] > 0 ? val : val + values[next]\n visited[next]++\n bt(next, nextVal, time + nextTime)\n visited[next]--\n }\n }\n};",
"const maximalPathQuality = function(values, edges, maxTime) {\n const graph = {}, n = values.length\n for(const [u, v, t] of edges) {\n if(graph[u] == null) graph[u] = []\n if(graph[v] == null) graph[v] = []\n graph[u].push([v, t])\n graph[v].push([u, t])\n }\n let res = 0, visited = Array(n).fill(false)\n bt(0, 0, 0)\n return res\n\n function bt(i, cur, time) {\n if(time > maxTime) return\n const backup = visited[i]\n if(!visited[i]) {\n visited[i] = true\n cur += values[i]\n }\n\n if(i === 0) {\n res = Math.max(res, cur)\n }\n\n for(const [next, nextTime] of (graph[i] || [])) {\n bt(next, cur, time + nextTime)\n }\n visited[i] = backup\n }\n};",
"const maximalPathQuality = function(values, edges, maxTime) {\n let zeroMax = 0;\n let n = values.length;\n let ll = Array.from({length: n + 1}, () => [])\n for (let edge of edges) {\n let u = edge[0];\n let v = edge[1];\n let t = edge[2];\n ll[u].push([v, t]);\n ll[v].push([u, t]);\n }\n const visited = Array(n + 1).fill(false);\n dfs(0, 0, 0, maxTime, visited);\n return zeroMax;\n\n function dfs(val, curNode, curTime, maxTime, visited) {\n if (curTime > maxTime) {\n return;\n }\n let before = visited[curNode];\n if (!visited[curNode]) {\n val += values[curNode];\n visited[curNode] = true;\n }\n if (curNode == 0) {\n zeroMax = Math.max(zeroMax, val);\n }\n for (let next of (ll[curNode] || [])) {\n dfs(val, next[0], curTime + next[1], maxTime, visited);\n }\n visited[curNode] = before;\n }\n};"
] |
|
2,068 | check-whether-two-strings-are-almost-equivalent | [
"What data structure can we use to count the frequency of each character?",
"Are there edge cases where a character is present in one string but not the other?"
] | /**
* @param {string} word1
* @param {string} word2
* @return {boolean}
*/
var checkAlmostEquivalent = function(word1, word2) {
}; | Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3.
Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise.
The frequency of a letter x is the number of times it occurs in the string.
Example 1:
Input: word1 = "aaaa", word2 = "bccb"
Output: false
Explanation: There are 4 'a's in "aaaa" but 0 'a's in "bccb".
The difference is 4, which is more than the allowed 3.
Example 2:
Input: word1 = "abcdeef", word2 = "abaaacc"
Output: true
Explanation: The differences between the frequencies of each letter in word1 and word2 are at most 3:
- 'a' appears 1 time in word1 and 4 times in word2. The difference is 3.
- 'b' appears 1 time in word1 and 1 time in word2. The difference is 0.
- 'c' appears 1 time in word1 and 2 times in word2. The difference is 1.
- 'd' appears 1 time in word1 and 0 times in word2. The difference is 1.
- 'e' appears 2 times in word1 and 0 times in word2. The difference is 2.
- 'f' appears 1 time in word1 and 0 times in word2. The difference is 1.
Example 3:
Input: word1 = "cccddabba", word2 = "babababab"
Output: true
Explanation: The differences between the frequencies of each letter in word1 and word2 are at most 3:
- 'a' appears 2 times in word1 and 4 times in word2. The difference is 2.
- 'b' appears 2 times in word1 and 5 times in word2. The difference is 3.
- 'c' appears 3 times in word1 and 0 times in word2. The difference is 3.
- 'd' appears 2 times in word1 and 0 times in word2. The difference is 2.
Constraints:
n == word1.length == word2.length
1 <= n <= 100
word1 and word2 consist only of lowercase English letters.
| Easy | [
"hash-table",
"string",
"counting"
] | [
"const checkAlmostEquivalent = function(word1, word2) {\n const a = 'a'.charCodeAt(0), n = word1.length\n const arr1 = Array(26).fill(0), arr2 = Array(26).fill(0)\n \n for(const ch of word1) {\n arr1[ch.charCodeAt(0) - a]++\n }\n for(const ch of word2) {\n arr2[ch.charCodeAt(0) - a]++\n }\n for(let i = 0; i < 26; i++) {\n if(Math.abs(arr1[i] - arr2[i]) > 3) return false\n }\n \n return true\n};"
] |
|
2,069 | walking-robot-simulation-ii | [
"The robot only moves along the perimeter of the grid. Can you think if modulus can help you quickly compute which cell it stops at?",
"After the robot moves one time, whenever the robot stops at some cell, it will always face a specific direction. i.e., The direction it faces is determined by the cell it stops at.",
"Can you precompute what direction it faces when it stops at each cell along the perimeter, and reuse the results?"
] | /**
* @param {number} width
* @param {number} height
*/
var Robot = function(width, height) {
};
/**
* @param {number} num
* @return {void}
*/
Robot.prototype.step = function(num) {
};
/**
* @return {number[]}
*/
Robot.prototype.getPos = function() {
};
/**
* @return {string}
*/
Robot.prototype.getDir = function() {
};
/**
* Your Robot object will be instantiated and called as such:
* var obj = new Robot(width, height)
* obj.step(num)
* var param_2 = obj.getPos()
* var param_3 = obj.getDir()
*/ | A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions ("North", "East", "South", and "West"). A robot is initially at cell (0, 0) facing direction "East".
The robot can be instructed to move for a specific number of steps. For each step, it does the following.
Attempts to move forward one cell in the direction it is facing.
If the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees counterclockwise and retries the step.
After the robot finishes moving the number of steps required, it stops and awaits the next instruction.
Implement the Robot class:
Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing "East".
void step(int num) Instructs the robot to move forward num steps.
int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y].
String getDir() Returns the current direction of the robot, "North", "East", "South", or "West".
Example 1:
Input
["Robot", "step", "step", "getPos", "getDir", "step", "step", "step", "getPos", "getDir"]
[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]
Output
[null, null, null, [4, 0], "East", null, null, null, [1, 2], "West"]
Explanation
Robot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.
robot.step(2); // It moves two steps East to (2, 0), and faces East.
robot.step(2); // It moves two steps East to (4, 0), and faces East.
robot.getPos(); // return [4, 0]
robot.getDir(); // return "East"
robot.step(2); // It moves one step East to (5, 0), and faces East.
// Moving the next step East would be out of bounds, so it turns and faces North.
// Then, it moves one step North to (5, 1), and faces North.
robot.step(1); // It moves one step North to (5, 2), and faces North (not West).
robot.step(4); // Moving the next step North would be out of bounds, so it turns and faces West.
// Then, it moves four steps West to (1, 2), and faces West.
robot.getPos(); // return [1, 2]
robot.getDir(); // return "West"
Constraints:
2 <= width, height <= 100
1 <= num <= 105
At most 104 calls in total will be made to step, getPos, and getDir.
| Medium | [
"design",
"simulation"
] | [
"const Robot = function(width, height) {\n this.i = 0\n const pos = Array()\n this.len = width + height - 1 + width - 1 + height - 2\n pos.push( [0,0,3] )\n for(let i = 1; i < width; i++) {\n pos.push([i, 0, 0])\n }\n for(let i = 1; i < height; i++) {\n pos.push([width - 1, i, 1])\n }\n for(let i = 1; i < width; i++) {\n pos.push([width - 1 - i, height - 1, 2])\n }\n for(let i = 1; i < height - 1; i++) {\n pos.push([0, height - 1 - i, 3])\n }\n this.pos = pos\n};\n\n\nRobot.prototype.step = function(num) {\n this.i += num\n};\n\n\nRobot.prototype.getPos = function() {\n return this.pos[this.i % this.len].slice(0, 2)\n};\n\n\nRobot.prototype.getDir = function() {\n const hash = ['East', 'North', 'West', 'South']\n if(this.i === 0) return hash[0]\n else {\n return hash[this.pos[this.i % this.len][2]]\n }\n};"
] |
|
2,070 | most-beautiful-item-for-each-query | [
"Can we process the queries in a smart order to avoid repeatedly checking the same items?",
"How can we use the answer to a query for other queries?"
] | /**
* @param {number[][]} items
* @param {number[]} queries
* @return {number[]}
*/
var maximumBeauty = function(items, queries) {
}; | You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively.
You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0.
Return an array answer of the same length as queries where answer[j] is the answer to the jth query.
Example 1:
Input: items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]
Output: [2,4,5,5,6,6]
Explanation:
- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.
- For queries[1]=2, the items which can be considered are [1,2] and [2,4].
The maximum beauty among them is 4.
- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].
The maximum beauty among them is 5.
- For queries[4]=5 and queries[5]=6, all items can be considered.
Hence, the answer for them is the maximum beauty of all items, i.e., 6.
Example 2:
Input: items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]
Output: [4]
Explanation:
The price of every item is equal to 1, so we choose the item with the maximum beauty 4.
Note that multiple items can have the same price and/or beauty.
Example 3:
Input: items = [[10,1000]], queries = [5]
Output: [0]
Explanation:
No item has a price less than or equal to 5, so no item can be chosen.
Hence, the answer to the query is 0.
Constraints:
1 <= items.length, queries.length <= 105
items[i].length == 2
1 <= pricei, beautyi, queries[j] <= 109
| Medium | [
"array",
"binary-search",
"sorting"
] | null | [] |
2,071 | maximum-number-of-tasks-you-can-assign | [
"Is it possible to assign the first k smallest tasks to the workers?",
"How can you efficiently try every k?"
] | /**
* @param {number[]} tasks
* @param {number[]} workers
* @param {number} pills
* @param {number} strength
* @return {number}
*/
var maxTaskAssign = function(tasks, workers, pills, strength) {
}; | You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks, with the ith task requiring tasks[i] strength to complete. The strength of each worker is stored in a 0-indexed integer array workers, with the jth worker having workers[j] strength. Each worker can only be assigned to a single task and must have a strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i]).
Additionally, you have pills magical pills that will increase a worker's strength by strength. You can decide which workers receive the magical pills, however, you may only give each worker at most one magical pill.
Given the 0-indexed integer arrays tasks and workers and the integers pills and strength, return the maximum number of tasks that can be completed.
Example 1:
Input: tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1
Output: 3
Explanation:
We can assign the magical pill and tasks as follows:
- Give the magical pill to worker 0.
- Assign worker 0 to task 2 (0 + 1 >= 1)
- Assign worker 1 to task 1 (3 >= 2)
- Assign worker 2 to task 0 (3 >= 3)
Example 2:
Input: tasks = [5,4], workers = [0,0,0], pills = 1, strength = 5
Output: 1
Explanation:
We can assign the magical pill and tasks as follows:
- Give the magical pill to worker 0.
- Assign worker 0 to task 0 (0 + 5 >= 5)
Example 3:
Input: tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10
Output: 2
Explanation:
We can assign the magical pills and tasks as follows:
- Give the magical pill to worker 0 and worker 1.
- Assign worker 0 to task 0 (0 + 10 >= 10)
- Assign worker 1 to task 1 (10 + 10 >= 15)
The last pill is not given because it will not make any worker strong enough for the last task.
Constraints:
n == tasks.length
m == workers.length
1 <= n, m <= 5 * 104
0 <= pills <= m
0 <= tasks[i], workers[j], strength <= 109
| Hard | [
"array",
"binary-search",
"greedy",
"queue",
"sorting",
"monotonic-queue"
] | [
"//////////////////////////////////////////////Template/////////////////////////////////////////////////////////////\nfunction Bisect() {\n return { insort_right, insort_left, bisect_left, bisect_right }\n function insort_right(a, x, lo = 0, hi = null) {\n lo = bisect_right(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_right(a, x, lo = 0, hi = null) {\n // > upper_bound\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2)\n x < a[mid] ? (hi = mid) : (lo = mid + 1)\n }\n return lo\n }\n function insort_left(a, x, lo = 0, hi = null) {\n lo = bisect_left(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_left(a, x, lo = 0, hi = null) {\n // >= lower_bound\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2)\n a[mid] < x ? (lo = mid + 1) : (hi = mid)\n }\n return lo\n }\n}\n\nconst maxTaskAssign = function(tasks, workers, pills, strength) {\n tasks.sort((a, b) => a - b)\n workers.sort((a, b) => b - a)\n const m = tasks.length, n = workers.length\n const { min, floor } = Math\n let l = 0, r = min(n, m)\n while (l < r) {\n const mid = r - floor((r - l) / 2)\n if (check(mid)) l = mid\n else r = mid - 1\n }\n\n return l\n\n function check(k){\n const wArr = workers.slice(0, k), tArr = tasks.slice(0, k)\n let tries = pills, bs = new Bisect()\n wArr.reverse()\n tArr.reverse()\n \n for (let elem of tArr) {\n const place = bs.bisect_left(wArr, elem)\n if (place < wArr.length) {\n wArr.pop()\n } else if (tries > 0) {\n const place2 = bs.bisect_left(wArr, elem - strength)\n if (place2 < wArr.length) {\n wArr.splice(place2, 1)\n tries -= 1\n }\n } else return false\n }\n \n return wArr.length === 0\n }\n};"
] |
|
2,073 | time-needed-to-buy-tickets | [
"Loop through the line of people and decrement the number of tickets for each to buy one at a time as if simulating the line moving forward. Keep track of how many tickets have been sold up until person k has no more tickets to buy.",
"Remember that those who have no more tickets to buy will leave the line."
] | /**
* @param {number[]} tickets
* @param {number} k
* @return {number}
*/
var timeRequiredToBuy = function(tickets, k) {
}; | There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.
You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].
Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.
Return the time taken for the person at position k (0-indexed) to finish buying tickets.
Example 1:
Input: tickets = [2,3,2], k = 2
Output: 6
Explanation:
- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].
- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0].
The person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.
Example 2:
Input: tickets = [5,1,1,1], k = 0
Output: 8
Explanation:
- In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0].
- In the next 4 passes, only the person in position 0 is buying tickets.
The person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.
Constraints:
n == tickets.length
1 <= n <= 100
1 <= tickets[i] <= 100
0 <= k < n
| Easy | [
"array",
"queue",
"simulation"
] | [
"const timeRequiredToBuy = function(tickets, k) {\n let res = 0\n \n while(tickets[k] !== 0) {\n res += helper(tickets, k)\n }\n \n return res\n \n function helper(arr, k) {\n let tmp = 0\n for(let i = 0; i < arr.length; i++) {\n if(arr[i] > 0) {\n arr[i]--\n tmp++\n }\n if(arr[k] === 0) break\n }\n return tmp\n }\n \n};"
] |
|
2,074 | reverse-nodes-in-even-length-groups | [
"Consider the list structure ...A → (B → ... → C) → D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure?",
"Suppose you have B → ... → C reversed (because it was of even length) so that it is now C → ... → B. What references do you need to fix so that the transitions between the previous, current, and next groups are correct?",
"A.next should be set to C, and B.next should be set to D.",
"Once the current group is finished being modified, you need to find the new A, B, C, and D nodes for the next group. How can you use the old A, B, C, and D nodes to find the new ones?",
"The new A is either the old B or old C depending on if the group was of even or odd length. The new B is always the old D. The new C and D can be found based on the new B and the next group's length.",
"You can set the initial values of A, B, C, and D to A = null, B = head, C = head, D = head.next. Repeat the steps from the previous hints until D is null."
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseEvenLengthGroups = function(head) {
}; | You are given the head of a linked list.
The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words,
The 1st node is assigned to the first group.
The 2nd and the 3rd nodes are assigned to the second group.
The 4th, 5th, and 6th nodes are assigned to the third group, and so on.
Note that the length of the last group may be less than or equal to 1 + the length of the second to last group.
Reverse the nodes in each group with an even length, and return the head of the modified linked list.
Example 1:
Input: head = [5,2,6,3,9,1,7,3,8,4]
Output: [5,6,2,3,9,1,4,8,3,7]
Explanation:
- The length of the first group is 1, which is odd, hence no reversal occurs.
- The length of the second group is 2, which is even, hence the nodes are reversed.
- The length of the third group is 3, which is odd, hence no reversal occurs.
- The length of the last group is 4, which is even, hence the nodes are reversed.
Example 2:
Input: head = [1,1,0,6]
Output: [1,0,1,6]
Explanation:
- The length of the first group is 1. No reversal occurs.
- The length of the second group is 2. The nodes are reversed.
- The length of the last group is 1. No reversal occurs.
Example 3:
Input: head = [1,1,0,6,5]
Output: [1,0,1,5,6]
Explanation:
- The length of the first group is 1. No reversal occurs.
- The length of the second group is 2. The nodes are reversed.
- The length of the last group is 2. The nodes are reversed.
Constraints:
The number of nodes in the list is in the range [1, 105].
0 <= Node.val <= 105
| Medium | [
"linked-list"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const reverseEvenLengthGroups = function(head) {\n const arr = []\n let cur = head\n while(cur) {\n arr.push(cur)\n cur = cur.next\n }\n let len = 1, res = []\n for(let i = 0, n = arr.length; i < n; ) {\n let backup = len, tmp = [], rev = len % 2 === 0\n while(len && i < n) {\n tmp.push(arr[i])\n i++\n len--\n }\n if((tmp.length % 2 === 0) ) {\n tmp.reverse()\n }\n res.push(...tmp)\n len = backup + 1\n }\n for(let i = 0; i < res.length; i++) {\n if(i === res.length - 1) res[i].next = null\n else {\n res[i].next = res[i + 1]\n }\n }\n \n return res[0]\n};"
] |
2,075 | decode-the-slanted-ciphertext | [
"How can you use rows and encodedText to find the number of columns of the matrix?",
"Once you have the number of rows and columns, you can create the matrix and place encodedText in it. How should you place it in the matrix?",
"How should you traverse the matrix to \"decode\" originalText?"
] | /**
* @param {string} encodedText
* @param {number} rows
* @return {string}
*/
var decodeCiphertext = function(encodedText, rows) {
}; | A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows.
originalText is placed first in a top-left to bottom-right manner.
The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText.
encodedText is then formed by appending all characters of the matrix in a row-wise fashion.
The characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed.
For example, if originalText = "cipher" and rows = 3, then we encode it in the following manner:
The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = "ch ie pr".
Given the encoded string encodedText and number of rows rows, return the original string originalText.
Note: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText.
Example 1:
Input: encodedText = "ch ie pr", rows = 3
Output: "cipher"
Explanation: This is the same example described in the problem description.
Example 2:
Input: encodedText = "iveo eed l te olc", rows = 4
Output: "i love leetcode"
Explanation: The figure above denotes the matrix that was used to encode originalText.
The blue arrows show how we can find originalText from encodedText.
Example 3:
Input: encodedText = "coding", rows = 1
Output: "coding"
Explanation: Since there is only 1 row, both originalText and encodedText are the same.
Constraints:
0 <= encodedText.length <= 106
encodedText consists of lowercase English letters and ' ' only.
encodedText is a valid encoding of some originalText that does not have trailing spaces.
1 <= rows <= 1000
The testcases are generated such that there is only one possible originalText.
| Medium | [
"string",
"simulation"
] | [
"var decodeCiphertext = function(encodedText, rows) {\n let n = encodedText.length;\n let cols = ~~(n / rows);\n const matrix = Array.from({ length: rows }, () => Array(cols).fill('')) \n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n matrix[i][j] = encodedText[i * cols + j];\n }\n }\n let ans = \"\";\n for (let i = 0; i < cols; i++) {\n let t = Math.min(rows, cols - i);\n for (let j = 0; j < t; j++) {\n ans += matrix[j][i + j];\n }\n }\n let idx = ans.length - 1\n for(; idx >= 0; idx--) {\n if(ans[idx] === ' ') continue\n else break\n }\n return ans.slice(0, idx + 1);\n};"
] |
|
2,076 | process-restricted-friend-requests | [
"For each request, we could loop through all restrictions. Can you think of doing a check-in close to O(1)?",
"Could you use Union Find?"
] | /**
* @param {number} n
* @param {number[][]} restrictions
* @param {number[][]} requests
* @return {boolean[]}
*/
var friendRequests = function(n, restrictions, requests) {
}; | You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1.
You are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] means that person xi and person yi cannot become friends, either directly or indirectly through other people.
Initially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests, where requests[j] = [uj, vj] is a friend request between person uj and person vj.
A friend request is successful if uj and vj can be friends. Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1]), and upon a successful request, uj and vj become direct friends for all future friend requests.
Return a boolean array result, where each result[j] is true if the jth friend request is successful or false if it is not.
Note: If uj and vj are already direct friends, the request is still successful.
Example 1:
Input: n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]]
Output: [true,false]
Explanation:
Request 0: Person 0 and person 2 can be friends, so they become direct friends.
Request 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0).
Example 2:
Input: n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]]
Output: [true,false]
Explanation:
Request 0: Person 1 and person 2 can be friends, so they become direct friends.
Request 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).
Example 3:
Input: n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]]
Output: [true,false,true,false]
Explanation:
Request 0: Person 0 and person 4 can be friends, so they become direct friends.
Request 1: Person 1 and person 2 cannot be friends since they are directly restricted.
Request 2: Person 3 and person 1 can be friends, so they become direct friends.
Request 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).
Constraints:
2 <= n <= 1000
0 <= restrictions.length <= 1000
restrictions[i].length == 2
0 <= xi, yi <= n - 1
xi != yi
1 <= requests.length <= 1000
requests[j].length == 2
0 <= uj, vj <= n - 1
uj != vj
| Hard | [
"union-find",
"graph"
] | [
"var friendRequests = function(n, restrictions, requests) {\n function validation(arr) {\n for (const [x, y] of restrictions) {\n if (arr[x] == arr[y]) return false \n }\n\n return true\n }\n\n\n\n let groupId = []\n for(let i = 0; i < n; i++) groupId.push(i) \n\n\n const ans = []\n for(let [u, v] of requests) {\n if (v < u) [u, v] = [v, u]\n const tmp = groupId.slice()\n\n for(let i = 0; i < n; i++) {\n if (tmp[i] == groupId[v]) tmp[i] = groupId[u] \n }\n\n if (validation(tmp)) {\n ans.push(true)\n groupId = tmp\n } else ans.push(false)\n }\n\n\n return ans \n};"
] |
|
2,078 | two-furthest-houses-with-different-colors | [
"The constraints are small. Can you try the combination of every two houses?",
"Greedily, the maximum distance will come from either the pair of the leftmost house and possibly some house on the right with a different color, or the pair of the rightmost house and possibly some house on the left with a different color."
] | /**
* @param {number[]} colors
* @return {number}
*/
var maxDistance = function(colors) {
}; | There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house.
Return the maximum distance between two houses with different colors.
The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x.
Example 1:
Input: colors = [1,1,1,6,1,1,1]
Output: 3
Explanation: In the above image, color 1 is blue, and color 6 is red.
The furthest two houses with different colors are house 0 and house 3.
House 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.
Note that houses 3 and 6 can also produce the optimal answer.
Example 2:
Input: colors = [1,8,3,8,3]
Output: 4
Explanation: In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.
The furthest two houses with different colors are house 0 and house 4.
House 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4.
Example 3:
Input: colors = [0,1]
Output: 1
Explanation: The furthest two houses with different colors are house 0 and house 1.
House 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1.
Constraints:
n == colors.length
2 <= n <= 100
0 <= colors[i] <= 100
Test data are generated such that at least two houses have different colors.
| Easy | [
"array",
"greedy"
] | [
"const maxDistance = function(colors) {\n const n = colors.length\n let res = 0\n for(let i = 1; i < n; i++) {\n const cur = colors[i]\n for(let j = 0; j < i; j++) {\n if(colors[i] !== colors[j]) {\n res = Math.max(res, i - j)\n break\n }\n }\n }\n \n return res\n};"
] |
|
2,079 | watering-plants | [
"Simulate the process.",
"Return to refill the container once you meet a plant that needs more water than you have."
] | /**
* @param {number[]} plants
* @param {number} capacity
* @return {number}
*/
var wateringPlants = function(plants, capacity) {
}; | You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at.
Each plant needs a specific amount of water. You will water the plants in the following way:
Water the plants in order from left to right.
After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can.
You cannot refill the watering can early.
You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis.
Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants.
Example 1:
Input: plants = [2,2,3,3], capacity = 5
Output: 14
Explanation: Start at the river with a full watering can:
- Walk to plant 0 (1 step) and water it. Watering can has 3 units of water.
- Walk to plant 1 (1 step) and water it. Watering can has 1 unit of water.
- Since you cannot completely water plant 2, walk back to the river to refill (2 steps).
- Walk to plant 2 (3 steps) and water it. Watering can has 2 units of water.
- Since you cannot completely water plant 3, walk back to the river to refill (3 steps).
- Walk to plant 3 (4 steps) and water it.
Steps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14.
Example 2:
Input: plants = [1,1,1,4,2,3], capacity = 4
Output: 30
Explanation: Start at the river with a full watering can:
- Water plants 0, 1, and 2 (3 steps). Return to river (3 steps).
- Water plant 3 (4 steps). Return to river (4 steps).
- Water plant 4 (5 steps). Return to river (5 steps).
- Water plant 5 (6 steps).
Steps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30.
Example 3:
Input: plants = [7,7,7,7,7,7,7], capacity = 8
Output: 49
Explanation: You have to refill before watering each plant.
Steps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49.
Constraints:
n == plants.length
1 <= n <= 1000
1 <= plants[i] <= 106
max(plants[i]) <= capacity <= 109
| Medium | [
"array"
] | [
"const wateringPlants = function(plants, capacity) {\n let res = 0, cap = capacity, full = capacity\n for(let i = 0, n = plants.length; i < n; i++) {\n const cur = plants[i]\n cap -= cur\n if(cap >= 0) res++\n else {\n res = res + (i + i + 1)\n cap = full - cur\n }\n }\n \n return res\n};"
] |
|
2,080 | range-frequency-queries | [
"The queries must be answered efficiently to avoid time limit exceeded verdict.",
"Store the elements of the array in a data structure that helps answering the queries efficiently.",
"Use a hash table that stored for each value, the indices where that value appeared.",
"Use binary search over the indices of a value to find its range frequency."
] | /**
* @param {number[]} arr
*/
var RangeFreqQuery = function(arr) {
};
/**
* @param {number} left
* @param {number} right
* @param {number} value
* @return {number}
*/
RangeFreqQuery.prototype.query = function(left, right, value) {
};
/**
* Your RangeFreqQuery object will be instantiated and called as such:
* var obj = new RangeFreqQuery(arr)
* var param_1 = obj.query(left,right,value)
*/ | Design a data structure to find the frequency of a given value in a given subarray.
The frequency of a value in a subarray is the number of occurrences of that value in the subarray.
Implement the RangeFreqQuery class:
RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr.
int query(int left, int right, int value) Returns the frequency of value in the subarray arr[left...right].
A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).
Example 1:
Input
["RangeFreqQuery", "query", "query"]
[[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]]
Output
[null, 1, 2]
Explanation
RangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);
rangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4]
rangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.
Constraints:
1 <= arr.length <= 105
1 <= arr[i], value <= 104
0 <= left <= right < arr.length
At most 105 calls will be made to query
| Medium | [
"array",
"hash-table",
"binary-search",
"design",
"segment-tree"
] | [
"//////////////////////////////////////////////Template/////////////////////////////////////////////////////////////\nfunction Bisect() {\n return { insort_right, insort_left, bisect_left, bisect_right }\n function insort_right(a, x, lo = 0, hi = null) {\n lo = bisect_right(a, x, lo, hi);\n a.splice(lo, 0, x);\n }\n function bisect_right(a, x, lo = 0, hi = null) { // > upper_bound\n if (lo < 0) throw new Error('lo must be non-negative');\n if (hi == null) hi = a.length;\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2);\n x < a[mid] ? hi = mid : lo = mid + 1;\n }\n return lo;\n }\n function insort_left(a, x, lo = 0, hi = null) {\n lo = bisect_left(a, x, lo, hi);\n a.splice(lo, 0, x);\n }\n function bisect_left(a, x, lo = 0, hi = null) { // >= lower_bound\n if (lo < 0) throw new Error('lo must be non-negative');\n if (hi == null) hi = a.length;\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2);\n a[mid] < x ? lo = mid + 1 : hi = mid;\n }\n return lo;\n }\n}\n\n// counter with {value: array indices (increasing order)}\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\nvar RangeFreqQuery = function(arr) {\n let a = arr\n this.m = counter_value_in_indexA_in(a)\n this.bi = new Bisect();\n};\n\n\nRangeFreqQuery.prototype.query = function(left, right, value) {\n let l = left, r =right, x = value, m = this.m, bi = this.bi\n if (!m.has(x)) return 0;\n let a = m.get(x), len = a.length;\n let min = a[0], max = a[len - 1];\n if (l <= min && r >= max) return len; // cover all\n if (r < min || l > max) return 0; // out of bound\n let lbs = bi.bisect_left(a, l); // needs lbs >= l (lower bound will find first >= l)\n let ubs = bi.bisect_right(a, r); // needs ubs <= r (upper bound will find first ubs > r, -1 will guarantee <= r)\n ubs--;\n return ubs - lbs + 1;\n};"
] |
|
2,081 | sum-of-k-mirror-numbers | [
"Since we need to reduce search space, instead of checking if every number is a palindrome in base-10, can we try to \"generate\" the palindromic numbers?",
"If you are provided with a d digit number, how can you generate a palindrome with 2*d or 2*d - 1 digit?",
"Try brute-forcing and checking if the palindrome you generated is a \"k-Mirror\" number."
] | /**
* @param {number} k
* @param {number} n
* @return {number}
*/
var kMirror = function(k, n) {
}; | A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k.
For example, 9 is a 2-mirror number. The representation of 9 in base-10 and base-2 are 9 and 1001 respectively, which read the same both forward and backward.
On the contrary, 4 is not a 2-mirror number. The representation of 4 in base-2 is 100, which does not read the same both forward and backward.
Given the base k and the number n, return the sum of the n smallest k-mirror numbers.
Example 1:
Input: k = 2, n = 5
Output: 25
Explanation:
The 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows:
base-10 base-2
1 1
3 11
5 101
7 111
9 1001
Their sum = 1 + 3 + 5 + 7 + 9 = 25.
Example 2:
Input: k = 3, n = 7
Output: 499
Explanation:
The 7 smallest 3-mirror numbers are and their representations in base-3 are listed as follows:
base-10 base-3
1 1
2 2
4 11
8 22
121 11111
151 12121
212 21212
Their sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499.
Example 3:
Input: k = 7, n = 17
Output: 20379000
Explanation: The 17 smallest 7-mirror numbers are:
1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596
Constraints:
2 <= k <= 9
1 <= n <= 30
| Hard | [
"math",
"enumeration"
] | [
"const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\n\nconst int = parseInt;\n\nvar kMirror = function(k, n) {\n let res = 0;\n for (let len = 1; ; len++) {\n let min = 10 ** ((len - 1) >> 1), max = 10 ** ((len + 1) >> 1);\n for (let base = min; base < max; base++) {\n let x = base;\n for (let i = len & 1 ? int(base / 10) : base; i > 0; i = int(i / 10)) {\n x = x * 10 + i % 10;\n }\n let s = x.toString(k);\n if (isPalindrome(s)) {\n res += x;\n n--;\n if (!n) return res;\n }\n }\n } \n};"
] |
|
2,085 | count-common-words-with-one-occurrence | [
"Could you try every word?",
"Could you use a hash map to achieve a good complexity?"
] | /**
* @param {string[]} words1
* @param {string[]} words2
* @return {number}
*/
var countWords = function(words1, words2) {
}; | Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.
Example 1:
Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
Output: 2
Explanation:
- "leetcode" appears exactly once in each of the two arrays. We count this string.
- "amazing" appears exactly once in each of the two arrays. We count this string.
- "is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.
- "as" appears once in words1, but does not appear in words2. We do not count this string.
Thus, there are 2 strings that appear exactly once in each of the two arrays.
Example 2:
Input: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]
Output: 0
Explanation: There are no strings that appear in each of the two arrays.
Example 3:
Input: words1 = ["a","ab"], words2 = ["a","a","a","ab"]
Output: 1
Explanation: The only string that appears exactly once in each of the two arrays is "ab".
Constraints:
1 <= words1.length, words2.length <= 1000
1 <= words1[i].length, words2[j].length <= 30
words1[i] and words2[j] consists only of lowercase English letters.
| Easy | [
"array",
"hash-table",
"string",
"counting"
] | null | [] |
2,086 | minimum-number-of-food-buckets-to-feed-the-hamsters | [
"When is it impossible to collect the rainwater from all the houses?",
"When one or more houses do not have an empty space adjacent to it.",
"Assuming the rainwater from all previous houses is collected. If there is a house at index i and you are able to place a bucket at index i - 1 or i + 1, where should you put it?",
"It is always better to place a bucket at index i + 1 because it can collect the rainwater from the next house as well."
] | /**
* @param {string} hamsters
* @return {number}
*/
var minimumBuckets = function(hamsters) {
}; | You are given a 0-indexed string hamsters where hamsters[i] is either:
'H' indicating that there is a hamster at index i, or
'.' indicating that index i is empty.
You will add some number of food buckets at the empty indices in order to feed the hamsters. A hamster can be fed if there is at least one food bucket to its left or to its right. More formally, a hamster at index i can be fed if you place a food bucket at index i - 1 and/or at index i + 1.
Return the minimum number of food buckets you should place at empty indices to feed all the hamsters or -1 if it is impossible to feed all of them.
Example 1:
Input: hamsters = "H..H"
Output: 2
Explanation: We place two food buckets at indices 1 and 2.
It can be shown that if we place only one food bucket, one of the hamsters will not be fed.
Example 2:
Input: hamsters = ".H.H."
Output: 1
Explanation: We place one food bucket at index 2.
Example 3:
Input: hamsters = ".HHH."
Output: -1
Explanation: If we place a food bucket at every empty index as shown, the hamster at index 2 will not be able to eat.
Constraints:
1 <= hamsters.length <= 105
hamsters[i] is either'H' or '.'.
| Medium | [
"string",
"dynamic-programming",
"greedy"
] | [
"var minimumBuckets = function(street) {\n const arr = street.split(''), n = arr.length\n let res = 0\n for(let i = 0; i < arr.length; i++) {\n if(arr[i] === 'H') {\n if(i > 0 && arr[i - 1] === 'B') continue\n if(i < n - 1 && arr[i + 1] === '.') arr[i + 1] = 'B', res++\n else if(i > 0 && arr[i - 1] === '.') arr[i - 1] = 'B', res++\n else return -1\n }\n }\n return res\n};"
] |
|
2,087 | minimum-cost-homecoming-of-a-robot-in-a-grid | [
"Irrespective of what path the robot takes, it will have to traverse all the rows between startRow and homeRow and all the columns between startCol and homeCol.",
"Hence, making any other move other than traversing the required rows and columns will potentially incur more cost which can be avoided."
] | /**
* @param {number[]} startPos
* @param {number[]} homePos
* @param {number[]} rowCosts
* @param {number[]} colCosts
* @return {number}
*/
var minCost = function(startPos, homePos, rowCosts, colCosts) {
}; | There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol).
The robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n.
If the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r].
If the robot moves left or right into a cell whose column is c, then this move costs colCosts[c].
Return the minimum total cost for this robot to return home.
Example 1:
Input: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]
Output: 18
Explanation: One optimal path is that:
Starting from (1, 0)
-> It goes down to (2, 0). This move costs rowCosts[2] = 3.
-> It goes right to (2, 1). This move costs colCosts[1] = 2.
-> It goes right to (2, 2). This move costs colCosts[2] = 6.
-> It goes right to (2, 3). This move costs colCosts[3] = 7.
The total cost is 3 + 2 + 6 + 7 = 18
Example 2:
Input: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]
Output: 0
Explanation: The robot is already at its home. Since no moves occur, the total cost is 0.
Constraints:
m == rowCosts.length
n == colCosts.length
1 <= m, n <= 105
0 <= rowCosts[r], colCosts[c] <= 104
startPos.length == 2
homePos.length == 2
0 <= startrow, homerow < m
0 <= startcol, homecol < n
| Medium | [
"array",
"greedy",
"matrix"
] | null | [] |
2,088 | count-fertile-pyramids-in-a-land | [
"Think about how dynamic programming can help solve the problem.",
"For any fixed cell (r, c), can you calculate the maximum height of the pyramid for which it is the apex? Let us denote this value as dp[r][c].",
"How will the values at dp[r+1][c-1] and dp[r+1][c+1] help in determining the value at dp[r][c]?",
"For the cell (r, c), is there a relation between the number of pyramids for which it serves as the apex and dp[r][c]? How does it help in calculating the answer?"
] | /**
* @param {number[][]} grid
* @return {number}
*/
var countPyramids = function(grid) {
}; | A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outside the grid are considered barren.
A pyramidal plot of land can be defined as a set of cells with the following criteria:
The number of cells in the set has to be greater than 1 and all cells must be fertile.
The apex of a pyramid is the topmost cell of the pyramid. The height of a pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r <= i <= r + h - 1 and c - (i - r) <= j <= c + (i - r).
An inverse pyramidal plot of land can be defined as a set of cells with similar criteria:
The number of cells in the set has to be greater than 1 and all cells must be fertile.
The apex of an inverse pyramid is the bottommost cell of the inverse pyramid. The height of an inverse pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r - h + 1 <= i <= r and c - (r - i) <= j <= c + (r - i).
Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells.
Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid.
Example 1:
Input: grid = [[0,1,1,0],[1,1,1,1]]
Output: 2
Explanation: The 2 possible pyramidal plots are shown in blue and red respectively.
There are no inverse pyramidal plots in this grid.
Hence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2.
Example 2:
Input: grid = [[1,1,1],[1,1,1]]
Output: 2
Explanation: The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red.
Hence the total number of plots is 1 + 1 = 2.
Example 3:
Input: grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]]
Output: 13
Explanation: There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures.
There are 6 inverse pyramidal plots, 2 of which are shown in the last figure.
The total number of plots is 7 + 6 = 13.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
grid[i][j] is either 0 or 1.
| Hard | [
"array",
"dynamic-programming",
"matrix"
] | [
" const countPyramids = function(grid) {\n const rev = clone(grid).reverse()\n let res = count(grid)\n res += count(rev)\n return res\n\n function clone(grid) {\n return grid.map(e => e.slice())\n }\n\n function count(grid) {\n const m = grid.length, n = grid[0].length\n let res = 0\n for (let i = 1; i < m; i++) {\n for (let j = 1; j < n - 1; j++) {\n if (grid[i][j] && grid[i - 1][j]) {\n grid[i][j] = Math.min(\n grid[i - 1][j - 1],\n grid[i - 1][j + 1]\n ) + 1\n res += grid[i][j] - 1\n }\n }\n }\n return res\n }\n};"
] |
|
2,089 | find-target-indices-after-sorting-array | [
"Try \"sorting\" the array first.",
"Now find all indices in the array whose values are equal to target."
] | /**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var targetIndices = function(nums, target) {
}; | You are given a 0-indexed integer array nums and a target element target.
A target index is an index i such that nums[i] == target.
Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.
Example 1:
Input: nums = [1,2,5,2,3], target = 2
Output: [1,2]
Explanation: After sorting, nums is [1,2,2,3,5].
The indices where nums[i] == 2 are 1 and 2.
Example 2:
Input: nums = [1,2,5,2,3], target = 3
Output: [3]
Explanation: After sorting, nums is [1,2,2,3,5].
The index where nums[i] == 3 is 3.
Example 3:
Input: nums = [1,2,5,2,3], target = 5
Output: [4]
Explanation: After sorting, nums is [1,2,2,3,5].
The index where nums[i] == 5 is 4.
Constraints:
1 <= nums.length <= 100
1 <= nums[i], target <= 100
| Easy | [
"array",
"binary-search",
"sorting"
] | [
"const targetIndices = function(nums, target) {\n let res = []\n nums.sort((a, b) => a - b)\n for(let i = 0; i < nums.length; i++) {\n if(nums[i] === target) res.push(i)\n }\n return res\n};"
] |
|
2,090 | k-radius-subarray-averages | [
"To calculate the average of a subarray, you need the sum and the K. K is already given. How could you quickly calculate the sum of a subarray?",
"Use the Prefix Sums method to calculate the subarray sums.",
"It is possible that the sum of all the elements does not fit in a 32-bit integer type. Be sure to use a 64-bit integer type for the prefix sum array."
] | /**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var getAverages = function(nums, k) {
}; | You are given a 0-indexed array nums of n integers, and an integer k.
The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-radius average is -1.
Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i.
The average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part.
For example, the average of four elements 2, 3, 1, and 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75, which truncates to 2.
Example 1:
Input: nums = [7,4,3,9,1,8,5,2,6], k = 3
Output: [-1,-1,-1,5,4,4,-1,-1,-1]
Explanation:
- avg[0], avg[1], and avg[2] are -1 because there are less than k elements before each index.
- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.
Using integer division, avg[3] = 37 / 7 = 5.
- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.
- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.
- avg[6], avg[7], and avg[8] are -1 because there are less than k elements after each index.
Example 2:
Input: nums = [100000], k = 0
Output: [100000]
Explanation:
- The sum of the subarray centered at index 0 with radius 0 is: 100000.
avg[0] = 100000 / 1 = 100000.
Example 3:
Input: nums = [8], k = 100000
Output: [-1]
Explanation:
- avg[0] is -1 because there are less than k elements before and after index 0.
Constraints:
n == nums.length
1 <= n <= 105
0 <= nums[i], k <= 105
| Medium | [
"array",
"sliding-window"
] | [
"const lowBit = (x) => x & -x\nclass FenwickTree {\n constructor(n) {\n if (n < 1) return\n this.sum = Array(n + 1).fill(0)\n }\n update(i, delta) {\n if (i < 1) return\n while (i < this.sum.length) {\n this.sum[i] += delta\n i += lowBit(i)\n }\n }\n query(i) {\n if (i < 1) return 0\n let sum = 0\n while (i > 0) {\n sum += this.sum[i]\n i -= lowBit(i)\n }\n return sum\n }\n}\n\nconst getAverages = function(nums, k) {\n const n = nums.length\n const bit = new FenwickTree(n)\n for(let i = 0; i < n; i++) {\n bit.update(i + 1, nums[i])\n }\n const res = Array(n).fill(-1)\n // console.log(bit)\n for(let i = k; i < n - k; i++) {\n const pre = bit.query(i + 1 - k - 1), cur = bit.query(i + 1 + k)\n res[i] = ~~((cur - pre) / (k * 2 + 1))\n }\n \n return res\n};"
] |
|
2,091 | removing-minimum-and-maximum-from-array | [
"There can only be three scenarios for deletions such that both minimum and maximum elements are removed:",
"Scenario 1: Both elements are removed by only deleting from the front.",
"Scenario 2: Both elements are removed by only deleting from the back.",
"Scenario 3: Delete from the front to remove one of the elements, and delete from the back to remove the other element.",
"Compare which of the three scenarios results in the minimum number of moves."
] | /**
* @param {number[]} nums
* @return {number}
*/
var minimumDeletions = function(nums) {
}; | You are given a 0-indexed array of distinct integers nums.
There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array.
A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array.
Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array.
Example 1:
Input: nums = [2,10,7,5,4,1,8,6]
Output: 5
Explanation:
The minimum element in the array is nums[5], which is 1.
The maximum element in the array is nums[1], which is 10.
We can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.
This results in 2 + 3 = 5 deletions, which is the minimum number possible.
Example 2:
Input: nums = [0,-4,19,1,8,-2,-3,5]
Output: 3
Explanation:
The minimum element in the array is nums[1], which is -4.
The maximum element in the array is nums[2], which is 19.
We can remove both the minimum and maximum by removing 3 elements from the front.
This results in only 3 deletions, which is the minimum number possible.
Example 3:
Input: nums = [101]
Output: 1
Explanation:
There is only one element in the array, which makes it both the minimum and maximum element.
We can remove it with 1 deletion.
Constraints:
1 <= nums.length <= 105
-105 <= nums[i] <= 105
The integers in nums are distinct.
| Medium | [
"array",
"greedy"
] | [
"const minimumDeletions = function(nums) {\n let mi = Infinity, ma = -Infinity\n let mii = -1, mai = -1\n const { max, min, abs } = Math, n = nums.length\n for(let i = 0; i < n; i++) {\n const e = nums[i]\n if(e < mi) {\n mi = e\n mii = i\n }\n if(e > ma) {\n ma = e\n mai = i\n }\n }\n \n const disMi = abs(mii + 1, n - mii)\n const disMa = abs(mai + 1, n - mai)\n let res = 0\n let lmi = min(mii, mai), lma = max(mii, mai)\n \n res += min(lmi + 1 + n - lma, lma + 1, n - lmi)\n \n \n return res\n};"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.