Datasets:

QID
int64
1
2.85k
titleSlug
stringlengths
3
77
Hints
sequence
Code
stringlengths
80
1.34k
Body
stringlengths
190
4.55k
Difficulty
stringclasses
3 values
Topics
sequence
Definitions
stringclasses
14 values
Solutions
sequence
2,092
find-all-people-with-secret
[ "Could you model all the meetings happening at the same time as a graph?", "What data structure can you use to efficiently share the secret?", "You can use the union-find data structure to quickly determine who knows the secret and share the secret." ]
/** * @param {number} n * @param {number[][]} meetings * @param {number} firstPerson * @return {number[]} */ var findAllPeople = function(n, meetings, firstPerson) { };
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.   Example 1: Input: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1 Output: [0,1,2,3,5] Explanation: At time 0, person 0 shares the secret with person 1. At time 5, person 1 shares the secret with person 2. At time 8, person 2 shares the secret with person 3. At time 10, person 1 shares the secret with person 5.​​​​ Thus, people 0, 1, 2, 3, and 5 know the secret after all the meetings. Example 2: Input: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3 Output: [0,1,3] Explanation: At time 0, person 0 shares the secret with person 3. At time 2, neither person 1 nor person 2 know the secret. At time 3, person 3 shares the secret with person 0 and person 1. Thus, people 0, 1, and 3 know the secret after all the meetings. Example 3: Input: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1 Output: [0,1,2,3,4] Explanation: At time 0, person 0 shares the secret with person 1. At time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3. Note that person 2 can share the secret at the same time as receiving it. At time 2, person 3 shares the secret with person 4. Thus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.   Constraints: 2 <= n <= 105 1 <= meetings.length <= 105 meetings[i].length == 3 0 <= xi, yi <= n - 1 xi != yi 1 <= timei <= 105 1 <= firstPerson <= n - 1
Hard
[ "depth-first-search", "breadth-first-search", "union-find", "graph", "sorting" ]
[ "const findAllPeople = function(n, meetings, firstPerson) {\n meetings.sort((a, b) => a[2] - b[2])\n const uf = new UnionFind(n);\n uf.connect(0, firstPerson);\n let ppl = [];\n for (let i = 0, len = meetings.length; i < len; ) {\n ppl = [];\n let time = meetings[i][2];\n while (i < len && meetings[i][2] === time) {\n uf.connect(meetings[i][0], meetings[i][1]);\n ppl.push(meetings[i][0]);\n ppl.push(meetings[i][1]);\n i++\n }\n for (let n of ppl) {\n if (!uf.connected(0, n)) uf.reset(n);\n }\n }\n let ans = [];\n for (let i = 0; i < n; ++i) {\n if (uf.connected(0, i)) ans.push(i);\n }\n return ans;\n};\n\nclass UnionFind {\n constructor(n) {\n this.arr = Array(n).fill(null)\n this.arr.forEach((e, i, arr) => arr[i] = i)\n }\n connect(a, b) {\n this.arr[this.find(a)] = this.find(this.arr[b])\n }\n find(a) {\n return this.arr[a] === a ? a : (this.arr[a] = this.find(this.arr[a]))\n }\n connected(a, b) {\n return this.find(a) === this.find(b)\n }\n reset(a) {\n this.arr[a] = a\n }\n}", "const findAllPeople = function(n, meetings, firstPerson) {\n meetings.sort((a, b) => a[2] - b[2])\n const shared = new Set([0, firstPerson])\n \n let start = new Set(), links = {}\n for(let i = 0, len = meetings.length; i < len; i++) {\n const [x,y,t] = meetings[i]\n if(i > 0 && t !== meetings[i - 1][2]) {\n bfs(start, links)\n start = new Set()\n links = {}\n }\n if(shared.has(x)) start.add(x)\n if(shared.has(y)) start.add(y)\n if(links[x] == null) links[x] = []\n if(links[y] == null) links[y] = []\n links[x].push(y)\n links[y].push(x)\n }\n \n bfs(start, links)\n return Array.from(shared)\n \n function bfs(start, links) {\n const visited = new Set()\n while(start.size) {\n const it = start[Symbol.iterator]()\n const cur = it.next().value\n start.delete(cur)\n visited.add(cur)\n shared.add(cur)\n for(let e of (links[cur] || [])) {\n if(!visited.has(e)) start.add(e)\n }\n }\n }\n};" ]
2,094
finding-3-digit-even-numbers
[ "The range of possible answers includes all even numbers between 100 and 999 inclusive. Could you check each possible answer to see if it could be formed from the digits in the array?" ]
/** * @param {number[]} digits * @return {number[]} */ var findEvenNumbers = function(digits) { };
You are given an integer array digits, where each element is a digit. The array may contain duplicates. You need to find all the unique integers that follow the given requirements: The integer consists of the concatenation of three elements from digits in any arbitrary order. The integer does not have leading zeros. The integer is even. For example, if the given digits were [1, 2, 3], integers 132 and 312 follow the requirements. Return a sorted array of the unique integers.   Example 1: Input: digits = [2,1,3,0] Output: [102,120,130,132,210,230,302,310,312,320] Explanation: All the possible integers that follow the requirements are in the output array. Notice that there are no odd integers or integers with leading zeros. Example 2: Input: digits = [2,2,8,8,2] Output: [222,228,282,288,822,828,882] Explanation: The same digit can be used as many times as it appears in digits. In this example, the digit 8 is used twice each time in 288, 828, and 882. Example 3: Input: digits = [3,7,5] Output: [] Explanation: No even integers can be formed using the given digits.   Constraints: 3 <= digits.length <= 100 0 <= digits[i] <= 9
Easy
[ "array", "hash-table", "sorting", "enumeration" ]
[ "const findEvenNumbers = function(digits) {\n const set = new Set(), visited = new Set()\n helper(0, [])\n const res = Array.from(set)\n res.sort((a, b) => a - b)\n return res\n \n function helper(idx, cur) {\n if(cur.length === 3) {\n set.add(+cur.join(''))\n return\n }\n for(let i = 0; i < digits.length; i++) {\n if(visited.has(i)) continue\n const d = digits[i]\n if(d === 0) {\n if(cur.length === 0) continue\n else {\n cur.push(d)\n visited.add(i)\n helper(i + 1, cur)\n visited.delete(i)\n cur.pop()\n }\n } else {\n const isEven = d % 2 === 0\n if(cur.length === 3 - 1) {\n if(isEven) {\n cur.push(d)\n visited.add(i)\n helper(i + 1, cur)\n visited.delete(i)\n cur.pop()\n } else continue\n } else {\n cur.push(d)\n visited.add(i)\n helper(i + 1, cur)\n visited.delete(i)\n cur.pop()\n }\n }\n }\n }\n};" ]
2,095
delete-the-middle-node-of-a-linked-list
[ "If a point with a speed s moves n units in a given time, a point with speed 2 * s will move 2 * n units at the same time. Can you use this to find the middle node of a linked list?", "If you are given the middle node, the node before it, and the node after it, how can you modify the linked list?" ]
/** * 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 deleteMiddle = function(head) { };
You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list. The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x. For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.   Example 1: Input: head = [1,3,4,7,1,2,6] Output: [1,3,4,1,2,6] Explanation: The above figure represents the given linked list. The indices of the nodes are written below. Since n = 7, node 3 with value 7 is the middle node, which is marked in red. We return the new list after removing this node. Example 2: Input: head = [1,2,3,4] Output: [1,2,4] Explanation: The above figure represents the given linked list. For n = 4, node 2 with value 3 is the middle node, which is marked in red. Example 3: Input: head = [2,1] Output: [2] Explanation: The above figure represents the given linked list. For n = 2, node 1 with value 1 is the middle node, which is marked in red. Node 0 with value 2 is the only node remaining after removing node 1.   Constraints: The number of nodes in the list is in the range [1, 105]. 1 <= Node.val <= 105
Medium
[ "linked-list", "two-pointers" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "const deleteMiddle = function(head) {\n if(head == null) return head\n const dummy = new ListNode(null, head)\n let n = 0, cur = head\n while(cur) {\n n++\n cur = cur.next\n }\n if(n === 1) return null\n const mid = Math.floor(n / 2)\n cur = dummy.next\n let pre = dummy \n for(let i = 0; i < n; i++) {\n if(i === mid - 1) {\n pre = cur\n // pre.next = cur.next.next\n }\n if(i === mid) {\n pre.next = cur.next\n }\n if(i > mid) break\n cur = cur.next\n }\n return dummy.next\n};" ]
2,096
step-by-step-directions-from-a-binary-tree-node-to-another
[ "The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t.", "Find the path strings from root → s, and root → t. Can you use these two strings to prepare the final answer?", "Remove the longest common prefix of the two path strings to get the path LCA → s, and LCA → t. Each step in the path of LCA → s should be reversed as 'U'." ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} startValue * @param {number} destValue * @return {string} */ var getDirections = function(root, startValue, destValue) { };
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: 'L' means to go from a node to its left child node. 'R' means to go from a node to its right child node. 'U' means to go from a node to its parent node. Return the step-by-step directions of the shortest path from node s to node t.   Example 1: Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6 Output: "UURL" Explanation: The shortest path is: 3 → 1 → 5 → 2 → 6. Example 2: Input: root = [2,1], startValue = 2, destValue = 1 Output: "L" Explanation: The shortest path is: 2 → 1.   Constraints: The number of nodes in the tree is n. 2 <= n <= 105 1 <= Node.val <= n All the values in the tree are unique. 1 <= startValue, destValue <= n startValue != destValue
Medium
[ "string", "tree", "depth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const getDirections = function (root, startValue, destValue) {\n let start = ''\n let end = ''\n const traverse = (node, path) => {\n if (node === null) return\n if (node.val === startValue) start = path\n if (node.val === destValue) end = path\n if (start !== '' && end !== '') return\n if (node.left !== null) traverse(node.left, path + 'L')\n if (node.right !== null) traverse(node.right, path + 'R')\n }\n traverse(root, '')\n let skip = 0\n while (start[skip] && start[skip] === end[skip]) skip++\n return 'U'.repeat(start.length - skip) + end.slice(skip)\n}" ]
2,097
valid-arrangement-of-pairs
[ "Could you convert this into a graph problem?", "Consider the pairs as edges and each number as a node.", "We have to find an Eulerian path of this graph. Hierholzer’s algorithm can be used." ]
/** * @param {number[][]} pairs * @return {number[][]} */ var validArrangement = function(pairs) { };
You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti. Return any valid arrangement of pairs. Note: The inputs will be generated such that there exists a valid arrangement of pairs.   Example 1: Input: pairs = [[5,1],[4,5],[11,9],[9,4]] Output: [[11,9],[9,4],[4,5],[5,1]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 9 == 9 = start1 end1 = 4 == 4 = start2 end2 = 5 == 5 = start3 Example 2: Input: pairs = [[1,3],[3,2],[2,1]] Output: [[1,3],[3,2],[2,1]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 3 == 3 = start1 end1 = 2 == 2 = start2 The arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid. Example 3: Input: pairs = [[1,2],[1,3],[2,1]] Output: [[1,2],[2,1],[1,3]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 2 == 2 = start1 end1 = 1 == 1 = start2   Constraints: 1 <= pairs.length <= 105 pairs[i].length == 2 0 <= starti, endi <= 109 starti != endi No two pairs are exactly the same. There exists a valid arrangement of pairs.
Hard
[ "depth-first-search", "graph", "eulerian-circuit" ]
[ "const packDGInOutDegreeMap = (gm, edges, dm) => { for (const [u, v] of edges) { if (!gm.has(u)) gm.set(u, []); gm.get(u).push(v); dm.set(u, (dm.get(u) || 0) + 1); dm.set(v, (dm.get(v) || 0) - 1); } };\n\n\nconst validArrangement = (pairs) => {\n let g = new Map(), deg = new Map(), res = [];\n packDGInOutDegreeMap(g, pairs, deg);\n let start = -1;\n for (const [node, ] of deg) { // looking for starting node\n if (start == -1 || deg.get(node) == 1) start = node;\n }\n let path = eulerianPath(g, start);\n path.reverse();\n for (let i = 1; i < path.length; i++) {\n res.push([path[i-1], path[i]]);\n }\n return res;\n};\n\nconst eulerianPath = (g, start) => { // eulerian Path with Hierholzer’s Algorithm\n let st = [start], path = [];\n while (st.length) {\n let u = st[st.length - 1], ua = g.get(u) || [];\n if (ua.length) {\n let v = ua.pop();\n g.set(u, ua);\n st.push(v);\n } else {\n path.push(u);\n st.pop();\n }\n }\n return path;\n};" ]
2,099
find-subsequence-of-length-k-with-the-largest-sum
[ "From a greedy perspective, what k elements should you pick?", "Could you sort the array while maintaining the index?" ]
/** * @param {number[]} nums * @param {number} k * @return {number[]} */ var maxSubsequence = function(nums, k) { };
You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum. Return any such subsequence as an integer array of length k. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.   Example 1: Input: nums = [2,1,3,3], k = 2 Output: [3,3] Explanation: The subsequence has the largest sum of 3 + 3 = 6. Example 2: Input: nums = [-1,-2,3,4], k = 3 Output: [-1,3,4] Explanation: The subsequence has the largest sum of -1 + 3 + 4 = 6. Example 3: Input: nums = [3,4,3,3], k = 2 Output: [3,4] Explanation: The subsequence has the largest sum of 3 + 4 = 7. Another possible subsequence is [4, 3].   Constraints: 1 <= nums.length <= 1000 -105 <= nums[i] <= 105 1 <= k <= nums.length
Easy
[ "array", "hash-table", "sorting", "heap-priority-queue" ]
null
[]
2,100
find-good-days-to-rob-the-bank
[ "The trivial solution is to check the time days before and after each day. There are a lot of repeated operations using this solution. How could we optimize this solution?", "We can use precomputation to make the solution faster.", "Use an array to store the number of days before the i<sup>th</sup> day that is non-increasing, and another array to store the number of days after the i<sup>th</sup> day that is non-decreasing." ]
/** * @param {number[]} security * @param {number} time * @return {number[]} */ var goodDaysToRobBank = function(security, time) { };
You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security, where security[i] is the number of guards on duty on the ith day. The days are numbered starting from 0. You are also given an integer time. The ith day is a good day to rob the bank if: There are at least time days before and after the ith day, The number of guards at the bank for the time days before i are non-increasing, and The number of guards at the bank for the time days after i are non-decreasing. More formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time]. Return a list of all days (0-indexed) that are good days to rob the bank. The order that the days are returned in does not matter.   Example 1: Input: security = [5,3,3,3,5,6,2], time = 2 Output: [2,3] Explanation: On day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4]. On day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5]. No other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank. Example 2: Input: security = [1,1,1,1,1], time = 0 Output: [0,1,2,3,4] Explanation: Since time equals 0, every day is a good day to rob the bank, so return every day. Example 3: Input: security = [1,2,3,4,5,6], time = 2 Output: [] Explanation: No day has 2 days before it that have a non-increasing number of guards. Thus, no day is a good day to rob the bank, so return an empty list.   Constraints: 1 <= security.length <= 105 0 <= security[i], time <= 105
Medium
[ "array", "dynamic-programming", "prefix-sum" ]
[ "const goodDaysToRobBank = function(security, time) {\n const n = security.length, sec = security\n const pre = Array(n).fill(0), post = Array(n).fill(0)\n \n const res = []\n let num = 0\n for(let i = 1; i < n; i++) {\n if(sec[i] <= sec[i - 1]) {\n num++\n } else {\n num = 0\n }\n pre[i] = num\n }\n \n num = 0\n for(let i = n - 2; i >= 0; i--) {\n if(sec[i] <= sec[i + 1]) {\n num++\n } else {\n num = 0\n }\n post[i] = num\n }\n \n // console.log(pre, post)\n for(let i = 0; i < n; i++) {\n if(pre[i] >= time && post[i] >= time) {\n res.push(i)\n }\n }\n \n return res\n};" ]
2,101
detonate-the-maximum-bombs
[ "How can we model the relationship between different bombs? Can \"graphs\" help us?", "Bombs are nodes and are connected to other bombs in their range by directed edges.", "If we know which bombs will be affected when any bomb is detonated, how can we find the total number of bombs that will be detonated if we start from a fixed bomb?", "Run a Depth First Search (DFS) from every node, and all the nodes it reaches are the bombs that will be detonated." ]
/** * @param {number[][]} bombs * @return {number} */ var maximumDetonation = function(bombs) { };
You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb. The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range. You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges. Given the list of bombs, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb.   Example 1: Input: bombs = [[2,1,3],[6,1,4]] Output: 2 Explanation: The above figure shows the positions and ranges of the 2 bombs. If we detonate the left bomb, the right bomb will not be affected. But if we detonate the right bomb, both bombs will be detonated. So the maximum bombs that can be detonated is max(1, 2) = 2. Example 2: Input: bombs = [[1,1,5],[10,10,5]] Output: 1 Explanation: Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1. Example 3: Input: bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]] Output: 5 Explanation: The best bomb to detonate is bomb 0 because: - Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0. - Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2. - Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3. Thus all 5 bombs are detonated.   Constraints: 1 <= bombs.length <= 100 bombs[i].length == 3 1 <= xi, yi, ri <= 105
Medium
[ "array", "math", "depth-first-search", "breadth-first-search", "graph", "geometry" ]
[ " const maximumDetonation = function(bombs) {\n let n = bombs.length, res = 1, graph = {}\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < n; j++) {\n if (i === j) continue\n if (bombAdj(bombs[i], bombs[j])) {\n if (graph[i] == null) graph[i] = []\n graph[i].push(j)\n }\n }\n }\n function dfs(node, visited) {\n for(const next of (graph[node] || [])) {\n if(!visited.has(next)) {\n visited.add(next)\n dfs(next, visited)\n }\n }\n }\n for (let i = 0; i < n; i++) {\n const set = new Set([i])\n dfs(i, set)\n res = Math.max(res, set.size)\n }\n\n return res\n};\n\nfunction bombAdj(source, target) {\n const [x1, y1, r1] = source\n const [x2, y2] = target\n const { abs } = Math\n return abs(x1 - x2) ** 2 + abs(y1 - y2) ** 2 <= r1 ** 2\n}", "const maximumDetonation = function(bombs) {\n const n = bombs.length, graph = {}\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < n; j++) {\n if(i === j) continue\n if(adjValid(bombs[i], bombs[j])) {\n if(graph[i] == null) graph[i] = []\n graph[i].push(j)\n }\n }\n }\n \n let res = 0\n for(let i = 0; i < n; i++) {\n const set = new Set([i])\n dfs(i, set)\n res = Math.max(res, set.size)\n }\n return res\n \n function dfs(node, visited){\n for (const e of (graph[node] || [])) {\n if(!visited.has(e)) {\n visited.add(e)\n dfs(e, visited)\n }\n }\n }\n \n function adjValid(start, target) {\n const [sx, sy, r] = start\n const [ex, ey] = target\n return Math.abs(sx - ex) ** 2 + Math.abs(sy - ey) ** 2 <= r ** 2\n }\n};" ]
2,102
sequentially-ordinal-rank-tracker
[ "If the problem were to find the median of a stream of scenery locations while they are being added, can you solve it?", "We can use a similar approach as an optimization to avoid repeated sorting.", "Employ two heaps: left heap and right heap. The left heap is a max-heap, and the right heap is a min-heap. The size of the left heap is k + 1 (best locations), where k is the number of times the get method was invoked. The other locations are maintained in the right heap.", "Every time when add is being called, we add it to the left heap. If the size of the left heap exceeds k + 1, we move the head element to the right heap.", "When the get method is invoked again (the k + 1 time it is invoked), we can return the head element of the left heap. But before returning it, if the right heap is not empty, we maintain the left heap to have the best k + 2 items by moving the best location from the right heap to the left heap." ]
var SORTracker = function() { }; /** * @param {string} name * @param {number} score * @return {void} */ SORTracker.prototype.add = function(name, score) { }; /** * @return {string} */ SORTracker.prototype.get = function() { }; /** * Your SORTracker object will be instantiated and called as such: * var obj = new SORTracker() * obj.add(name,score) * var param_2 = obj.get() */
A scenic location is represented by its name and attractiveness score, where name is a unique string among all locations and score is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better. You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports: Adding scenic locations, one at a time. Querying the ith best location of all locations already added, where i is the number of times the system has been queried (including the current query). For example, when the system is queried for the 4th time, it returns the 4th best location of all locations already added. Note that the test data are generated so that at any time, the number of queries does not exceed the number of locations added to the system. Implement the SORTracker class: SORTracker() Initializes the tracker system. void add(string name, int score) Adds a scenic location with name and score to the system. string get() Queries and returns the ith best location, where i is the number of times this method has been invoked (including this invocation).   Example 1: Input ["SORTracker", "add", "add", "get", "add", "get", "add", "get", "add", "get", "add", "get", "get"] [[], ["bradford", 2], ["branford", 3], [], ["alps", 2], [], ["orland", 2], [], ["orlando", 3], [], ["alpine", 2], [], []] Output [null, null, null, "branford", null, "alps", null, "bradford", null, "bradford", null, "bradford", "orland"] Explanation SORTracker tracker = new SORTracker(); // Initialize the tracker system. tracker.add("bradford", 2); // Add location with name="bradford" and score=2 to the system. tracker.add("branford", 3); // Add location with name="branford" and score=3 to the system. tracker.get(); // The sorted locations, from best to worst, are: branford, bradford. // Note that branford precedes bradford due to its higher score (3 > 2). // This is the 1st time get() is called, so return the best location: "branford". tracker.add("alps", 2); // Add location with name="alps" and score=2 to the system. tracker.get(); // Sorted locations: branford, alps, bradford. // Note that alps precedes bradford even though they have the same score (2). // This is because "alps" is lexicographically smaller than "bradford". // Return the 2nd best location "alps", as it is the 2nd time get() is called. tracker.add("orland", 2); // Add location with name="orland" and score=2 to the system. tracker.get(); // Sorted locations: branford, alps, bradford, orland. // Return "bradford", as it is the 3rd time get() is called. tracker.add("orlando", 3); // Add location with name="orlando" and score=3 to the system. tracker.get(); // Sorted locations: branford, orlando, alps, bradford, orland. // Return "bradford". tracker.add("alpine", 2); // Add location with name="alpine" and score=2 to the system. tracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland. // Return "bradford". tracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland. // Return "orland".   Constraints: name consists of lowercase English letters, and is unique among all locations. 1 <= name.length <= 10 1 <= score <= 105 At any time, the number of calls to get does not exceed the number of calls to add. At most 4 * 104 calls in total will be made to add and get.
Hard
[ "design", "heap-priority-queue", "data-stream", "ordered-set" ]
[ "const maxFn = (a, b) => a.score === b.score ? a.name < b.name : a.score > b.score\nconst minFn = (a, b) => a.score === b.score ? a.name > b.name : a.score < b.score\nconst SORTracker = function() {\n this.maxPQ = new PQ(maxFn)\n this.minPQ = new PQ(minFn)\n this.idx = 0\n};\n\n\nSORTracker.prototype.add = function(name, score) {\n this.maxPQ.push({name, score})\n};\n\n\nSORTracker.prototype.get = function() {\n if(this.idx) {\n this.minPQ.push(this.maxPQ.pop())\n while(maxFn(this.maxPQ.peek(), this.minPQ.peek())) {\n const tmp = this.minPQ.pop()\n this.minPQ.push(this.maxPQ.pop())\n this.maxPQ.push(tmp)\n }\n }\n this.idx++\n return this.maxPQ.peek().name\n};\n\n\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}", "const maxComp = (a, b) => {\n return a[1] === b[1] ? b[0].localeCompare(a[0]) > 0 : a[1] > b[1]\n}\n\nconst minComp = (a, b) => {\n return a[1] === b[1] ? a[0].localeCompare(b[0]) > 0: a[1] < b[1]\n}\n\nconst SORTracker = function() {\n // max\n this.pq = new PriorityQueue(maxComp)\n // min\n this.best = new PriorityQueue(minComp)\n};\n\n\nSORTracker.prototype.add = function(name, score) {\n this.pq.push([name, score])\n while(!this.best.isEmpty() && maxComp(this.pq.peek(), this.best.peek())) {\n const a = this.best.pop(), b = this.pq.pop()\n this.best.push(b)\n this.pq.push(a)\n }\n};\n\n\nSORTracker.prototype.get = function() {\n const tmp = this.pq.pop()\n this.best.push(tmp)\n return tmp[0]\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 SORTracker = function() {\n this.maxCmp = (a, b) => a[1] === b[1] ? a[0] < b[0] : a[1] > b[1]\n this.minCmp = (a, b) => a[1] === b[1] ? a[0] > b[0] : a[1] < b[1]\n this.maxQ = new PriorityQueue(this.maxCmp)\n this.minQ = new PriorityQueue(this.minCmp)\n this.cnt = 0\n};\n\n\nSORTracker.prototype.add = function(name, score) {\n this.maxQ.push([name, score])\n};\n\n\nSORTracker.prototype.get = function() {\n if(this.cnt) {\n this.minQ.push(this.maxQ.pop())\n while(this.maxCmp(this.maxQ.peek(), this.minQ.peek())) {\n const tmp = this.minQ.pop()\n this.minQ.push(this.maxQ.pop())\n this.maxQ.push(tmp)\n }\n }\n this.cnt++\n\n return this.maxQ.peek()[0]\n};\n\n\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}" ]
2,103
rings-and-rods
[ "For every rod, look through ‘rings’ to see if the rod contains all colors.", "Create 3 booleans, 1 for each color, to store if that color is present for the current rod. If all 3 are true after looking through the string, then the rod contains all the colors." ]
/** * @param {string} rings * @return {number} */ var countPoints = function(rings) { };
There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9. You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where: The first character of the ith pair denotes the ith ring's color ('R', 'G', 'B'). The second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9'). For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1. Return the number of rods that have all three colors of rings on them.   Example 1: Input: rings = "B0B6G0R6R0R6G9" Output: 1 Explanation: - The rod labeled 0 holds 3 rings with all colors: red, green, and blue. - The rod labeled 6 holds 3 rings, but it only has red and blue. - The rod labeled 9 holds only a green ring. Thus, the number of rods with all three colors is 1. Example 2: Input: rings = "B0R0G0R9R0B0G0" Output: 1 Explanation: - The rod labeled 0 holds 6 rings with all colors: red, green, and blue. - The rod labeled 9 holds only a red ring. Thus, the number of rods with all three colors is 1. Example 3: Input: rings = "G4" Output: 0 Explanation: Only one ring is given. Thus, no rods have all three colors.   Constraints: rings.length == 2 * n 1 <= n <= 100 rings[i] where i is even is either 'R', 'G', or 'B' (0-indexed). rings[i] where i is odd is a digit from '0' to '9' (0-indexed).
Easy
[ "hash-table", "string" ]
[ "const countPoints = function(rings) {\n const hash = {}\n \n for(let i = 0, n = rings.length; i < n; i+=2) {\n const ch = rings[i], num = +rings[i + 1]\n if(hash[num] == null) hash[num] = new Set()\n hash[num].add(ch)\n }\n \n \n \n let res = 0\n Object.keys(hash).forEach(k => {\n if(hash[k].size === 3) res++\n })\n \n return res\n};" ]
2,104
sum-of-subarray-ranges
[ "Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it?", "Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j]." ]
/** * @param {number[]} nums * @return {number} */ var subArrayRanges = function(nums) { };
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,2,3] Output: 4 Explanation: The 6 subarrays of nums are the following: [1], range = largest - smallest = 1 - 1 = 0 [2], range = 2 - 2 = 0 [3], range = 3 - 3 = 0 [1,2], range = 2 - 1 = 1 [2,3], range = 3 - 2 = 1 [1,2,3], range = 3 - 1 = 2 So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4. Example 2: Input: nums = [1,3,3] Output: 4 Explanation: The 6 subarrays of nums are the following: [1], range = largest - smallest = 1 - 1 = 0 [3], range = 3 - 3 = 0 [3], range = 3 - 3 = 0 [1,3], range = 3 - 1 = 2 [3,3], range = 3 - 3 = 0 [1,3,3], range = 3 - 1 = 2 So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4. Example 3: Input: nums = [4,-2,-3,4,1] Output: 59 Explanation: The sum of all subarray ranges of nums is 59.   Constraints: 1 <= nums.length <= 1000 -109 <= nums[i] <= 109   Follow-up: Could you find a solution with O(n) time complexity?
Medium
[ "array", "stack", "monotonic-stack" ]
[ "const subArrayRanges = function(nums) {\n const n = nums.length, { max, min } = Math\n let res = 0\n \n for(let i = 0; i < n; i++) {\n let [most, least] = [-Infinity, Infinity]\n for(let j = i; j < n; j++) {\n most = max(most, nums[j])\n least = min(least, nums[j])\n res += most - least \n }\n }\n return res\n};", "const subArrayRanges = function(nums) {\n let res = 0, n = nums.length\n for(let i = 0; i < n; i++) {\n let max = nums[i], min = nums[i]\n for(let j = i; j < n; j++) {\n max = Math.max(max, nums[j])\n min = Math.min(min, nums[j])\n res += max - min\n }\n }\n return res\n};" ]
2,105
watering-plants-ii
[ "Try \"simulating\" the process.", "Since watering each plant takes the same amount of time, where will Alice and Bob meet if they start watering the plants simultaneously? How can you use this to optimize your solution?", "What will you do when both Alice and Bob have to water the same plant?" ]
/** * @param {number[]} plants * @param {number} capacityA * @param {number} capacityB * @return {number} */ var minimumRefill = function(plants, capacityA, capacityB) { };
Alice and Bob want to water n plants in their garden. 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. Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way: Alice waters the plants in order from left to right, starting from the 0th plant. Bob waters the plants in order from right to left, starting from the (n - 1)th plant. They begin watering the plants simultaneously. It takes the same amount of time to water each plant regardless of how much water it needs. Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant. In case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant. Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants.   Example 1: Input: plants = [2,2,3,3], capacityA = 5, capacityB = 5 Output: 1 Explanation: - Initially, Alice and Bob have 5 units of water each in their watering cans. - Alice waters plant 0, Bob waters plant 3. - Alice and Bob now have 3 units and 2 units of water respectively. - Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it. So, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1. Example 2: Input: plants = [2,2,3,3], capacityA = 3, capacityB = 4 Output: 2 Explanation: - Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively. - Alice waters plant 0, Bob waters plant 3. - Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively. - Since neither of them have enough water for their current plants, they refill their cans and then water the plants. So, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2. Example 3: Input: plants = [5], capacityA = 10, capacityB = 8 Output: 0 Explanation: - There is only one plant. - Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant. So, the total number of times they have to refill is 0.   Constraints: n == plants.length 1 <= n <= 105 1 <= plants[i] <= 106 max(plants[i]) <= capacityA, capacityB <= 109
Medium
[ "array", "two-pointers", "simulation" ]
[ "const minimumRefill = function(plants, capacityA, capacityB) {\n const n = plants.length\n let [left, right] = [0, n - 1]\n let [A, B] = [capacityA, capacityB]\n let ans = 0\n while (left < right) {\n if (A < plants[left]) {\n A = capacityA\n ans += 1 \n }\n\n A -= plants[left]\n left += 1\n if (B < plants[right]) {\n B = capacityB\n ans += 1 \n }\n\n B -= plants[right]\n right -= 1 \n }\n\n\n if (left != right || A >= plants[left] || B >= plants[left]) return ans\n return ans + 1 \n};" ]
2,106
maximum-fruits-harvested-after-at-most-k-steps
[ "Does an optimal path have very few patterns? For example, could a path that goes left, turns and goes right, then turns again and goes left be any better than a path that simply goes left, turns, and goes right?", "The optimal path turns at most once. That is, the optimal path is one of these: to go left only; to go right only; to go left, turn and go right; or to go right, turn and go left.", "Moving x steps left then k-x steps right gives you a range of positions that you can reach.", "Use prefix sums to get the sum of all fruits for each possible range.", "Use a similar strategy for all the paths that go right, then turn and go left." ]
/** * @param {number[][]} fruits * @param {number} startPos * @param {number} k * @return {number} */ var maxTotalFruits = function(fruits, startPos, k) { };
Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique. You are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest.   Example 1: Input: fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4 Output: 9 Explanation: The optimal way is to: - Move right to position 6 and harvest 3 fruits - Move right to position 8 and harvest 6 fruits You moved 3 steps and harvested 3 + 6 = 9 fruits in total. Example 2: Input: fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4 Output: 14 Explanation: You can move at most k = 4 steps, so you cannot reach position 0 nor 10. The optimal way is to: - Harvest the 7 fruits at the starting position 5 - Move left to position 4 and harvest 1 fruit - Move right to position 6 and harvest 2 fruits - Move right to position 7 and harvest 4 fruits You moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total. Example 3: Input: fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2 Output: 0 Explanation: You can move at most k = 2 steps and cannot reach any position with fruits.   Constraints: 1 <= fruits.length <= 105 fruits[i].length == 2 0 <= startPos, positioni <= 2 * 105 positioni-1 < positioni for any i > 0 (0-indexed) 1 <= amounti <= 104 0 <= k <= 2 * 105
Hard
[ "array", "binary-search", "sliding-window", "prefix-sum" ]
[ "const maxTotalFruits = function(fruits, startPos, k) {\n let n = fruits.length, { max, min } = Math\n let pos = fruits.map(([p,a]) => p)\n const prefix = Array(n).fill(0)\n\n let curr = 0\n for (let i = 0; i < n; i++) {\n curr += fruits[i][1]\n prefix[i] = curr \n }\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 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 query(left, right) {\n left = max(left, 0)\n right = min(right, 200000)\n let l = bisect_left(pos, left)\n let r = bisect_right(pos, right) - 1\n if (l > r) return 0\n if (!l) return prefix[r]\n return prefix[r] - prefix[l - 1] \n }\n\n\n let best = 0\n let idx = 0\n for(let right = startPos + k; right > startPos - 1; right -= 2) {\n let cand = query(startPos - idx, right)\n best = max(best, cand)\n idx += 1 \n }\n\n idx = 0\n for(let left = startPos - k; left < startPos + 1; left += 2) {\n let cand = query(left, startPos + idx)\n best = max(best, cand)\n idx += 1\n }\n\n return best \n};" ]
2,108
find-first-palindromic-string-in-the-array
[ "Iterate through the elements in order. As soon as the current element is a palindrome, return it.", "To check if an element is a palindrome, can you reverse the string?" ]
/** * @param {string[]} words * @return {string} */ var firstPalindrome = function(words) { };
Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "". A string is palindromic if it reads the same forward and backward.   Example 1: Input: words = ["abc","car","ada","racecar","cool"] Output: "ada" Explanation: The first string that is palindromic is "ada". Note that "racecar" is also palindromic, but it is not the first. Example 2: Input: words = ["notapalindrome","racecar"] Output: "racecar" Explanation: The first and only string that is palindromic is "racecar". Example 3: Input: words = ["def","ghi"] Output: "" Explanation: There are no palindromic strings, so the empty string is returned.   Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 100 words[i] consists only of lowercase English letters.
Easy
[ "array", "two-pointers", "string" ]
null
[]
2,109
adding-spaces-to-a-string
[ "Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character.", "Since the array of indices for the space locations is sorted, use a pointer to keep track of the next index to place a space. Only increment the pointer once a space has been appended.", "Ensure that your append operation can be done in O(1)." ]
/** * @param {string} s * @param {number[]} spaces * @return {string} */ var addSpaces = function(s, spaces) { };
You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. For example, given s = "EnjoyYourCoffee" and spaces = [5, 9], we place spaces before 'Y' and 'C', which are at indices 5 and 9 respectively. Thus, we obtain "Enjoy Your Coffee". Return the modified string after the spaces have been added.   Example 1: Input: s = "LeetcodeHelpsMeLearn", spaces = [8,13,15] Output: "Leetcode Helps Me Learn" Explanation: The indices 8, 13, and 15 correspond to the underlined characters in "LeetcodeHelpsMeLearn". We then place spaces before those characters. Example 2: Input: s = "icodeinpython", spaces = [1,5,7,9] Output: "i code in py thon" Explanation: The indices 1, 5, 7, and 9 correspond to the underlined characters in "icodeinpython". We then place spaces before those characters. Example 3: Input: s = "spacing", spaces = [0,1,2,3,4,5,6] Output: " s p a c i n g" Explanation: We are also able to place spaces before the first character of the string.   Constraints: 1 <= s.length <= 3 * 105 s consists only of lowercase and uppercase English letters. 1 <= spaces.length <= 3 * 105 0 <= spaces[i] <= s.length - 1 All the values of spaces are strictly increasing.
Medium
[ "array", "string", "simulation" ]
null
[]
2,110
number-of-smooth-descent-periods-of-a-stock
[ "Any array is a series of adjacent longest possible smooth descent periods. For example, [5,3,2,1,7,6] is [5] + [3,2,1] + [7,6].", "Think of a 2-pointer approach to traverse the array and find each longest possible period.", "Suppose you found the longest possible period with a length of k. How many periods are within that period? How can you count them quickly? Think of the formula to calculate the sum of 1, 2, 3, ..., k." ]
/** * @param {number[]} prices * @return {number} */ var getDescentPeriods = function(prices) { };
You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day. A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule. Return the number of smooth descent periods.   Example 1: Input: prices = [3,2,1,4] Output: 7 Explanation: There are 7 smooth descent periods: [3], [2], [1], [4], [3,2], [2,1], and [3,2,1] Note that a period with one day is a smooth descent period by the definition. Example 2: Input: prices = [8,6,7,7] Output: 4 Explanation: There are 4 smooth descent periods: [8], [6], [7], and [7] Note that [8,6] is not a smooth descent period as 8 - 6 ≠ 1. Example 3: Input: prices = [1] Output: 1 Explanation: There is 1 smooth descent period: [1]   Constraints: 1 <= prices.length <= 105 1 <= prices[i] <= 105
Medium
[ "array", "math", "dynamic-programming" ]
null
[]
2,111
minimum-operations-to-make-the-array-k-increasing
[ "Can we divide the array into non-overlapping subsequences and simplify the problem?", "In the final array, arr[i-k] ≤ arr[i] should hold. We can use this to divide the array into at most k non-overlapping sequences, where arr[i] will belong to the (i%k)th sequence.", "Now our problem boils down to performing the minimum operations on each sequence such that it becomes non-decreasing. Our answer will be the sum of operations on each sequence.", "Which indices of a sequence should we not change in order to count the minimum operations? Can finding the longest non-decreasing subsequence of the sequence help?" ]
/** * @param {number[]} arr * @param {number} k * @return {number} */ var kIncreasing = function(arr, k) { };
You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1. For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: arr[0] <= arr[2] (4 <= 5) arr[1] <= arr[3] (1 <= 2) arr[2] <= arr[4] (5 <= 6) arr[3] <= arr[5] (2 <= 2) However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1]) or k = 3 (because arr[0] > arr[3]). In one operation, you can choose an index i and change arr[i] into any positive integer. Return the minimum number of operations required to make the array K-increasing for the given k.   Example 1: Input: arr = [5,4,3,2,1], k = 1 Output: 4 Explanation: For k = 1, the resultant array has to be non-decreasing. Some of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations. It is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations. It can be shown that we cannot make the array K-increasing in less than 4 operations. Example 2: Input: arr = [4,1,5,2,6,2], k = 2 Output: 0 Explanation: This is the same example as the one in the problem description. Here, for every index i where 2 <= i <= 5, arr[i-2] <= arr[i]. Since the given array is already K-increasing, we do not need to perform any operations. Example 3: Input: arr = [4,1,5,2,6,2], k = 3 Output: 2 Explanation: Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5. One of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5. The array will now be [4,1,5,4,6,5]. Note that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.   Constraints: 1 <= arr.length <= 105 1 <= arr[i], k <= arr.length
Hard
[ "array", "binary-search" ]
[ "const kIncreasing = function(arr, k) {\n let res = 0, matrix = Array.from({ length: k }, () => []), n = arr.length\n for(let i = 0; i < k; i++) {\n for(let j = i; j < n; j += k) {\n matrix[i].push(arr[j])\n }\n }\n\n for (let i = 0; i < k; i++) {\n res += matrix[i].length - nonDecreasing(matrix[i])\n }\n\n return res\n\n function bisect_right(ar, x, l = 0, r) {\n if(r == null) r = ar.length\n while(l < r) {\n const mid = ~~((l + r) / 2)\n if(ar[mid] <= x) l = mid + 1\n else r = mid\n }\n return l\n }\n\n function nonDecreasing(ar) {\n let stk = []\n for(let e of ar) {\n const idx = bisect_right(stk, e)\n if(idx === stk.length) stk.push(e)\n else stk[idx] = e\n }\n\n return stk.length\n }\n};", "const kIncreasing = function(arr, k) {\n const n = arr.length\n const a = Array.from({ length: k }, () => Array())\n \n for(let i = 0; i < k; i++) {\n for(let j = i; j < n; j += k) {\n a[i].push(arr[j])\n }\n }\n \n let res = 0\n for(let i = 0; i < a.length; i++) {\n const r = a[i]\n res += r.length - lis(r)\n }\n \n return res\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 \n function lis(ar) {\n let q = []\n for (let x of ar) {\n let i = bisect_right(q, x)\n if (i == q.length) q.push(x)\n else q[i] = x \n }\n\n return q.length\n }\n};" ]
2,114
maximum-number-of-words-found-in-sentences
[ "Process each sentence separately and count the number of words by looking for the number of space characters in the sentence and adding it by 1." ]
/** * @param {string[]} sentences * @return {number} */ var mostWordsFound = function(sentences) { };
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. You are given an array of strings sentences, where each sentences[i] represents a single sentence. Return the maximum number of words that appear in a single sentence.   Example 1: Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"] Output: 6 Explanation: - The first sentence, "alice and bob love leetcode", has 5 words in total. - The second sentence, "i think so too", has 4 words in total. - The third sentence, "this is great thanks very much", has 6 words in total. Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words. Example 2: Input: sentences = ["please wait", "continue to fight", "continue to win"] Output: 3 Explanation: It is possible that multiple sentences contain the same number of words. In this example, the second and third sentences (underlined) have the same number of words.   Constraints: 1 <= sentences.length <= 100 1 <= sentences[i].length <= 100 sentences[i] consists only of lowercase English letters and ' ' only. sentences[i] does not have leading or trailing spaces. All the words in sentences[i] are separated by a single space.
Easy
[ "array", "string" ]
null
[]
2,115
find-all-possible-recipes-from-given-supplies
[ "Can we use a data structure to quickly query whether we have a certain ingredient?", "Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this." ]
/** * @param {string[]} recipes * @param {string[][]} ingredients * @param {string[]} supplies * @return {string[]} */ var findAllRecipes = function(recipes, ingredients, supplies) { };
You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients.   Example 1: Input: recipes = ["bread"], ingredients = [["yeast","flour"]], supplies = ["yeast","flour","corn"] Output: ["bread"] Explanation: We can create "bread" since we have the ingredients "yeast" and "flour". Example 2: Input: recipes = ["bread","sandwich"], ingredients = [["yeast","flour"],["bread","meat"]], supplies = ["yeast","flour","meat"] Output: ["bread","sandwich"] Explanation: We can create "bread" since we have the ingredients "yeast" and "flour". We can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread". Example 3: Input: recipes = ["bread","sandwich","burger"], ingredients = [["yeast","flour"],["bread","meat"],["sandwich","meat","bread"]], supplies = ["yeast","flour","meat"] Output: ["bread","sandwich","burger"] Explanation: We can create "bread" since we have the ingredients "yeast" and "flour". We can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread". We can create "burger" since we have the ingredient "meat" and can create the ingredients "bread" and "sandwich".   Constraints: n == recipes.length == ingredients.length 1 <= n <= 100 1 <= ingredients[i].length, supplies.length <= 100 1 <= recipes[i].length, ingredients[i][j].length, supplies[k].length <= 10 recipes[i], ingredients[i][j], and supplies[k] consist only of lowercase English letters. All the values of recipes and supplies combined are unique. Each ingredients[i] does not contain any duplicate values.
Medium
[ "array", "hash-table", "string", "graph", "topological-sort" ]
[ "const findAllRecipes = function(recipes, ingredients, supplies) {\n const set = new Set(supplies), res = [], graph = {}, n = recipes.length\n const inDegree = {}\n for(let x of recipes) inDegree[x] = 0\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < ingredients[i].length; j++) {\n const ing = ingredients[i][j]\n if(!set.has(ing)) {\n if (graph[ing] == null) graph[ing] = []\n graph[ing].push(recipes[i])\n inDegree[recipes[i]]++\n }\n }\n }\n // Kahn's Algorithm\n const q = []\n for(let x in inDegree) {\n if (inDegree[x] === 0) q.push(x)\n }\n while(q.length) {\n const len = q.length\n for(let i = 0; i < len; i++) {\n const cur = q.pop()\n res.push(cur)\n for(let next of (graph[cur] || [])) {\n inDegree[next]--\n if(inDegree[next] === 0) {\n q.push(next)\n }\n }\n }\n }\n return res\n};", "const findAllRecipes = function(recipes, ingredients, supplies) {\n const graph = {}\n const n = recipes.length\n\n const inDegree = {}\n supplies = new Set(supplies)\n for(const e of recipes) inDegree[e] = 0\n\n let q = []\n for(let i = 0; i < n; i++) {\n const rec = recipes[i]\n for(let e of ingredients[i]) {\n if(!supplies.has(e)) {\n if(graph[e] == null) graph[e] = []\n graph[e].push(rec)\n inDegree[rec]++\n }\n }\n }\n // console.log(inDegree)\n for(let i = 0; i < n; i++) {\n if(inDegree[recipes[i]] === 0) {\n q.push(recipes[i])\n }\n }\n \n // console.log(q)\n const res = [] \n while(q.length) {\n const size = q.length\n const nxt = []\n \n for(let i = 0; i < size; i++) {\n const cur = q[i]\n res.push(cur)\n for(const e of (graph[cur] || [])) {\n inDegree[e]--\n if(inDegree[e] === 0) nxt.push(e)\n }\n }\n \n q = nxt\n }\n\n return res\n};" ]
2,116
check-if-a-parentheses-string-can-be-valid
[ "Can an odd length string ever be valid?", "From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use?", "After the above, we may have locked indices of '(' and additional unlocked indices. How can you balance out the locked '(' now? What if you cannot balance any locked '('?" ]
/** * @param {string} s * @param {string} locked * @return {boolean} */ var canBeValid = function(s, locked) { };
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: It is (). It can be written as AB (A concatenated with B), where A and B are valid parentheses strings. It can be written as (A), where A is a valid parentheses string. You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked, If locked[i] is '1', you cannot change s[i]. But if locked[i] is '0', you can change s[i] to either '(' or ')'. Return true if you can make s a valid parentheses string. Otherwise, return false.   Example 1: Input: s = "))()))", locked = "010100" Output: true Explanation: locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3]. We change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid. Example 2: Input: s = "()()", locked = "0000" Output: true Explanation: We do not need to make any changes because s is already valid. Example 3: Input: s = ")", locked = "0" Output: false Explanation: locked permits us to change s[0]. Changing s[0] to either '(' or ')' will not make s valid.   Constraints: n == s.length == locked.length 1 <= n <= 105 s[i] is either '(' or ')'. locked[i] is either '0' or '1'.
Medium
[ "string", "stack", "greedy" ]
[ "const canBeValid = function(s, locked) {\n const n = s.length\n if(n % 2 === 1) return false\n let x = 0\n for(let i = 0; i < n; i++) {\n if(s[i] === '(' || locked[i] === '0') x++\n else if(x > 0) x--\n else return false\n }\n x = 0\n for(let i = n - 1; i >= 0; i--) {\n if(s[i] === ')' || locked[i] === '0') x++\n else if(x > 0) x--\n else return false\n }\n return true\n};", "const canBeValid = function (s, locked) {\n return s.length % 2 === 0 && chk(s, locked, '(') && chk(s, locked, ')')\n\n function chk(s, locked, op) {\n let bal = 0,\n wild = 0,\n sz = s.length\n let start = op === '(' ? 0 : sz - 1,\n dir = op === '(' ? 1 : -1\n for (let i = start; i >= 0 && i < sz && wild + bal >= 0; i += dir) {\n if (locked[i] === '1') bal += s[i] === op ? 1 : -1\n else wild++\n }\n return Math.abs(bal) <= wild\n }\n}" ]
2,117
abbreviating-the-product-of-a-range
[ "Calculating the number of trailing zeros, the last five digits, and the first five digits can all be done separately.", "Use a prime factorization property to find the number of trailing zeros. Use modulo to find the last 5 digits. Use a logarithm property to find the first 5 digits.", "The number of trailing zeros C is nothing but the number of times the product is completely divisible by 10. Since 2 and 5 are the only prime factors of 10, C will be equal to the minimum number of times 2 or 5 appear in the prime factorization of the product.", "Iterate through the integers from left to right. For every integer, keep dividing it by 2 as long as it is divisible by 2 and C occurrences of 2 haven't been removed in total. Repeat this process for 5. Finally, multiply the integer under modulo of 10^5 with the product obtained till now to obtain the last five digits.", "The product P can be represented as P=10^(x+y) where x is the integral part and y is the fractional part of x+y. Using the property \"if S = A * B, then log(S) = log(A) + log(B)\", we can write x+y = log_10(P) = sum(log_10(i)) for each integer i in [left, right]. Once we obtain the sum, the first five digits can be represented as floor(10^(y+4))." ]
/** * @param {number} left * @param {number} right * @return {string} */ var abbreviateProduct = function(left, right) { };
You are given two positive integers left and right with left <= right. Calculate the product of all integers in the inclusive range [left, right]. Since the product may be very large, you will abbreviate it following these steps: Count all trailing zeros in the product and remove them. Let us denote this count as C. For example, there are 3 trailing zeros in 1000, and there are 0 trailing zeros in 546. Denote the remaining number of digits in the product as d. If d > 10, then express the product as <pre>...<suf> where <pre> denotes the first 5 digits of the product, and <suf> denotes the last 5 digits of the product after removing all trailing zeros. If d <= 10, we keep it unchanged. For example, we express 1234567654321 as 12345...54321, but 1234567 is represented as 1234567. Finally, represent the product as a string "<pre>...<suf>eC". For example, 12345678987600000 will be represented as "12345...89876e5". Return a string denoting the abbreviated product of all integers in the inclusive range [left, right].   Example 1: Input: left = 1, right = 4 Output: "24e0" Explanation: The product is 1 × 2 × 3 × 4 = 24. There are no trailing zeros, so 24 remains the same. The abbreviation will end with "e0". Since the number of digits is 2, which is less than 10, we do not have to abbreviate it further. Thus, the final representation is "24e0". Example 2: Input: left = 2, right = 11 Output: "399168e2" Explanation: The product is 39916800. There are 2 trailing zeros, which we remove to get 399168. The abbreviation will end with "e2". The number of digits after removing the trailing zeros is 6, so we do not abbreviate it further. Hence, the abbreviated product is "399168e2". Example 3: Input: left = 371, right = 375 Output: "7219856259e3" Explanation: The product is 7219856259000.   Constraints: 1 <= left <= right <= 104
Hard
[ "math" ]
null
[]
2,119
a-number-after-a-double-reversal
[ "Other than the number 0 itself, any number that ends with 0 would lose some digits permanently when reversed." ]
/** * @param {number} num * @return {boolean} */ var isSameAfterReversals = function(num) { };
Reversing an integer means to reverse all its digits. For example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained. Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false.   Example 1: Input: num = 526 Output: true Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num. Example 2: Input: num = 1800 Output: false Explanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num. Example 3: Input: num = 0 Output: true Explanation: Reverse num to get 0, then reverse 0 to get 0, which equals num.   Constraints: 0 <= num <= 106
Easy
[ "math" ]
[ "var isSameAfterReversals = function(num) {\n if(('' +num).length === 1) return true\n const tmp = (''+num).endsWith('0')\n return !tmp\n};" ]
2,120
execution-of-all-suffix-instructions-staying-in-a-grid
[ "The constraints are not very large. Can we simulate the execution by starting from each index of s?", "Before any of the stopping conditions is met, stop the simulation for that index and set the answer for that index." ]
/** * @param {number} n * @param {number[]} startPos * @param {string} s * @return {number[]} */ var executeInstructions = function(n, startPos, s) { };
There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol). You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down). The robot can begin executing from any ith instruction in s. It executes the instructions one by one towards the end of s but it stops if either of these conditions is met: The next instruction will move the robot off the grid. There are no more instructions left to execute. Return an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the ith instruction in s.   Example 1: Input: n = 3, startPos = [0,1], s = "RRDDLU" Output: [1,5,4,3,1,0] Explanation: Starting from startPos and beginning execution from the ith instruction: - 0th: "RRDDLU". Only one instruction "R" can be executed before it moves off the grid. - 1st: "RDDLU". All five instructions can be executed while it stays in the grid and ends at (1, 1). - 2nd: "DDLU". All four instructions can be executed while it stays in the grid and ends at (1, 0). - 3rd: "DLU". All three instructions can be executed while it stays in the grid and ends at (0, 0). - 4th: "LU". Only one instruction "L" can be executed before it moves off the grid. - 5th: "U". If moving up, it would move off the grid. Example 2: Input: n = 2, startPos = [1,1], s = "LURD" Output: [4,1,0,0] Explanation: - 0th: "LURD". - 1st: "URD". - 2nd: "RD". - 3rd: "D". Example 3: Input: n = 1, startPos = [0,0], s = "LRUD" Output: [0,0,0,0] Explanation: No matter which instruction the robot begins execution from, it would move off the grid.   Constraints: m == s.length 1 <= n, m <= 500 startPos.length == 2 0 <= startrow, startcol < n s consists of 'L', 'R', 'U', and 'D'.
Medium
[ "string", "simulation" ]
null
[]
2,121
intervals-between-identical-elements
[ "For each unique value found in the array, store a sorted list of indices of elements that have this value in the array.", "One way of doing this is to use a HashMap that maps the values to their list of indices. Update this mapping as you iterate through the array.", "Process each list of indices separately and get the sum of intervals for the elements of that value by utilizing prefix sums.", "For each element, keep track of the sum of indices of the identical elements that have come before and that will come after respectively. Use this to calculate the sum of intervals for that element to the rest of the elements with identical values." ]
/** * @param {number[]} arr * @return {number[]} */ var getDistances = function(arr) { };
You are given a 0-indexed array of n integers arr. The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|. Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i]. Note: |x| is the absolute value of x.   Example 1: Input: arr = [2,1,3,1,2,3,3] Output: [4,2,7,2,4,4,5] Explanation: - Index 0: Another 2 is found at index 4. |0 - 4| = 4 - Index 1: Another 1 is found at index 3. |1 - 3| = 2 - Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7 - Index 3: Another 1 is found at index 1. |3 - 1| = 2 - Index 4: Another 2 is found at index 0. |4 - 0| = 4 - Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4 - Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5 Example 2: Input: arr = [10,5,10,10] Output: [5,0,3,4] Explanation: - Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5 - Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0. - Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3 - Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4   Constraints: n == arr.length 1 <= n <= 105 1 <= arr[i] <= 105
Medium
[ "array", "hash-table", "prefix-sum" ]
[ "const getDistances = function(arr) {\n let n = arr.length\n const pre = Array(n).fill(0), suf = Array(n).fill(0), res = Array(n).fill(0), mp = {}\n \n for(let i = 0; i < n; i++) {\n if(mp[arr[i]] == null) mp[arr[i]] = []\n mp[arr[i]].push(i)\n }\n\n Object.keys(mp).forEach(k => {\n const idxArr = mp[k]\n for(let i = 1; i < idxArr.length; i++) {\n pre[idxArr[i]] = pre[idxArr[i - 1]] + i * (idxArr[i] - idxArr[i - 1])\n }\n })\n\n Object.keys(mp).forEach(k => {\n const idxArr = mp[k]\n for(let i = idxArr.length - 2; i >= 0; i--) {\n suf[idxArr[i]] = suf[idxArr[i + 1]] + (idxArr.length - 1 - i) * (idxArr[i + 1] - idxArr[i])\n }\n })\n\n for(let i = 0; i < n; i++) res[i] = pre[i] + suf[i]\n\n return res\n};" ]
2,122
recover-the-original-array
[ "If we fix the value of k, how can we check if an original array exists for the fixed k?", "The smallest value of nums is obtained by subtracting k from the smallest value of the original array. How can we use this to reduce the search space for finding a valid k?", "You can compute every possible k by using the smallest value of nums (as lower[i]) against every other value in nums (as the corresponding higher[i]).", "For every computed k, greedily pair up the values in nums. This can be done sorting nums, then using a map to store previous values and searching that map for a corresponding lower[i] for the current nums[j] (as higher[i])." ]
/** * @param {number[]} nums * @return {number[]} */ var recoverArray = function(nums) { };
Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: lower[i] = arr[i] - k, for every index i where 0 <= i < n higher[i] = arr[i] + k, for every index i where 0 <= i < n Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher, but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher, return the original array arr. In case the answer is not unique, return any valid array. Note: The test cases are generated such that there exists at least one valid array arr.   Example 1: Input: nums = [2,10,6,4,8,12] Output: [3,7,11] Explanation: If arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12]. Combining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums. Another valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12]. Example 2: Input: nums = [1,1,3,3] Output: [2,2] Explanation: If arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3]. Combining lower and higher gives us [1,1,3,3], which is equal to nums. Note that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0. This is invalid since k must be positive. Example 3: Input: nums = [5,435] Output: [220] Explanation: The only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].   Constraints: 2 * n == nums.length 1 <= n <= 1000 1 <= nums[i] <= 109 The test cases are generated such that there exists at least one valid array arr.
Hard
[ "array", "hash-table", "sorting", "enumeration" ]
[ "const recoverArray = function(nums) {\n const n = nums.length, cnt = calcHash(nums)\n nums.sort((a, b) => a - b)\n for(let i = 1; i < n; i++) {\n const tk = nums[i] - nums[0]\n if(tk === 0 || tk % 2 === 1) continue\n const [valid, res] = helper(tk)\n if(valid) return res\n }\n \n function helper(tk) {\n const res = [], hash = Object.assign({}, cnt)\n for(let i = 0; i < n; i++) {\n const cur = nums[i]\n if(hash[cur] === 0) continue\n if(hash[cur + tk] === 0 || hash[cur + tk] == null) return [false]\n hash[cur]--\n hash[cur + tk]--\n res.push(cur + tk / 2)\n }\n return [true, res]\n }\n function calcHash(arr) {\n const hash = {}\n for(let e of arr) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n return hash\n }\n};" ]
2,124
check-if-all-as-appears-before-all-bs
[ "You can check the opposite: check if there is a ‘b’ before an ‘a’. Then, negate and return that answer.", "s should not have any occurrences of “ba” as a substring." ]
/** * @param {string} s * @return {boolean} */ var checkString = function(s) { };
Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.   Example 1: Input: s = "aaabbb" Output: true Explanation: The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5. Hence, every 'a' appears before every 'b' and we return true. Example 2: Input: s = "abab" Output: false Explanation: There is an 'a' at index 2 and a 'b' at index 1. Hence, not every 'a' appears before every 'b' and we return false. Example 3: Input: s = "bbb" Output: true Explanation: There are no 'a's, hence, every 'a' appears before every 'b' and we return true.   Constraints: 1 <= s.length <= 100 s[i] is either 'a' or 'b'.
Easy
[ "string" ]
[ "const checkString = function(s) {\n const la = s.lastIndexOf('a')\n const fb = s.indexOf('b')\n return fb === -1 ? true : la < fb\n};" ]
2,125
number-of-laser-beams-in-a-bank
[ "What is the commonality between security devices on the same row?", "Each device on the same row has the same number of beams pointing towards the devices on the next row with devices.", "If you were given an integer array where each element is the number of security devices on each row, can you solve it?", "Convert the input to such an array, skip any row with no security device, then find the sum of the product between adjacent elements." ]
/** * @param {string[]} bank * @return {number} */ var numberOfBeams = function(bank) { };
Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: The two devices are located on two different rows: r1 and r2, where r1 < r2. For each row i where r1 < i < r2, there are no security devices in the ith row. Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank.   Example 1: Input: bank = ["011001","000000","010100","001000"] Output: 8 Explanation: Between each of the following device pairs, there is one beam. In total, there are 8 beams: * bank[0][1] -- bank[2][1] * bank[0][1] -- bank[2][3] * bank[0][2] -- bank[2][1] * bank[0][2] -- bank[2][3] * bank[0][5] -- bank[2][1] * bank[0][5] -- bank[2][3] * bank[2][1] -- bank[3][2] * bank[2][3] -- bank[3][2] Note that there is no beam between any device on the 0th row with any on the 3rd row. This is because the 2nd row contains security devices, which breaks the second condition. Example 2: Input: bank = ["000","111","000"] Output: 0 Explanation: There does not exist two devices located on two different rows.   Constraints: m == bank.length n == bank[i].length 1 <= m, n <= 500 bank[i][j] is either '0' or '1'.
Medium
[ "array", "math", "string", "matrix" ]
[ "var numberOfBeams = function(bank) {\n const comb = (num1, num2) => num1 * num2\n const m = bank.length, n = bank[0].length\n if(m === 0 || n === 0) return 0\n let pre = 0, res = 0\n for(let j = 0; j < n; j++) {\n if(bank[0][j] === '1') pre++\n }\n for(let i = 1; i < m; i++) {\n let chk = 0, cur = bank[i]\n for(let j = 0; j < n; j++) {\n if(cur[j] === '1') chk++\n }\n if(chk) {\n res += comb(pre, chk)\n pre = chk\n }\n }\n return res\n};" ]
2,126
destroying-asteroids
[ "Choosing the asteroid to collide with can be done greedily.", "If an asteroid will destroy the planet, then every bigger asteroid will also destroy the planet.", "You only need to check the smallest asteroid at each collision. If it will destroy the planet, then every other asteroid will also destroy the planet.", "Sort the asteroids in non-decreasing order by mass, then greedily try to collide with the asteroids in that order." ]
/** * @param {number} mass * @param {number[]} asteroids * @return {boolean} */ var asteroidsDestroyed = function(mass, asteroids) { };
You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed. Return true if all asteroids can be destroyed. Otherwise, return false.   Example 1: Input: mass = 10, asteroids = [3,9,19,5,21] Output: true Explanation: One way to order the asteroids is [9,19,5,3,21]: - The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19 - The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38 - The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43 - The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46 - The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67 All asteroids are destroyed. Example 2: Input: mass = 5, asteroids = [4,9,23,4] Output: false Explanation: The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23. After the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22. This is less than 23, so a collision would not destroy the last asteroid.   Constraints: 1 <= mass <= 105 1 <= asteroids.length <= 105 1 <= asteroids[i] <= 105
Medium
[ "array", "greedy", "sorting" ]
[ "const asteroidsDestroyed = function(mass, asteroids) {\n asteroids.sort((a, b) => a - b)\n let res = true\n for(let i = 0, n = asteroids.length; i < n; i++) {\n const cur = asteroids[i]\n if(mass >= cur) {\n mass += cur\n } else {\n res = false\n break\n }\n }\n \n return res\n};" ]
2,127
maximum-employees-to-be-invited-to-a-meeting
[ "From the given array favorite, create a graph where for every index i, there is a directed edge from favorite[i] to i. The graph will be a combination of cycles and chains of acyclic edges. Now, what are the ways in which we can choose employees to sit at the table?", "The first way by which we can choose employees is by selecting a cycle of the graph. It can be proven that in this case, the employees that do not lie in the cycle can never be seated at the table.", "The second way is by combining acyclic chains. At most two chains can be combined by a cycle of length 2, where each chain ends on one of the employees in the cycle." ]
/** * @param {number[]} favorite * @return {number} */ var maximumInvitations = function(favorite) { };
A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting.   Example 1: Input: favorite = [2,2,1,2] Output: 3 Explanation: The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table. All employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously. Note that the company can also invite employees 1, 2, and 3, and give them their desired seats. The maximum number of employees that can be invited to the meeting is 3. Example 2: Input: favorite = [1,2,0] Output: 3 Explanation: Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee. The seating arrangement will be the same as that in the figure given in example 1: - Employee 0 will sit between employees 2 and 1. - Employee 1 will sit between employees 0 and 2. - Employee 2 will sit between employees 1 and 0. The maximum number of employees that can be invited to the meeting is 3. Example 3: Input: favorite = [3,0,1,4,1] Output: 4 Explanation: The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table. Employee 2 cannot be invited because the two spots next to their favorite employee 1 are taken. So the company leaves them out of the meeting. The maximum number of employees that can be invited to the meeting is 4.   Constraints: n == favorite.length 2 <= n <= 105 0 <= favorite[i] <= n - 1 favorite[i] != i
Hard
[ "depth-first-search", "graph", "topological-sort" ]
[ "const maximumInvitations = function(favorite) {\n const n = favorite.length\n const inDegree = Array(n).fill(0)\n const { max } = Math\n for(let i = 0; i < n; i++) {\n inDegree[favorite[i]]++\n }\n \n let q = []\n const visited = Array(n).fill(0)\n const depth = Array(n).fill(1)\n for(let i = 0; i < n; i++) {\n if(inDegree[i] === 0) {\n q.push(i)\n visited[i] = 1\n depth[i] = 1\n }\n }\n \n while(q.length) {\n const cur = q.pop()\n const nxt = favorite[cur]\n inDegree[nxt]--\n if(inDegree[nxt] === 0) {\n q.push(nxt)\n visited[nxt] = 1\n }\n depth[nxt] = max(depth[nxt], depth[cur] + 1)\n }\n\n let maxLoopSize = 0\n let twoNodesSize = 0\n\n for(let i = 0; i < n; i++) {\n if(visited[i] === 1) continue\n let j = i\n let cnt = 0\n while(visited[j] === 0) {\n cnt++\n visited[j] = 1\n j = favorite[j]\n }\n \n if(cnt > 2) {\n maxLoopSize = max(maxLoopSize, cnt)\n } else if(cnt === 2) {\n twoNodesSize += depth[i] + depth[favorite[i]]\n }\n }\n \n return max(maxLoopSize, twoNodesSize)\n};", "const maximumInvitations = function (favorite) {\n const n = favorite.length\n const indegree = Array(n).fill(0)\n for (let i = 0; i < n; i++) indegree[favorite[i]]++\n const { max } = Math\n let q = []\n const visited = Array(n).fill(0)\n const depth = Array(n).fill(1)\n for (let i = 0; i < n; i++) {\n if (indegree[i] === 0) {\n depth[i] = 1\n visited[i] = 1\n q.push(i)\n }\n }\n\n while (q.length) {\n const cur = q.shift()\n const nxt = favorite[cur]\n indegree[nxt]--\n if (indegree[nxt] == 0) {\n q.push(nxt)\n visited[nxt] = 1\n }\n depth[nxt] = depth[cur] + 1\n }\n\n let max_circle_size = 0\n let max_link_size = 0\n for (let i = 0; i < n; i++) {\n if (visited[i] === 1) continue\n let j = i\n let count = 0\n while (visited[j] == 0) {\n count++\n visited[j] = 1\n j = favorite[j]\n }\n if (count > 2) max_circle_size = max(max_circle_size, count)\n else if (count == 2) max_link_size += depth[i] + depth[favorite[i]]\n }\n\n return max(max_circle_size, max_link_size)\n}", "var maximumInvitations = function(favorite) {\n const n = favorite.length, m = Array(n).fill(-1), r = Array.from({ length: n }, () => [])\n for(let i = 0; i < n; i++) r[favorite[i]].push(i)\n \n function dfs(u) {\n if(m[u] !== -1) return m[u]\n let res = 0\n for(let v of r[u]) res = Math.max(res, dfs(v))\n return m[u] = 1 + res\n }\n let res = 0, free = 0\n for(let i = 0; i < n; ++i) {\n if (m[i] != -1) continue; // skip visited nodes\n if (favorite[favorite[i]] == i) {\n m[i] = m[favorite[i]] = 0;\n let a = 0, b = 0; // find the length of the longest arms starting from `i` and `A[i]`\n for (let v of r[i]) {\n if (v == favorite[i]) continue;\n a = Math.max(a, dfs(v));\n }\n for (let v of r[favorite[i]]) {\n if (v == i) continue;\n b = Math.max(b, dfs(v));\n }\n free += a + b + 2; // this free component is of length `a+b+2`\n } \n }\n function dfs2(u) {\n if (m[u] != -1) return[u, m[u], false]; // this is the merge point\n m[u] = 0;\n let [mergePoint, depth, mergePointMet] = dfs2(favorite[u]);\n if (mergePointMet) { // If we've met the merge point again already, this node is outside of the cycle and should be ignored.\n m[u] = 0;\n return [mergePoint, depth, true];\n }\n m[u] = 1 + depth; // If we haven't met the merge point, we increment the depth.\n return [mergePoint, m[u], u == mergePoint];\n }\n \n for(let i = 0; i < n; i++) {\n if(m[i] !== -1) continue\n let [mergePoint, depth, mergePointMet] = dfs2(i)\n if(mergePointMet) res = Math.max(res, depth)\n }\n \n return Math.max(res, free)\n};" ]
2,129
capitalize-the-title
[ "Firstly, try to find all the words present in the string.", "On the basis of each word's lengths, simulate the process explained in Problem." ]
/** * @param {string} title * @return {string} */ var capitalizeTitle = function(title) { };
You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: If the length of the word is 1 or 2 letters, change all letters to lowercase. Otherwise, change the first letter to uppercase and the remaining letters to lowercase. Return the capitalized title.   Example 1: Input: title = "capiTalIze tHe titLe" Output: "Capitalize The Title" Explanation: Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase. Example 2: Input: title = "First leTTeR of EACH Word" Output: "First Letter of Each Word" Explanation: The word "of" has length 2, so it is all lowercase. The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase. Example 3: Input: title = "i lOve leetcode" Output: "i Love Leetcode" Explanation: The word "i" has length 1, so it is lowercase. The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.   Constraints: 1 <= title.length <= 100 title consists of words separated by a single space without any leading or trailing spaces. Each word consists of uppercase and lowercase English letters and is non-empty.
Easy
[ "string" ]
null
[]
2,130
maximum-twin-sum-of-a-linked-list
[ "How can \"reversing\" a part of the linked list help find the answer?", "We know that the nodes of the first half are twins of nodes in the second half, so try dividing the linked list in half and reverse the second half.", "How can two pointers be used to find every twin sum optimally?", "Use two different pointers pointing to the first nodes of the two halves of the linked list. The second pointer will point to the first node of the reversed half, which is the (n-1-i)th node in the original linked list. By moving both pointers forward at the same time, we find all twin sums." ]
/** * 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 pairSum = function(head) { };
In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4. The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list.   Example 1: Input: head = [5,4,2,1] Output: 6 Explanation: Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6. There are no other nodes with twins in the linked list. Thus, the maximum twin sum of the linked list is 6. Example 2: Input: head = [4,2,2,3] Output: 7 Explanation: The nodes with twins present in this linked list are: - Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7. - Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4. Thus, the maximum twin sum of the linked list is max(7, 4) = 7. Example 3: Input: head = [1,100000] Output: 100001 Explanation: There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.   Constraints: The number of nodes in the list is an even integer in the range [2, 105]. 1 <= Node.val <= 105
Medium
[ "linked-list", "two-pointers", "stack" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "const pairSum = function(head) {\n let slow = head, fast = head\n while(fast && fast.next) {\n slow = slow.next\n fast = fast.next.next\n }\n // reverse\n let next = null, pre = null\n while(slow) {\n next = slow.next\n slow.next = pre\n pre = slow\n slow = next\n }\n\n let res = 0\n while(pre) {\n res = Math.max(res, pre.val + head.val)\n pre = pre.next\n head = head.next\n }\n \n return res\n};", "const pairSum = function(head) {\n const arr = []\n let cur = head\n \n while(cur) {\n arr.push(cur.val)\n cur = cur.next\n }\n \n let res = 0\n for(let i = 0, n = arr.length; i < n / 2; i++) {\n res = Math.max(res, arr[i] + arr[n - 1 - i])\n }\n \n return res\n};" ]
2,131
longest-palindrome-by-concatenating-two-letter-words
[ "A palindrome must be mirrored over the center. Suppose we have a palindrome. If we prepend the word \"ab\" on the left, what must we append on the right to keep it a palindrome?", "We must append \"ba\" on the right. The number of times we can do this is the minimum of (occurrences of \"ab\") and (occurrences of \"ba\").", "For words that are already palindromes, e.g. \"aa\", we can prepend and append these in pairs as described in the previous hint. We can also use exactly one in the middle to form an even longer palindrome." ]
/** * @param {string[]} words * @return {number} */ var longestPalindrome = function(words) { };
You are given an array of strings words. Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once. Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0. A palindrome is a string that reads the same forward and backward.   Example 1: Input: words = ["lc","cl","gg"] Output: 6 Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6. Note that "clgglc" is another longest palindrome that can be created. Example 2: Input: words = ["ab","ty","yt","lc","cl","ab"] Output: 8 Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8. Note that "lcyttycl" is another longest palindrome that can be created. Example 3: Input: words = ["cc","ll","xx"] Output: 2 Explanation: One longest palindrome is "cc", of length 2. Note that "ll" is another longest palindrome that can be created, and so is "xx".   Constraints: 1 <= words.length <= 105 words[i].length == 2 words[i] consists of lowercase English letters.
Medium
[ "array", "hash-table", "string", "greedy", "counting" ]
null
[]
2,132
stamping-the-grid
[ "We can check if every empty cell is a part of a consecutive row of empty cells that has a width of at least stampWidth as well as a consecutive column of empty cells that has a height of at least stampHeight.", "We can prove that this condition is sufficient and necessary to fit the stamps while following the given restrictions and requirements.", "For each row, find every consecutive row of empty cells, and mark all the cells where the consecutive row is at least stampWidth wide. Do the same for the columns with stampHeight. Then, you can check if every cell is marked twice." ]
/** * @param {number[][]} grid * @param {number} stampHeight * @param {number} stampWidth * @return {boolean} */ var possibleToStamp = function(grid, stampHeight, stampWidth) { };
You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied). You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that they follow the given restrictions and requirements: Cover all the empty cells. Do not cover any of the occupied cells. We can put as many stamps as we want. Stamps can overlap with each other. Stamps are not allowed to be rotated. Stamps must stay completely inside the grid. Return true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false.   Example 1: Input: grid = [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0]], stampHeight = 4, stampWidth = 3 Output: true Explanation: We have two overlapping stamps (labeled 1 and 2 in the image) that are able to cover all the empty cells. Example 2: Input: grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], stampHeight = 2, stampWidth = 2 Output: false Explanation: There is no way to fit the stamps onto all the empty cells without the stamps going outside the grid.   Constraints: m == grid.length n == grid[r].length 1 <= m, n <= 105 1 <= m * n <= 2 * 105 grid[r][c] is either 0 or 1. 1 <= stampHeight, stampWidth <= 105
Hard
[ "array", "greedy", "matrix", "prefix-sum" ]
[ "var possibleToStamp = function(grid, stampHeight, stampWidth) {\n let d = [];\n let a = grid;\n let h = grid.length;\n let w = grid[0].length;\n for (let i = 0; i <= h; i++) {\n d[i] = new Array(w + 1).fill(0);\n }\n //d - height of empty cells below\n for (let i = h - 1; i >= 0; i--) {\n for (let j = 0; j < w; j++) {\n if (a[i][j] === 0) d[i][j] = d[i + 1][j] + 1;\n }\n }\n //find stamps, and start to fill matrix\n for (let i = 0; i < h; i++) {\n let columns = 0; //width of consecutive empty columns with height>=stampHeight\n for (let j = 0; j <= w; j++) {\n if (d[i][j] >= stampHeight) { //column can be part of stamp\n columns++;\n if (columns >= stampWidth) {\n //fill first row\n if (columns === stampWidth) {\n //fill previous columns\n for (let l = j - stampWidth + 1; l <= j; l++) {\n a[i][l] = stampHeight\n }\n } else {\n a[i][j] = stampHeight;\n }\n }\n } else {\n columns = 0;\n }\n }\n //fill cells below\n for (let l = 0; l < w; l++) {\n if (a[i][l] > 1) {\n a[i + 1][l] = a[i][l] - 1;\n }\n }\n }\n\n //check if all cells covered\n let ans = true;\n for (let i = 0; i < h; i++) {\n for (let j = 0; j < w; j++) {\n if (a[i][j] === 0) ans = false;\n }\n }\n\n return ans; \n};" ]
2,133
check-if-every-row-and-column-contains-all-numbers
[ "Use for loops to check each row for every number from 1 to n. Similarly, do the same for each column.", "For each check, you can keep a set of the unique elements in the checked row/col. By the end of the check, the size of the set should be n." ]
/** * @param {number[][]} matrix * @return {boolean} */ var checkValid = function(matrix) { };
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.   Example 1: Input: matrix = [[1,2,3],[3,1,2],[2,3,1]] Output: true Explanation: In this case, n = 3, and every row and column contains the numbers 1, 2, and 3. Hence, we return true. Example 2: Input: matrix = [[1,1,1],[1,2,3],[1,2,3]] Output: false Explanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3. Hence, we return false.   Constraints: n == matrix.length == matrix[i].length 1 <= n <= 100 1 <= matrix[i][j] <= n
Easy
[ "array", "hash-table", "matrix" ]
null
[]
2,134
minimum-swaps-to-group-all-1s-together-ii
[ "Notice that the number of 1’s to be grouped together is fixed. It is the number of 1's the whole array has.", "Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1’s.", "The number of swaps required is the number of 0’s in the subarray.", "To eliminate the circular property of the array, we can append the original array to itself. Then, we check each subarray of length total.", "How do we avoid recounting the number of 0’s in the subarray each time? The Sliding Window technique can help." ]
/** * @param {number[]} nums * @return {number} */ var minSwaps = function(nums) { };
A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.   Example 1: Input: nums = [0,1,0,1,1,0,0] Output: 1 Explanation: Here are a few of the ways to group all the 1's together: [0,0,1,1,1,0,0] using 1 swap. [0,1,1,1,0,0,0] using 1 swap. [1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array). There is no way to group all 1's together with 0 swaps. Thus, the minimum number of swaps required is 1. Example 2: Input: nums = [0,1,1,1,0,0,1,1,0] Output: 2 Explanation: Here are a few of the ways to group all the 1's together: [1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array). [1,1,1,1,1,0,0,0,0] using 2 swaps. There is no way to group all 1's together with 0 or 1 swaps. Thus, the minimum number of swaps required is 2. Example 3: Input: nums = [1,1,0,0,1] Output: 0 Explanation: All the 1's are already grouped together due to the circular property of the array. Thus, the minimum number of swaps required is 0.   Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.
Medium
[ "array", "sliding-window" ]
null
[]
2,135
count-words-obtained-after-adding-a-letter
[ "Which data structure can be used to efficiently check if a string exists in startWords?", "After appending a letter, all letters of a string can be rearranged in any possible way. How can we use this to reduce our search space while checking if a string in targetWords can be obtained from a string in startWords?" ]
/** * @param {string[]} startWords * @param {string[]} targetWords * @return {number} */ var wordCount = function(startWords, targetWords) { };
You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only. For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords. The conversion operation is described in the following two steps: Append any lowercase letter that is not present in the string to its end. For example, if the string is "abc", the letters 'd', 'e', or 'y' can be added to it, but not 'a'. If 'd' is added, the resulting string will be "abcd". Rearrange the letters of the new string in any arbitrary order. For example, "abcd" can be rearranged to "acbd", "bacd", "cbda", and so on. Note that it can also be rearranged to "abcd" itself. Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords. Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.   Example 1: Input: startWords = ["ant","act","tack"], targetWords = ["tack","act","acti"] Output: 2 Explanation: - In order to form targetWords[0] = "tack", we use startWords[1] = "act", append 'k' to it, and rearrange "actk" to "tack". - There is no string in startWords that can be used to obtain targetWords[1] = "act". Note that "act" does exist in startWords, but we must append one letter to the string before rearranging it. - In order to form targetWords[2] = "acti", we use startWords[1] = "act", append 'i' to it, and rearrange "acti" to "acti" itself. Example 2: Input: startWords = ["ab","a"], targetWords = ["abc","abcd"] Output: 1 Explanation: - In order to form targetWords[0] = "abc", we use startWords[0] = "ab", add 'c' to it, and rearrange it to "abc". - There is no string in startWords that can be used to obtain targetWords[1] = "abcd".   Constraints: 1 <= startWords.length, targetWords.length <= 5 * 104 1 <= startWords[i].length, targetWords[j].length <= 26 Each string of startWords and targetWords consists of lowercase English letters only. No letter occurs more than once in any string of startWords or targetWords.
Medium
[ "array", "hash-table", "string", "bit-manipulation", "sorting" ]
null
[]
2,136
earliest-possible-day-of-full-bloom
[ "List the planting like the diagram above shows, where a row represents the timeline of a seed. A row i is above another row j if the last day planting seed i is ahead of the last day for seed j. Does it have any advantage to spend some days to plant seed j before completely planting seed i?", "No. It does not help seed j but could potentially delay the completion of seed i, resulting in a worse final answer. Remaining focused is a part of the optimal solution.", "Sort the seeds by their growTime in descending order. Can you prove why this strategy is the other part of the optimal solution? Note the bloom time of a seed is the sum of plantTime of all seeds preceding this seed plus the growTime of this seed.", "There is no way to improve this strategy. The seed to bloom last dominates the final answer. Exchanging the planting of this seed with another seed with either a larger or smaller growTime will result in a potentially worse answer." ]
/** * @param {number[]} plantTime * @param {number[]} growTime * @return {number} */ var earliestFullBloom = function(plantTime, growTime) { };
You have n flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed integer arrays plantTime and growTime, of length n each: plantTime[i] is the number of full days it takes you to plant the ith seed. Every day, you can work on planting exactly one seed. You do not have to work on planting the same seed on consecutive days, but the planting of a seed is not complete until you have worked plantTime[i] days on planting it in total. growTime[i] is the number of full days it takes the ith seed to grow after being completely planted. After the last day of its growth, the flower blooms and stays bloomed forever. From the beginning of day 0, you can plant the seeds in any order. Return the earliest possible day where all seeds are blooming.   Example 1: Input: plantTime = [1,4,3], growTime = [2,3,1] Output: 9 Explanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms. One optimal way is: On day 0, plant the 0th seed. The seed grows for 2 full days and blooms on day 3. On days 1, 2, 3, and 4, plant the 1st seed. The seed grows for 3 full days and blooms on day 8. On days 5, 6, and 7, plant the 2nd seed. The seed grows for 1 full day and blooms on day 9. Thus, on day 9, all the seeds are blooming. Example 2: Input: plantTime = [1,2,3,2], growTime = [2,1,2,1] Output: 9 Explanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms. One optimal way is: On day 1, plant the 0th seed. The seed grows for 2 full days and blooms on day 4. On days 0 and 3, plant the 1st seed. The seed grows for 1 full day and blooms on day 5. On days 2, 4, and 5, plant the 2nd seed. The seed grows for 2 full days and blooms on day 8. On days 6 and 7, plant the 3rd seed. The seed grows for 1 full day and blooms on day 9. Thus, on day 9, all the seeds are blooming. Example 3: Input: plantTime = [1], growTime = [1] Output: 2 Explanation: On day 0, plant the 0th seed. The seed grows for 1 full day and blooms on day 2. Thus, on day 2, all the seeds are blooming.   Constraints: n == plantTime.length == growTime.length 1 <= n <= 105 1 <= plantTime[i], growTime[i] <= 104
Hard
[ "array", "greedy", "sorting" ]
[ "const earliestFullBloom = function(plantTime, growTime) {\n const n = plantTime.length, arr = Array(n)\n for(let i = 0; i < n; i++) {\n arr.push([growTime[i], plantTime[i]])\n }\n arr.sort((a, b) => b[0] - a[0])\n \n let res = 0, cur = 0\n for(let i = 0; i < n; i++) {\n const e = arr[i]\n res = Math.max(res, cur + e[0] + e[1])\n cur += e[1]\n }\n \n return res\n};", "const earliestFullBloom = function(plantTime, growTime) {\n const sum = arr => arr.reduce((ac, e) => ac +e, 0)\n let l = 0, r = sum(plantTime) + sum(growTime)\n const n = plantTime.length\n\n const a = []\n for(let i = 0; i < n; i++) {\n a.push([growTime[i], plantTime[i] ])\n }\n\n a.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])\n a.reverse()\n function chk(d) {\n let total = -1\n let max_num = 0\n for(let i = 0; i < n; i++) {\n total += a[i][1]\n max_num = Math.max(max_num, total + a[i][0] + 1)\n }\n return max_num <= d\n }\n\n while (l < r) {\n let m = ~~((l + r) / 2)\n if (chk(m)) r = m\n else l = m + 1 \n }\n\n return l\n};" ]
2,138
divide-a-string-into-groups-of-size-k
[ "Using the length of the string and k, can you count the number of groups the string can be divided into?", "Try completing each group using characters from the string. If there aren’t enough characters for the last group, use the fill character to complete the group." ]
/** * @param {string} s * @param {number} k * @param {character} fill * @return {string[]} */ var divideString = function(s, k, fill) { };
A string s can be partitioned into groups of size k using the following procedure: The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group. For the last group, if the string does not have k characters remaining, a character fill is used to complete the group. Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s. Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.   Example 1: Input: s = "abcdefghi", k = 3, fill = "x" Output: ["abc","def","ghi"] Explanation: The first 3 characters "abc" form the first group. The next 3 characters "def" form the second group. The last 3 characters "ghi" form the third group. Since all groups can be completely filled by characters from the string, we do not need to use fill. Thus, the groups formed are "abc", "def", and "ghi". Example 2: Input: s = "abcdefghij", k = 3, fill = "x" Output: ["abc","def","ghi","jxx"] Explanation: Similar to the previous example, we are forming the first three groups "abc", "def", and "ghi". For the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice. Thus, the 4 groups formed are "abc", "def", "ghi", and "jxx".   Constraints: 1 <= s.length <= 100 s consists of lowercase English letters only. 1 <= k <= 100 fill is a lowercase English letter.
Easy
[ "string", "simulation" ]
[ "var divideString = function(s, k, fill) {\n let res = [], tmp = ''\n for(let i = 0, n = s.length; i < n; i++) {\n tmp += s[i]\n if(tmp.length === k) {\n res.push(tmp)\n tmp = ''\n }\n }\n if(tmp.length) {\n for(let i = 0, limit = k - tmp.length; i < limit; i++) {\n tmp += fill\n }\n res.push(tmp)\n }\n return res\n};" ]
2,139
minimum-moves-to-reach-target-score
[ "Solve the opposite problem: start at the given score and move to 1.", "It is better to use the move of the second type once we can to lose more scores fast." ]
/** * @param {number} target * @param {number} maxDoubles * @return {number} */ var minMoves = function(target, maxDoubles) { };
You are playing a game with integers. You start with the integer 1 and you want to reach the integer target. In one move, you can either: Increment the current integer by one (i.e., x = x + 1). Double the current integer (i.e., x = 2 * x). You can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times. Given the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1.   Example 1: Input: target = 5, maxDoubles = 0 Output: 4 Explanation: Keep incrementing by 1 until you reach target. Example 2: Input: target = 19, maxDoubles = 2 Output: 7 Explanation: Initially, x = 1 Increment 3 times so x = 4 Double once so x = 8 Increment once so x = 9 Double again so x = 18 Increment once so x = 19 Example 3: Input: target = 10, maxDoubles = 4 Output: 4 Explanation: Initially, x = 1 Increment once so x = 2 Double once so x = 4 Increment once so x = 5 Double again so x = 10   Constraints: 1 <= target <= 109 0 <= maxDoubles <= 100
Medium
[ "math", "greedy" ]
[ "const minMoves = function(target, maxDoubles) {\n let count = 0;\n \n while(target != 1){\n \n if(target % 2 != 0){\n target--;\n count++;\n }\n else{\n if(maxDoubles != 0){\n target /= 2;\n count++;\n maxDoubles--;\n }\n else{\n count += target - 1;\n break;\n }\n }\n }\n return count;\n};" ]
2,140
solving-questions-with-brainpower
[ "For each question, we can either solve it or skip it. How can we use Dynamic Programming to decide the most optimal option for each problem?", "We store for each question the maximum points we can earn if we started the exam on that question.", "If we skip a question, then the answer for it will be the same as the answer for the next question.", "If we solve a question, then the answer for it will be the points of the current question plus the answer for the next solvable question.", "The maximum of these two values will be the answer to the current question." ]
/** * @param {number[][]} questions * @return {number} */ var mostPoints = function(questions) { };
You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri]. The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0) and make a decision whether to solve or skip each question. Solving question i will earn you pointsi points but you will be unable to solve each of the next brainpoweri questions. If you skip question i, you get to make the decision on the next question. For example, given questions = [[3, 2], [4, 3], [4, 4], [2, 5]]: If question 0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2. If instead, question 0 is skipped and question 1 is solved, you will earn 4 points but you will be unable to solve questions 2 and 3. Return the maximum points you can earn for the exam.   Example 1: Input: questions = [[3,2],[4,3],[4,4],[2,5]] Output: 5 Explanation: The maximum points can be earned by solving questions 0 and 3. - Solve question 0: Earn 3 points, will be unable to solve the next 2 questions - Unable to solve questions 1 and 2 - Solve question 3: Earn 2 points Total points earned: 3 + 2 = 5. There is no other way to earn 5 or more points. Example 2: Input: questions = [[1,1],[2,2],[3,3],[4,4],[5,5]] Output: 7 Explanation: The maximum points can be earned by solving questions 1 and 4. - Skip question 0 - Solve question 1: Earn 2 points, will be unable to solve the next 2 questions - Unable to solve questions 2 and 3 - Solve question 4: Earn 5 points Total points earned: 2 + 5 = 7. There is no other way to earn 7 or more points.   Constraints: 1 <= questions.length <= 105 questions[i].length == 2 1 <= pointsi, brainpoweri <= 105
Medium
[ "array", "dynamic-programming" ]
[ "const mostPoints = function(questions) {\n const n = questions.length, dp = Array(n + 1).fill(0)\n for (let i = n - 1; i >= 0; i--) {\n const [gain, p] = questions[i]\n dp[i] = Math.max(dp[i + 1], (dp[p + i + 1] || 0) + gain)\n }\n return dp[0]\n};", "const mostPoints = function (questions) {\n let n = questions.length\n const temp = Array(n).fill(0)\n\n temp[n - 1] = questions[n - 1][0]\n\n for (let i = n - 2; i >= 0; i--) {\n if (i + questions[i][1] + 1 <= n - 1)\n temp[i] = Math.max(\n temp[i + 1],\n questions[i][0] + temp[i + questions[i][1] + 1]\n )\n else temp[i] = Math.max(temp[i + 1], questions[i][0])\n }\n return temp[0]\n}" ]
2,141
maximum-running-time-of-n-computers
[ "For a given running time, can you determine if it is possible to run all n computers simultaneously?", "Try to use Binary Search to find the maximal running time" ]
/** * @param {number} n * @param {number[]} batteries * @return {number} */ var maxRunTime = function(n, batteries) { };
You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously.   Example 1: Input: n = 2, batteries = [3,3,3] Output: 4 Explanation: Initially, insert battery 0 into the first computer and battery 1 into the second computer. After two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute. At the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead. By the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running. We can run the two computers simultaneously for at most 4 minutes, so we return 4. Example 2: Input: n = 2, batteries = [1,1,1,1] Output: 2 Explanation: Initially, insert battery 0 into the first computer and battery 2 into the second computer. After one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. After another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running. We can run the two computers simultaneously for at most 2 minutes, so we return 2.   Constraints: 1 <= n <= batteries.length <= 105 1 <= batteries[i] <= 109
Hard
[ "array", "binary-search", "greedy", "sorting" ]
[ "const maxRunTime = function(n, batteries) {\n n = BigInt(n)\n batteries = batteries.map(e => BigInt(e))\n const sum = batteries.reduce((ac, e) => ac + e, 0n)\n let l = 0n, r = sum / n\n while(l < r) {\n const mid = r - (r - l) / 2n\n if(valid(mid)) l = mid\n else r = mid - 1n\n }\n \n return l\n \n function valid(mid) {\n let curSum = 0n, target = mid * n\n for(const e of batteries) {\n curSum += e > mid ? mid : e\n if(curSum >= target) return true\n }\n return false\n }\n};", "var maxRunTime = function (n, batteries) {\n batteries.sort((a, b) => a - b)\n const sum = batteries.reduce((ac, e) => ac + BigInt(e), 0n)\n let hi = ~~(sum / BigInt(n)) + 1n,\n lo = 0n\n while (lo < hi) {\n let mid = ~~((lo + hi) / 2n)\n if (chk(mid)) {\n lo = mid + 1n\n } else {\n hi = mid\n }\n }\n\n return lo - 1n\n function chk(x) {\n let current = 0n\n let i = 0n\n for (let b of batteries) {\n if (i == BigInt(n)) break\n if (b > x) b = x\n if (b >= x - current) {\n i += 1n\n current = BigInt(b) - (x - current)\n } else {\n current += BigInt(b)\n }\n }\n\n return i == n\n }\n}" ]
2,144
minimum-cost-of-buying-candies-with-discount
[ "If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free?", "How can we generalize this approach to maximize the costs of the candies we get for free?", "Can “sorting” the array help us find the minimum cost?", "If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free?", "How can we generalize this approach to maximize the costs of the candies we get for free?", "Can “sorting” the array help us find the minimum cost?" ]
/** * @param {number[]} cost * @return {number} */ var minimumCost = function(cost) { };
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. For example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys candies with costs 2 and 3, they can take the candy with cost 1 for free, but not the candy with cost 4. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.   Example 1: Input: cost = [1,2,3] Output: 5 Explanation: We buy the candies with costs 2 and 3, and take the candy with cost 1 for free. The total cost of buying all candies is 2 + 3 = 5. This is the only way we can buy the candies. Note that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free. The cost of the free candy has to be less than or equal to the minimum cost of the purchased candies. Example 2: Input: cost = [6,5,7,9,2,2] Output: 23 Explanation: The way in which we can get the minimum cost is described below: - Buy candies with costs 9 and 7 - Take the candy with cost 6 for free - We buy candies with costs 5 and 2 - Take the last remaining candy with cost 2 for free Hence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23. Example 3: Input: cost = [5,5] Output: 10 Explanation: Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free. Hence, the minimum cost to buy all candies is 5 + 5 = 10.   Constraints: 1 <= cost.length <= 100 1 <= cost[i] <= 100
Easy
[ "array", "greedy", "sorting" ]
null
[]
2,145
count-the-hidden-sequences
[ "Fix the first element of the hidden sequence to any value x and ignore the given bounds. Notice that we can then determine all the other elements of the sequence by using the differences array.", "We will also be able to determine the difference between the minimum and maximum elements of the sequence. Notice that the value of x does not affect this.", "We now have the ‘range’ of the sequence (difference between min and max element), we can then calculate how many ways there are to fit this range into the given range of lower to upper.", "Answer is (upper - lower + 1) - (range of sequence)" ]
/** * @param {number[]} differences * @param {number} lower * @param {number} upper * @return {number} */ var numberOfArrays = function(differences, lower, upper) { };
You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i]. You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. For example, given differences = [1, -3, 4], lower = 1, upper = 6, the hidden sequence is a sequence of length 4 whose elements are in between 1 and 6 (inclusive). [3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences. [5, 6, 3, 7] is not possible since it contains an element greater than 6. [1, 2, 3, 4] is not possible since the differences are not correct. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0.   Example 1: Input: differences = [1,-3,4], lower = 1, upper = 6 Output: 2 Explanation: The possible hidden sequences are: - [3, 4, 1, 5] - [4, 5, 2, 6] Thus, we return 2. Example 2: Input: differences = [3,-4,5,1,-2], lower = -4, upper = 5 Output: 4 Explanation: The possible hidden sequences are: - [-3, 0, -4, 1, 2, 0] - [-2, 1, -3, 2, 3, 1] - [-1, 2, -2, 3, 4, 2] - [0, 3, -1, 4, 5, 3] Thus, we return 4. Example 3: Input: differences = [4,-7,2], lower = 3, upper = 6 Output: 0 Explanation: There are no possible hidden sequences. Thus, we return 0.   Constraints: n == differences.length 1 <= n <= 105 -105 <= differences[i] <= 105 -105 <= lower <= upper <= 105
Medium
[ "array", "prefix-sum" ]
null
[]
2,146
k-highest-ranked-items-within-a-price-range
[ "Could you determine the rank of every item efficiently?", "We can perform a breadth-first search from the starting position and know the length of the shortest path from start to every item.", "Sort all the items according to the conditions listed in the problem, and return the first k (or all if less than k exist) items as the answer." ]
/** * @param {number[][]} grid * @param {number[]} pricing * @param {number[]} start * @param {number} k * @return {number[][]} */ var highestRankedKItems = function(grid, pricing, start, k) { };
You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following: 0 represents a wall that you cannot pass through. 1 represents an empty cell that you can freely move to and from. All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells. It takes 1 step to travel between adjacent grid cells. You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] (inclusive). You are further given an integer k. You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: Distance, defined as the length of the shortest path from the start (shorter distance has a higher rank). Price (lower price has a higher rank, but it must be in the price range). The row number (smaller row number has a higher rank). The column number (smaller column number has a higher rank). Return the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k reachable items within the price range, return all of them.   Example 1: Input: grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3 Output: [[0,1],[1,1],[2,1]] Explanation: You start at (0,0). With a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2). The ranks of these items are: - (0,1) with distance 1 - (1,1) with distance 2 - (2,1) with distance 3 - (2,2) with distance 4 Thus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1). Example 2: Input: grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2 Output: [[2,1],[1,2]] Explanation: You start at (2,3). With a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1). The ranks of these items are: - (2,1) with distance 2, price 2 - (1,2) with distance 2, price 3 - (1,1) with distance 3 - (0,1) with distance 4 Thus, the 2 highest ranked items in the price range are (2,1) and (1,2). Example 3: Input: grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3 Output: [[2,1],[2,0]] Explanation: You start at (0,0). With a price range of [2,3], we can take items from (2,0) and (2,1). The ranks of these items are: - (2,1) with distance 5 - (2,0) with distance 6 Thus, the 2 highest ranked items in the price range are (2,1) and (2,0). Note that k = 3 but there are only 2 reachable items within the price range.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 105 1 <= m * n <= 105 0 <= grid[i][j] <= 105 pricing.length == 2 2 <= low <= high <= 105 start.length == 2 0 <= row <= m - 1 0 <= col <= n - 1 grid[row][col] > 0 1 <= k <= m * n
Medium
[ "array", "breadth-first-search", "sorting", "heap-priority-queue", "matrix" ]
null
[]
2,147
number-of-ways-to-divide-a-long-corridor
[ "Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat.", "How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats.", "If there are k plants between two adjacent segments, there are k + 1 positions (ways) you could install the divider you must install.", "The problem now becomes: Find the product of all possible positions between every two adjacent segments." ]
/** * @param {string} corridor * @return {number} */ var numberOfWays = function(corridor) { };
Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7. If there is no way, return 0.   Example 1: Input: corridor = "SSPPSPS" Output: 3 Explanation: There are 3 different ways to divide the corridor. The black bars in the above image indicate the two room dividers already installed. Note that in each of the ways, each section has exactly two seats. Example 2: Input: corridor = "PPSPSP" Output: 1 Explanation: There is only 1 way to divide the corridor, by not installing any additional dividers. Installing any would create some section that does not have exactly two seats. Example 3: Input: corridor = "S" Output: 0 Explanation: There is no way to divide the corridor because there will always be a section that does not have exactly two seats.   Constraints: n == corridor.length 1 <= n <= 105 corridor[i] is either 'S' or 'P'.
Hard
[ "math", "string", "dynamic-programming" ]
null
[]
2,148
count-elements-with-strictly-smaller-and-greater-elements
[ "All the elements in the array should be counted except for the minimum and maximum elements.", "If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums))", "This formula will not work in case the array has all the elements equal, why?" ]
/** * @param {number[]} nums * @return {number} */ var countElements = function(nums) { };
Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.   Example 1: Input: nums = [11,7,2,15] Output: 2 Explanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it. Element 11 has element 7 strictly smaller than it and element 15 strictly greater than it. In total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums. Example 2: Input: nums = [-3,3,3,90] Output: 2 Explanation: The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it. Since there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.   Constraints: 1 <= nums.length <= 100 -105 <= nums[i] <= 105
Easy
[ "array", "sorting" ]
[ "var countElements = function(nums) {\n let min = Infinity, max = -Infinity\n for(let e of nums) {\n if(e > max) max = e\n if(e < min) min = e\n }\n let res = 0\n for(let e of nums) {\n if(e > min && e < max) res++\n }\n return res\n};" ]
2,149
rearrange-array-elements-by-sign
[ "Divide the array into two parts- one comprising of only positive integers and the other of negative integers.", "Merge the two parts to get the resultant array." ]
/** * @param {number[]} nums * @return {number[]} */ var rearrangeArray = function(nums) { };
You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers. You should rearrange the elements of nums such that the modified array follows the given conditions: Every consecutive pair of integers have opposite signs. For all integers with the same sign, the order in which they were present in nums is preserved. The rearranged array begins with a positive integer. Return the modified array after rearranging the elements to satisfy the aforementioned conditions.   Example 1: Input: nums = [3,1,-2,-5,2,-4] Output: [3,-2,1,-5,2,-4] Explanation: The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4]. The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4]. Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions. Example 2: Input: nums = [-1,1] Output: [1,-1] Explanation: 1 is the only positive integer and -1 the only negative integer in nums. So nums is rearranged to [1,-1].   Constraints: 2 <= nums.length <= 2 * 105 nums.length is even 1 <= |nums[i]| <= 105 nums consists of equal number of positive and negative integers.
Medium
[ "array", "two-pointers", "simulation" ]
[ "const rearrangeArray = function(nums) {\n const pos = [], neg = []\n for(let e of nums) {\n if(e >= 0) pos.push(e)\n else neg.push(e)\n }\n const res = []\n for(let i = 0; i < nums.length; i++) {\n if(i % 2 === 0) res.push(pos[~~(i / 2)])\n else res.push(neg[~~(i / 2)])\n }\n return res\n};" ]
2,150
find-all-lonely-numbers-in-the-array
[ "For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array?", "Use a set or a hash map." ]
/** * @param {number[]} nums * @return {number[]} */ var findLonely = function(nums) { };
You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums. You may return the answer in any order.   Example 1: Input: nums = [10,6,5,8] Output: [10,8] Explanation: - 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums. - 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums. - 5 is not a lonely number since 6 appears in nums and vice versa. Hence, the lonely numbers in nums are [10, 8]. Note that [8, 10] may also be returned. Example 2: Input: nums = [1,3,5,3] Output: [1,5] Explanation: - 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums. - 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums. - 3 is not a lonely number since it appears twice. Hence, the lonely numbers in nums are [1, 5]. Note that [5, 1] may also be returned.   Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 106
Medium
[ "array", "hash-table", "counting" ]
[ "var findLonely = function(nums) {\n nums.sort((a, b) => a - b)\n const cnt = {}\n for(let e of nums) {\n if(cnt[e] == null) cnt[e] = 0\n cnt[e]++\n }\n // console.log(cnt)\n const res = []\n for(let i = 0, n = nums.length; i < n; i++) {\n if(i === 0){\n if(nums[i + 1] !== nums[i] + 1 && cnt[nums[i]] === 1) {\n res.push(nums[i]) \n }\n } \n else if(i === n - 1 ) {\n if(nums[i] !== nums[i - 1] + 1 && cnt[nums[i]] === 1) {\n res.push(nums[i])\n }\n }\n else if(cnt[nums[i]] === 1 && nums[i] !== nums[i - 1] + 1 && nums[i] !== nums[i + 1] - 1) {\n res.push(nums[i])\n }\n }\n \n return res\n};" ]
2,151
maximum-good-people-based-on-statements
[ "You should test every possible assignment of good and bad people, using a bitmask.", "In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid.", "If the assignment is valid, count how many people are good and keep track of the maximum." ]
/** * @param {number[][]} statements * @return {number} */ var maximumGood = function(statements) { };
There are two types of persons: The good person: The person who always tells the truth. The bad person: The person who might tell the truth and might lie. You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following: 0 which represents a statement made by person i that person j is a bad person. 1 which represents a statement made by person i that person j is a good person. 2 represents that no statement is made by person i about person j. Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n. Return the maximum number of people who can be good based on the statements made by the n people.   Example 1: Input: statements = [[2,1,2],[1,2,2],[2,0,2]] Output: 2 Explanation: Each person makes a single statement. - Person 0 states that person 1 is good. - Person 1 states that person 0 is good. - Person 2 states that person 1 is bad. Let's take person 2 as the key. - Assuming that person 2 is a good person: - Based on the statement made by person 2, person 1 is a bad person. - Now we know for sure that person 1 is bad and person 2 is good. - Based on the statement made by person 1, and since person 1 is bad, they could be: - telling the truth. There will be a contradiction in this case and this assumption is invalid. - lying. In this case, person 0 is also a bad person and lied in their statement. - Following that person 2 is a good person, there will be only one good person in the group. - Assuming that person 2 is a bad person: - Based on the statement made by person 2, and since person 2 is bad, they could be: - telling the truth. Following this scenario, person 0 and 1 are both bad as explained before. - Following that person 2 is bad but told the truth, there will be no good persons in the group. - lying. In this case person 1 is a good person. - Since person 1 is a good person, person 0 is also a good person. - Following that person 2 is bad and lied, there will be two good persons in the group. We can see that at most 2 persons are good in the best case, so we return 2. Note that there is more than one way to arrive at this conclusion. Example 2: Input: statements = [[2,0],[0,2]] Output: 1 Explanation: Each person makes a single statement. - Person 0 states that person 1 is bad. - Person 1 states that person 0 is bad. Let's take person 0 as the key. - Assuming that person 0 is a good person: - Based on the statement made by person 0, person 1 is a bad person and was lying. - Following that person 0 is a good person, there will be only one good person in the group. - Assuming that person 0 is a bad person: - Based on the statement made by person 0, and since person 0 is bad, they could be: - telling the truth. Following this scenario, person 0 and 1 are both bad. - Following that person 0 is bad but told the truth, there will be no good persons in the group. - lying. In this case person 1 is a good person. - Following that person 0 is bad and lied, there will be only one good person in the group. We can see that at most, one person is good in the best case, so we return 1. Note that there is more than one way to arrive at this conclusion.   Constraints: n == statements.length == statements[i].length 2 <= n <= 15 statements[i][j] is either 0, 1, or 2. statements[i][i] == 2
Hard
[ "array", "backtracking", "bit-manipulation", "enumeration" ]
[ "const maximumGood = function (statements) {\n const n = statements.length\n let res = 0,\n c = (1 << n) - 1\n for (let i = 0; i < c + 1; i++) {\n let s = dec2bin(i)\n s = '0'.repeat(n - s.length) + s\n let arr = [],\n f = 1\n for (let i = 0; i < n; i++) {\n if (s[i] === '1') arr.push(i)\n }\n for (let i of arr) {\n for (let j = 0; j < n; j++) {\n if (statements[i][j] !== 2 && statements[i][j] !== +s[j]) {\n f = 0\n break\n }\n }\n if (!f) break\n }\n if (f) res = Math.max(res, cnt(s, '1'))\n }\n\n return res\n}\nfunction cnt(s, ch) {\n let res = 0\n for (let e of s) {\n if (e === ch) res++\n }\n return res\n}\nfunction dec2bin(dec) {\n return (dec >>> 0).toString(2)\n}" ]
2,154
keep-multiplying-found-values-by-two
[ "Repeatedly iterate through the array and check if the current value of original is in the array.", "If original is not found, stop and return its current value.", "Otherwise, multiply original by 2 and repeat the process.", "Use set data structure to check the existence faster." ]
/** * @param {number[]} nums * @param {number} original * @return {number} */ var findFinalValue = function(nums, original) { };
You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums. You then do the following steps: If original is found in nums, multiply it by two (i.e., set original = 2 * original). Otherwise, stop the process. Repeat this process with the new number as long as you keep finding the number. Return the final value of original.   Example 1: Input: nums = [5,3,6,1,12], original = 3 Output: 24 Explanation: - 3 is found in nums. 3 is multiplied by 2 to obtain 6. - 6 is found in nums. 6 is multiplied by 2 to obtain 12. - 12 is found in nums. 12 is multiplied by 2 to obtain 24. - 24 is not found in nums. Thus, 24 is returned. Example 2: Input: nums = [2,7,9], original = 4 Output: 4 Explanation: - 4 is not found in nums. Thus, 4 is returned.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i], original <= 1000
Easy
[ "array", "hash-table", "sorting", "simulation" ]
[ "var findFinalValue = function(nums, original) {\n let res = original\n while(nums.indexOf(res) !== -1) {\n // const idx = nums.indexOf(res)\n res *= 2\n }\n return res\n};" ]
2,155
all-divisions-with-the-highest-score-of-a-binary-array
[ "When you iterate the array, maintain the number of zeros and ones on the left side. Can you quickly calculate the number of ones on the right side?", "The number of ones on the right side equals the number of ones in the whole array minus the number of ones on the left side.", "Alternatively, you can quickly calculate it by using a prefix sum array." ]
/** * @param {number[]} nums * @return {number[]} */ var maxScoreIndices = function(nums) { };
You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) numsleft and numsright: numsleft has all the elements of nums between index 0 and i - 1 (inclusive), while numsright has all the elements of nums between index i and n - 1 (inclusive). If i == 0, numsleft is empty, while numsright has all the elements of nums. If i == n, numsleft has all the elements of nums, while numsright is empty. The division score of an index i is the sum of the number of 0's in numsleft and the number of 1's in numsright. Return all distinct indices that have the highest possible division score. You may return the answer in any order.   Example 1: Input: nums = [0,0,1,0] Output: [2,4] Explanation: Division at index - 0: numsleft is []. numsright is [0,0,1,0]. The score is 0 + 1 = 1. - 1: numsleft is [0]. numsright is [0,1,0]. The score is 1 + 1 = 2. - 2: numsleft is [0,0]. numsright is [1,0]. The score is 2 + 1 = 3. - 3: numsleft is [0,0,1]. numsright is [0]. The score is 2 + 0 = 2. - 4: numsleft is [0,0,1,0]. numsright is []. The score is 3 + 0 = 3. Indices 2 and 4 both have the highest possible division score 3. Note the answer [4,2] would also be accepted. Example 2: Input: nums = [0,0,0] Output: [3] Explanation: Division at index - 0: numsleft is []. numsright is [0,0,0]. The score is 0 + 0 = 0. - 1: numsleft is [0]. numsright is [0,0]. The score is 1 + 0 = 1. - 2: numsleft is [0,0]. numsright is [0]. The score is 2 + 0 = 2. - 3: numsleft is [0,0,0]. numsright is []. The score is 3 + 0 = 3. Only index 3 has the highest possible division score 3. Example 3: Input: nums = [1,1] Output: [0] Explanation: Division at index - 0: numsleft is []. numsright is [1,1]. The score is 0 + 2 = 2. - 1: numsleft is [1]. numsright is [1]. The score is 0 + 1 = 1. - 2: numsleft is [1,1]. numsright is []. The score is 0 + 0 = 0. Only index 0 has the highest possible division score 2.   Constraints: n == nums.length 1 <= n <= 105 nums[i] is either 0 or 1.
Medium
[ "array" ]
[ "var maxScoreIndices = function(nums) {\n const n = nums.length\n // if(n === 1) return [0]\n const leftZero = Array(n).fill(0), rightOne = Array(n).fill(0)\n for (let i = 0, sum = 0; i < n; i++) {\n if(nums[i] === 0) sum++\n leftZero[i] = sum\n }\n for (let i = n - 1, sum = 0; i >= 0; i--) {\n if(nums[i] === 1) sum++\n rightOne[i] = sum\n }\n let hash = {}\n for (let i = 0, sum = 0; i <= n; i++) {\n \n hash[i] = (i === 0 ? 0 : leftZero[i - 1]) + (i === n ? 0 : rightOne[i])\n }\n const max = Math.max(...Object.values(hash))\n const res = []\n Object.keys(hash).forEach(k => {\n if(hash[k] === max) res.push(+k)\n })\n return res\n};" ]
2,156
find-substring-with-given-hash-value
[ "How can we update the hash value efficiently while iterating instead of recalculating it each time?", "Use the rolling hash method." ]
/** * @param {string} s * @param {number} power * @param {number} modulo * @param {number} k * @param {number} hashValue * @return {string} */ var subStrHash = function(s, power, modulo, k, hashValue) { };
The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function: hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m. Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue. The test cases will be generated such that an answer always exists. A substring is a contiguous non-empty sequence of characters within a string.   Example 1: Input: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0 Output: "ee" Explanation: The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. "ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee". Example 2: Input: s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32 Output: "fbx" Explanation: The hash of "fbx" can be computed to be hash("fbx", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. The hash of "bxz" can be computed to be hash("bxz", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. "fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx". Note that "bxz" also has a hash of 32 but it appears later than "fbx".   Constraints: 1 <= k <= s.length <= 2 * 104 1 <= power, modulo <= 109 0 <= hashValue < modulo s consists of lowercase English letters only. The test cases are generated such that an answer always exists.
Hard
[ "string", "sliding-window", "rolling-hash", "hash-function" ]
[ "var subStrHash = function (s, power, modulo, k, hashValue) {\n let n = s.length;\n const p_pow = Array(n + 1);\n p_pow[0] = 1n;\n power = BigInt(power);\n let m = BigInt(modulo);\n for (let i = 1; i < p_pow.length; i++) p_pow[i] = (p_pow[i - 1] * power) % m;\n\n const val = (ch) => BigInt(ch.charCodeAt(0) - \"a\".charCodeAt(0));\n const h = Array(n + 1).fill(0n);\n for (let i = n - 1; i >= 0; i--)\n h[i] = (h[i + 1] * power + val(s[i]) + 1n) % m;\n\n for (let i = 0; i + k - 1 < n; i++) {\n let cur_h = (h[i] - h[i + k] * p_pow[k]) % m;\n let temp = (cur_h + m) % m;\n if (temp == hashValue) {\n return s.substr(i, k);\n }\n }\n return \"\";\n};" ]
2,157
groups-of-strings
[ "Can we build a graph from words, where there exists an edge between nodes i and j if words[i] and words[j] are connected?", "The problem now boils down to finding the total number of components and the size of the largest component in the graph.", "How can we use bit masking to reduce the search space while adding edges to node i?" ]
/** * @param {string[]} words * @return {number[]} */ var groupStrings = function(words) { };
You are given a 0-indexed array of strings words. Each string consists of lowercase English letters only. No letter occurs more than once in any string of words. Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations: Adding exactly one letter to the set of the letters of s1. Deleting exactly one letter from the set of the letters of s1. Replacing exactly one letter from the set of the letters of s1 with any letter, including itself. The array words can be divided into one or more non-intersecting groups. A string belongs to a group if any one of the following is true: It is connected to at least one other string of the group. It is the only string present in the group. Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. Return an array ans of size 2 where: ans[0] is the maximum number of groups words can be divided into, and ans[1] is the size of the largest group.   Example 1: Input: words = ["a","b","ab","cde"] Output: [2,3] Explanation: - words[0] can be used to obtain words[1] (by replacing 'a' with 'b'), and words[2] (by adding 'b'). So words[0] is connected to words[1] and words[2]. - words[1] can be used to obtain words[0] (by replacing 'b' with 'a'), and words[2] (by adding 'a'). So words[1] is connected to words[0] and words[2]. - words[2] can be used to obtain words[0] (by deleting 'b'), and words[1] (by deleting 'a'). So words[2] is connected to words[0] and words[1]. - words[3] is not connected to any string in words. Thus, words can be divided into 2 groups ["a","b","ab"] and ["cde"]. The size of the largest group is 3. Example 2: Input: words = ["a","ab","abc"] Output: [1,3] Explanation: - words[0] is connected to words[1]. - words[1] is connected to words[0] and words[2]. - words[2] is connected to words[1]. Since all strings are connected to each other, they should be grouped together. Thus, the size of the largest group is 3.   Constraints: 1 <= words.length <= 2 * 104 1 <= words[i].length <= 26 words[i] consists of lowercase English letters only. No letter occurs more than once in words[i].
Hard
[ "string", "bit-manipulation", "union-find" ]
null
[]
2,160
minimum-sum-of-four-digit-number-after-splitting-digits
[ "Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers.", "We can use the two smallest digits out of the four as the digits found in the tens place respectively.", "Similarly, we use the final 2 larger digits as the digits found in the ones place." ]
/** * @param {number} num * @return {number} */ var minimumSum = function(num) { };
You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. For example, given num = 2932, you have the following digits: two 2's, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329]. Return the minimum possible sum of new1 and new2.   Example 1: Input: num = 2932 Output: 52 Explanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc. The minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52. Example 2: Input: num = 4009 Output: 13 Explanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. The minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.   Constraints: 1000 <= num <= 9999
Easy
[ "math", "greedy", "sorting" ]
null
[]
2,161
partition-array-according-to-given-pivot
[ "Could you put the elements smaller than the pivot and greater than the pivot in a separate list as in the sequence that they occur?", "With the separate lists generated, could you then generate the result?" ]
/** * @param {number[]} nums * @param {number} pivot * @return {number[]} */ var pivotArray = function(nums, pivot) { };
You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied: Every element less than pivot appears before every element greater than pivot. Every element equal to pivot appears in between the elements less than and greater than pivot. The relative order of the elements less than pivot and the elements greater than pivot is maintained. More formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i < j and nums[i] < pivot and nums[j] < pivot, then pi < pj. Similarly for elements greater than pivot, if i < j and nums[i] > pivot and nums[j] > pivot, then pi < pj. Return nums after the rearrangement.   Example 1: Input: nums = [9,12,5,10,14,3,10], pivot = 10 Output: [9,5,3,10,10,12,14] Explanation: The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array. The elements 12 and 14 are greater than the pivot so they are on the right side of the array. The relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings. Example 2: Input: nums = [-3,4,3,2], pivot = 2 Output: [-3,2,4,3] Explanation: The element -3 is less than the pivot so it is on the left side of the array. The elements 4 and 3 are greater than the pivot so they are on the right side of the array. The relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.   Constraints: 1 <= nums.length <= 105 -106 <= nums[i] <= 106 pivot equals to an element of nums.
Medium
[ "array", "two-pointers", "simulation" ]
[ "var pivotArray = function(nums, pivot) {\n const less = [], greater = [], mid = []\n for(const e of nums) {\n if(e < pivot) less.push(e)\n else if(e === pivot) mid.push(e)\n else greater.push(e)\n }\n \n return less.concat(mid, greater)\n};" ]
2,162
minimum-cost-to-set-cooking-time
[ "Define a separate function Cost(mm, ss) where 0 <= mm <= 99 and 0 <= ss <= 99. This function should calculate the cost of setting the cocking time to mm minutes and ss seconds", "The range of the minutes is small (i.e., [0, 99]), how can you use that?", "For every mm in [0, 99], calculate the needed ss to make mm:ss equal to targetSeconds and minimize the cost of setting the cocking time to mm:ss", "Be careful in some cases when ss is not in the valid range [0, 99]." ]
/** * @param {number} startAt * @param {number} moveCost * @param {number} pushCost * @param {number} targetSeconds * @return {number} */ var minCostSetTime = function(startAt, moveCost, pushCost, targetSeconds) { };
A generic microwave supports cooking times for: at least 1 second. at most 99 minutes and 99 seconds. To set the cooking time, you push at most four digits. The microwave normalizes what you push as four digits by prepending zeroes. It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example, You push 9 5 4 (three digits). It is normalized as 0954 and interpreted as 9 minutes and 54 seconds. You push 0 0 0 8 (four digits). It is interpreted as 0 minutes and 8 seconds. You push 8 0 9 0. It is interpreted as 80 minutes and 90 seconds. You push 8 1 3 0. It is interpreted as 81 minutes and 30 seconds. You are given integers startAt, moveCost, pushCost, and targetSeconds. Initially, your finger is on the digit startAt. Moving the finger above any specific digit costs moveCost units of fatigue. Pushing the digit below the finger once costs pushCost units of fatigue. There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost. Return the minimum cost to set targetSeconds seconds of cooking time. Remember that one minute consists of 60 seconds.   Example 1: Input: startAt = 1, moveCost = 2, pushCost = 1, targetSeconds = 600 Output: 6 Explanation: The following are the possible ways to set the cooking time. - 1 0 0 0, interpreted as 10 minutes and 0 seconds.   The finger is already on digit 1, pushes 1 (with cost 1), moves to 0 (with cost 2), pushes 0 (with cost 1), pushes 0 (with cost 1), and pushes 0 (with cost 1).   The cost is: 1 + 2 + 1 + 1 + 1 = 6. This is the minimum cost. - 0 9 6 0, interpreted as 9 minutes and 60 seconds. That is also 600 seconds.   The finger moves to 0 (with cost 2), pushes 0 (with cost 1), moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).   The cost is: 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 = 12. - 9 6 0, normalized as 0960 and interpreted as 9 minutes and 60 seconds.   The finger moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).   The cost is: 2 + 1 + 2 + 1 + 2 + 1 = 9. Example 2: Input: startAt = 0, moveCost = 1, pushCost = 2, targetSeconds = 76 Output: 6 Explanation: The optimal way is to push two digits: 7 6, interpreted as 76 seconds. The finger moves to 7 (with cost 1), pushes 7 (with cost 2), moves to 6 (with cost 1), and pushes 6 (with cost 2). The total cost is: 1 + 2 + 1 + 2 = 6 Note other possible ways are 0076, 076, 0116, and 116, but none of them produces the minimum cost.   Constraints: 0 <= startAt <= 9 1 <= moveCost, pushCost <= 105 1 <= targetSeconds <= 6039
Medium
[ "math", "enumeration" ]
null
[]
2,163
minimum-difference-in-sums-after-removal-of-elements
[ "The lowest possible difference can be obtained when the sum of the first n elements in the resultant array is minimum, and the sum of the next n elements is maximum.", "For every index i, think about how you can find the minimum possible sum of n elements with indices lesser or equal to i, if possible.", "Similarly, for every index i, try to find the maximum possible sum of n elements with indices greater or equal to i, if possible.", "Now for all indices, check if we can consider it as the partitioning index and hence find the answer." ]
/** * @param {number[]} nums * @return {number} */ var minimumDifference = function(nums) { };
You are given a 0-indexed integer array nums consisting of 3 * n elements. You are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts: The first n elements belonging to the first part and their sum is sumfirst. The next n elements belonging to the second part and their sum is sumsecond. The difference in sums of the two parts is denoted as sumfirst - sumsecond. For example, if sumfirst = 3 and sumsecond = 2, their difference is 1. Similarly, if sumfirst = 2 and sumsecond = 3, their difference is -1. Return the minimum difference possible between the sums of the two parts after the removal of n elements.   Example 1: Input: nums = [3,1,2] Output: -1 Explanation: Here, nums has 3 elements, so n = 1. Thus we have to remove 1 element from nums and divide the array into two equal parts. - If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1. - If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1. - If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2. The minimum difference between sums of the two parts is min(-1,1,2) = -1. Example 2: Input: nums = [7,9,5,8,1,3] Output: 1 Explanation: Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each. If we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12. To obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1. It can be shown that it is not possible to obtain a difference smaller than 1.   Constraints: nums.length == 3 * n 1 <= n <= 105 1 <= nums[i] <= 105
Hard
[ "array", "dynamic-programming", "heap-priority-queue" ]
[ "const minimumDifference = function(nums) {\n const n = nums.length, len = n / 3\n const maxCompare = (p, c) => { return p === c ? 0 : (p > c ? -1 : 1)}\n const minCompare = (p, c) => { return p === c ? 0 : (p < c ? -1 : 1)}\n const maxHeap = new PriorityQueue({compare: maxCompare})\n const minHeap = new PriorityQueue({compare: minCompare})\n const pre = Array(n).fill(Infinity), suffix = Array(n).fill(-Infinity)\n for(let i = 0, sum = 0; i < 2 * len; i++) {\n const cur = nums[i]\n maxHeap.enqueue(cur)\n sum += cur\n if(maxHeap.size() > len) {\n const tmp = maxHeap.dequeue()\n sum -= tmp\n }\n if(maxHeap.size() === len) {\n pre[i] = sum \n }\n }\n\n for(let i = n - 1, sum = 0; i >= len; i--) {\n const cur = nums[i]\n minHeap.enqueue(cur)\n sum += cur\n if(minHeap.size() > len) {\n const tmp = minHeap.dequeue()\n sum -= tmp\n }\n if(minHeap.size() === len) {\n suffix[i] = sum\n }\n }\n\n // console.log(pre, suffix)\n let res = Infinity\n for(let i = len - 1; i < n - len; i++) {\n res = Math.min(res, pre[i] - suffix[i + 1])\n }\n return res\n};", "const minimumDifference = function(nums) {\n const n = nums.length, len = n / 3\n const maxHeap = new PriorityQueue((a, b) => a > b)\n const minHeap = new PriorityQueue((a, b) => a < b)\n const pre = Array(n).fill(Infinity), suffix = Array(n).fill(-Infinity)\n for(let i = 0, sum = 0; i < 2 * len; i++) {\n const cur = nums[i]\n maxHeap.push(cur)\n sum += cur\n if(maxHeap.size() > len) {\n const tmp = maxHeap.pop()\n sum -= tmp\n }\n if(maxHeap.size() === len) {\n pre[i] = sum\n }\n }\n\n for(let i = n - 1, sum = 0; i >= len; i--) {\n const cur = nums[i]\n minHeap.push(cur)\n sum += cur\n if(minHeap.size() > len) {\n const tmp = minHeap.pop()\n sum -= tmp\n }\n if(minHeap.size() === len) {\n suffix[i] = sum\n }\n }\n\n // console.log(pre, suffix)\n let res = Infinity\n for(let i = len - 1; i < n - len; i++) {\n res = Math.min(res, pre[i] - suffix[i + 1])\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,164
sort-even-and-odd-indices-independently
[ "Try to separate the elements at odd indices from the elements at even indices.", "Sort the two groups of elements individually.", "Combine them to form the resultant array." ]
/** * @param {number[]} nums * @return {number[]} */ var sortEvenOdd = function(nums) { };
You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules: Sort the values at odd indices of nums in non-increasing order. For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values at odd indices 1 and 3 are sorted in non-increasing order. Sort the values at even indices of nums in non-decreasing order. For example, if nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after. The values at even indices 0 and 2 are sorted in non-decreasing order. Return the array formed after rearranging the values of nums.   Example 1: Input: nums = [4,1,2,3] Output: [2,3,4,1] Explanation: First, we sort the values present at odd indices (1 and 3) in non-increasing order. So, nums changes from [4,1,2,3] to [4,3,2,1]. Next, we sort the values present at even indices (0 and 2) in non-decreasing order. So, nums changes from [4,1,2,3] to [2,3,4,1]. Thus, the array formed after rearranging the values is [2,3,4,1]. Example 2: Input: nums = [2,1] Output: [2,1] Explanation: Since there is exactly one odd index and one even index, no rearrangement of values takes place. The resultant array formed is [2,1], which is the same as the initial array.   Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100
Easy
[ "array", "sorting" ]
[ "var sortEvenOdd = function(nums) {\n let nums_size = nums.length;\n for (let i = 0; i < nums_size - 2; i++) {\n for (let j = i + 2; j < nums_size; j += 2) {\n if (i % 2 == 1) {\n if (nums[i] < nums[j]) {\n let temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n } else {\n if (nums[i] > nums[j]) {\n let temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n }\n }\n }\n return nums; \n};" ]
2,165
smallest-value-of-the-rearranged-number
[ "For positive numbers, the leading digit should be the smallest nonzero digit. Then the remaining digits follow in ascending order.", "For negative numbers, the digits should be arranged in descending order." ]
/** * @param {number} num * @return {number} */ var smallestNumber = function(num) { };
You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value. Note that the sign of the number does not change after rearranging the digits.   Example 1: Input: num = 310 Output: 103 Explanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. The arrangement with the smallest value that does not contain any leading zeros is 103. Example 2: Input: num = -7605 Output: -7650 Explanation: Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567. The arrangement with the smallest value that does not contain any leading zeros is -7650.   Constraints: -1015 <= num <= 1015
Medium
[ "math", "sorting" ]
[ "var smallestNumber = function(num) {\n const minus = num < 0\n const nums = Math.abs(num)\n .toString()\n .split('')\n .map(_ => parseInt(_))\n .sort((a, b) => minus ? b-a : a-b);\n if(!minus && nums[0] === 0) {\n let i = 0\n while(nums[i] === 0 && i < nums.length-1) i++\n nums[0] = nums[i]\n nums[i] = 0\n }\n const answer = parseInt(nums.map(_ => _.toString()).join(''))\n return minus ? -answer : answer\n};" ]
2,166
design-bitset
[ "Note that flipping a bit twice does nothing.", "In order to determine the value of a bit, consider how you can efficiently count the number of flips made on the bit since its latest update." ]
/** * @param {number} size */ var Bitset = function(size) { }; /** * @param {number} idx * @return {void} */ Bitset.prototype.fix = function(idx) { }; /** * @param {number} idx * @return {void} */ Bitset.prototype.unfix = function(idx) { }; /** * @return {void} */ Bitset.prototype.flip = function() { }; /** * @return {boolean} */ Bitset.prototype.all = function() { }; /** * @return {boolean} */ Bitset.prototype.one = function() { }; /** * @return {number} */ Bitset.prototype.count = function() { }; /** * @return {string} */ Bitset.prototype.toString = function() { }; /** * Your Bitset object will be instantiated and called as such: * var obj = new Bitset(size) * obj.fix(idx) * obj.unfix(idx) * obj.flip() * var param_4 = obj.all() * var param_5 = obj.one() * var param_6 = obj.count() * var param_7 = obj.toString() */
A Bitset is a data structure that compactly stores bits. Implement the Bitset class: Bitset(int size) Initializes the Bitset with size bits, all of which are 0. void fix(int idx) Updates the value of the bit at the index idx to 1. If the value was already 1, no change occurs. void unfix(int idx) Updates the value of the bit at the index idx to 0. If the value was already 0, no change occurs. void flip() Flips the values of each bit in the Bitset. In other words, all bits with value 0 will now have value 1 and vice versa. boolean all() Checks if the value of each bit in the Bitset is 1. Returns true if it satisfies the condition, false otherwise. boolean one() Checks if there is at least one bit in the Bitset with value 1. Returns true if it satisfies the condition, false otherwise. int count() Returns the total number of bits in the Bitset which have value 1. String toString() Returns the current composition of the Bitset. Note that in the resultant string, the character at the ith index should coincide with the value at the ith bit of the Bitset.   Example 1: Input ["Bitset", "fix", "fix", "flip", "all", "unfix", "flip", "one", "unfix", "count", "toString"] [[5], [3], [1], [], [], [0], [], [], [0], [], []] Output [null, null, null, null, false, null, null, true, null, 2, "01010"] Explanation Bitset bs = new Bitset(5); // bitset = "00000". bs.fix(3); // the value at idx = 3 is updated to 1, so bitset = "00010". bs.fix(1); // the value at idx = 1 is updated to 1, so bitset = "01010". bs.flip(); // the value of each bit is flipped, so bitset = "10101". bs.all(); // return False, as not all values of the bitset are 1. bs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "00101". bs.flip(); // the value of each bit is flipped, so bitset = "11010". bs.one(); // return True, as there is at least 1 index with value 1. bs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "01010". bs.count(); // return 2, as there are 2 bits with value 1. bs.toString(); // return "01010", which is the composition of bitset.   Constraints: 1 <= size <= 105 0 <= idx <= size - 1 At most 105 calls will be made in total to fix, unfix, flip, all, one, count, and toString. At least one call will be made to all, one, count, or toString. At most 5 calls will be made to toString.
Medium
[ "array", "hash-table", "design" ]
[ "const Bitset = function (size) {\n this.arr = Array.from({ length: 2 }, (el, idx) =>\n Array(size).fill(idx === 0 ? 0 : 1)\n )\n this.cur = 0\n this.cnt = 0\n}\n\n\nBitset.prototype.fix = function (idx) {\n if(this.arr[this.cur][idx] === 1) return\n this.arr[this.cur][idx] = 1\n this.arr[this.cur ^ 1][idx] = 0\n this.cnt++\n}\n\n\nBitset.prototype.unfix = function (idx) {\n if(this.arr[this.cur][idx] === 0) return\n this.arr[this.cur][idx] = 0\n this.arr[this.cur ^ 1][idx] = 1\n this.cnt--\n}\n\n\nBitset.prototype.flip = function () {\n this.cur ^= 1\n this.cnt = this.arr[this.cur].length - this.cnt\n}\n\n\nBitset.prototype.all = function () {\n return this.cnt === this.arr[this.cur].length\n}\n\n\nBitset.prototype.one = function () {\n return this.cnt > 0\n}\n\n\nBitset.prototype.count = function () {\n return this.cnt\n}\n\n\nBitset.prototype.toString = function () {\n return this.arr[this.cur].join('')\n}", "var Bitset = function(size) {\n this.s = Array.from({ length:2 }, () => Array())\n this.cnt = 0\n this.now = 0\n for (let i = 0; i < size; i++) {\n this.s[this.now].push( '0');\n this.s[this.now ^ 1].push( '1');\n }\n};\n\n\nBitset.prototype.fix = function(idx) {\n if (this.s[this.now][idx] == '1') return;\n // swap(this.s[this.now][idx], this.s[this.now ^ 1][idx]);\n const tmp = this.s[this.now][idx]\n this.s[this.now][idx] = this.s[this.now ^ 1][idx]\n this.s[this.now ^ 1][idx] = tmp\n this.cnt++;\n};\n\n\nBitset.prototype.unfix = function(idx) {\n if (this.s[this.now][idx] == '0') return;\n // swap(this.s[this.now][idx], this.s[this.now ^ 1][idx]);\n const tmp = this.s[this.now][idx]\n this.s[this.now][idx] = this.s[this.now ^ 1][idx]\n this.s[this.now ^ 1][idx] = tmp\n this.cnt--;\n};\n\n\nBitset.prototype.flip = function() {\n this.now = this.now ^ 1;\n this.cnt = this.s[0].length - this.cnt;\n};\n\n\nBitset.prototype.all = function() {\n return this.cnt == this.s[0].length;\n};\n\n\nBitset.prototype.one = function() {\n return this.cnt !== 0\n};\n\n\nBitset.prototype.count = function() {\n return this.cnt;\n};\n\n\nBitset.prototype.toString = function() {\n return this.s[this.now].join('');\n};" ]
2,167
minimum-time-to-remove-all-cars-containing-illegal-goods
[ "Build an array withoutFirst where withoutFirst[i] stores the minimum time to remove all the cars containing illegal goods from the ‘suffix’ of the sequence starting from the ith car without using any type 1 operations.", "Next, build an array onlyFirst where onlyFirst[i] stores the minimum time to remove all the cars containing illegal goods from the ‘prefix’ of the sequence ending on the ith car using only type 1 operations.", "Finally, we can compare the best way to split the operations amongst these two types by finding the minimum time across all onlyFirst[i] + withoutFirst[i + 1]." ]
/** * @param {string} s * @return {number} */ var minimumTime = function(s) { };
You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times: Remove a train car from the left end (i.e., remove s[0]) which takes 1 unit of time. Remove a train car from the right end (i.e., remove s[s.length - 1]) which takes 1 unit of time. Remove a train car from anywhere in the sequence which takes 2 units of time. Return the minimum time to remove all the cars containing illegal goods. Note that an empty sequence of cars is considered to have no cars containing illegal goods.   Example 1: Input: s = "1100101" Output: 5 Explanation: One way to remove all the cars containing illegal goods from the sequence is to - remove a car from the left end 2 times. Time taken is 2 * 1 = 2. - remove a car from the right end. Time taken is 1. - remove the car containing illegal goods found in the middle. Time taken is 2. This obtains a total time of 2 + 1 + 2 = 5. An alternative way is to - remove a car from the left end 2 times. Time taken is 2 * 1 = 2. - remove a car from the right end 3 times. Time taken is 3 * 1 = 3. This also obtains a total time of 2 + 3 = 5. 5 is the minimum time taken to remove all the cars containing illegal goods. There are no other ways to remove them with less time. Example 2: Input: s = "0010" Output: 2 Explanation: One way to remove all the cars containing illegal goods from the sequence is to - remove a car from the left end 3 times. Time taken is 3 * 1 = 3. This obtains a total time of 3. Another way to remove all the cars containing illegal goods from the sequence is to - remove the car containing illegal goods found in the middle. Time taken is 2. This obtains a total time of 2. Another way to remove all the cars containing illegal goods from the sequence is to - remove a car from the right end 2 times. Time taken is 2 * 1 = 2. This obtains a total time of 2. 2 is the minimum time taken to remove all the cars containing illegal goods. There are no other ways to remove them with less time.   Constraints: 1 <= s.length <= 2 * 105 s[i] is either '0' or '1'.
Hard
[ "string", "dynamic-programming" ]
[ "const minimumTime = function(s) {\n const n = s.length\n const arr = []\n for(let ch of s) {\n arr.push(ch === '1' ? 1 : -1)\n }\n const score = minSum(arr)\n return n + score\n\n function minSum(ar) {\n const dp = Array(n).fill(Infinity)\n dp[0] = ar[0]\n let ans = dp[0]\n for(let i = 1; i < n; i++) {\n dp[i] = Math.min(ar[i], ar[i] + dp[i - 1])\n ans = Math.min(ans, dp[i])\n }\n return ans > 0 ? 0 : ans\n }\n};", "const minimumTime = function(s) {\n const n = s.length\n const arr = []\n for(let ch of s) {\n arr.push(ch === '1' ? 1 : -1)\n }\n const score = minSum(arr)\n return n + score\n\n function minSum(ar) {\n const dp = Array(n).fill(0)\n dp[0] = ar[0]\n for(let i = 1; i < n; i++) {\n dp[i] = Math.min(ar[i], ar[i] + dp[i - 1])\n }\n return Math.min(0, Math.min(...dp))\n }\n};", "const minimumTime = function(s) {\n if(s.length === 1) return s === '1' ? 1 : 0\n const n = s.length\n const arr = []\n for(let ch of s) {\n arr.push(ch === '1' ? 1 : -1)\n }\n const score = minSum(arr)\n return n + score\n\n function minSum(ar) {\n const dp = Array(n).fill(0)\n dp[0] = ar[0]\n let ans = dp[0]\n for(let i = 1; i < n; i++) {\n dp[i] = Math.min(ar[i], ar[i] + dp[i - 1])\n ans = Math.min(0, ans, dp[i])\n }\n return ans\n }\n};", "var minimumTime = function(s) {\n\n const { max, min } = Math\n \n let n = s.length;\n const l = Array.from({ length: n + 1 }, () => Array(2).fill(0))\n const r = Array.from({ length: n + 1 }, () => Array(2).fill(0))\n for (let i = 0; i < n; i++) l[i][0] = l[i][1] = r[i][0] = r[i][1] = 0;\n if (s[0] == '1') {\n l[0][0] = 1;\n l[0][1] = 2;\n }\n for (let i = 1; i < n; i++) {\n if (s[i] == '0') {\n l[i][0] = l[i - 1][0];\n l[i][1] = l[i - 1][1];\n } else {\n l[i][0] = i + 1;\n l[i][1] = min(l[i - 1][0], l[i - 1][1]) + 2;\n }\n }\n if (s[n - 1] == '1') {\n r[n - 1][0] = 1;\n r[n - 1][1] = 2;\n }\n for (let i = n - 2; i >= 0; i--) {\n if (s[i] == '0') {\n r[i][0] = r[i + 1][0];\n r[i][1] = r[i + 1][1];\n } else {\n r[i][0] = n - i;\n r[i][1] = min(r[i + 1][0], r[i + 1][1]) + 2;\n }\n }\n let ans = n;\n for (let i = -1; i < n; i++) {\n let cost = 0;\n if (i != -1) cost += min(l[i][0], l[i][1]);\n if (i != n - 1) cost += min(r[i + 1][0], r[i + 1][1]);\n ans = min(ans, cost);\n }\n return ans;\n};" ]
2,169
count-operations-to-obtain-zero
[ "Try simulating the process until either of the two integers is zero.", "Count the number of operations done." ]
/** * @param {number} num1 * @param {number} num2 * @return {number} */ var countOperations = function(num1, num2) { };
You are given two non-negative integers num1 and num2. In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2. For example, if num1 = 5 and num2 = 4, subtract num2 from num1, thus obtaining num1 = 1 and num2 = 4. However, if num1 = 4 and num2 = 5, after one operation, num1 = 4 and num2 = 1. Return the number of operations required to make either num1 = 0 or num2 = 0.   Example 1: Input: num1 = 2, num2 = 3 Output: 3 Explanation: - Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1. - Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1. - Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1. Now num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations. So the total number of operations required is 3. Example 2: Input: num1 = 10, num2 = 10 Output: 1 Explanation: - Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0. Now num1 = 0 and num2 = 10. Since num1 == 0, we are done. So the total number of operations required is 1.   Constraints: 0 <= num1, num2 <= 105
Easy
[ "math", "simulation" ]
[ "var countOperations = function(num1, num2) {\n let res = 0\n while(num1 !== 0 && num2 !== 0) {\n if(num1 >= num2) num1 -= num2\n else num2 -= num1\n res++\n }\n return res\n};" ]
2,170
minimum-operations-to-make-the-array-alternating
[ "Count the frequency of each element in odd positions in the array. Do the same for elements in even positions.", "To minimize the number of operations we need to maximize the number of elements we keep from the original array.", "What are the possible combinations of elements we can choose from odd indices and even indices so that the number of unchanged elements is maximized?" ]
/** * @param {number[]} nums * @return {number} */ var minimumOperations = function(nums) { };
You are given a 0-indexed array nums consisting of n positive integers. The array nums is called alternating if: nums[i - 2] == nums[i], where 2 <= i <= n - 1. nums[i - 1] != nums[i], where 1 <= i <= n - 1. In one operation, you can choose an index i and change nums[i] into any positive integer. Return the minimum number of operations required to make the array alternating.   Example 1: Input: nums = [3,1,3,2,4,3] Output: 3 Explanation: One way to make the array alternating is by converting it to [3,1,3,1,3,1]. The number of operations required in this case is 3. It can be proven that it is not possible to make the array alternating in less than 3 operations. Example 2: Input: nums = [1,2,2,2,2] Output: 2 Explanation: One way to make the array alternating is by converting it to [1,2,1,2,1]. The number of operations required in this case is 2. Note that the array cannot be converted to [2,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105
Medium
[ "array", "hash-table", "greedy", "counting" ]
null
[]
2,171
removing-minimum-number-of-magic-beans
[ "Notice that if we choose to make x bags of beans empty, we should choose the x bags with the least amount of beans.", "Notice that if the minimum number of beans in a non-empty bag is m, then the best way to make all bags have an equal amount of beans is to reduce all the bags to have m beans.", "Can we iterate over how many bags we should remove and choose the one that minimizes the total amount of beans to remove?", "Sort the bags of beans first." ]
/** * @param {number[]} beans * @return {number} */ var minimumRemoval = function(beans) { };
You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags. Return the minimum number of magic beans that you have to remove.   Example 1: Input: beans = [4,1,6,5] Output: 4 Explanation: - We remove 1 bean from the bag with only 1 bean. This results in the remaining bags: [4,0,6,5] - Then we remove 2 beans from the bag with 6 beans. This results in the remaining bags: [4,0,4,5] - Then we remove 1 bean from the bag with 5 beans. This results in the remaining bags: [4,0,4,4] We removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans. There are no other solutions that remove 4 beans or fewer. Example 2: Input: beans = [2,10,3,2] Output: 7 Explanation: - We remove 2 beans from one of the bags with 2 beans. This results in the remaining bags: [0,10,3,2] - Then we remove 2 beans from the other bag with 2 beans. This results in the remaining bags: [0,10,3,0] - Then we remove 3 beans from the bag with 3 beans. This results in the remaining bags: [0,10,0,0] We removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans. There are no other solutions that removes 7 beans or fewer.   Constraints: 1 <= beans.length <= 105 1 <= beans[i] <= 105
Medium
[ "array", "sorting", "prefix-sum" ]
null
[]
2,172
maximum-and-sum-of-array
[ "Can you think of a dynamic programming solution to this problem?", "Can you use a bitmask to represent the state of the slots?" ]
/** * @param {number[]} nums * @param {number} numSlots * @return {number} */ var maximumANDSum = function(nums, numSlots) { };
You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots. You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. For example, the AND sum of placing the numbers [1, 3] into slot 1 and [4, 6] into slot 2 is equal to (1 AND 1) + (3 AND 1) + (4 AND 2) + (6 AND 2) = 1 + 1 + 0 + 2 = 4. Return the maximum possible AND sum of nums given numSlots slots.   Example 1: Input: nums = [1,2,3,4,5,6], numSlots = 3 Output: 9 Explanation: One possible placement is [1, 4] into slot 1, [2, 6] into slot 2, and [3, 5] into slot 3. This gives the maximum AND sum of (1 AND 1) + (4 AND 1) + (2 AND 2) + (6 AND 2) + (3 AND 3) + (5 AND 3) = 1 + 0 + 2 + 2 + 3 + 1 = 9. Example 2: Input: nums = [1,3,10,4,7,1], numSlots = 9 Output: 24 Explanation: One possible placement is [1, 1] into slot 1, [3] into slot 3, [4] into slot 4, [7] into slot 7, and [10] into slot 9. This gives the maximum AND sum of (1 AND 1) + (1 AND 1) + (3 AND 3) + (4 AND 4) + (7 AND 7) + (10 AND 9) = 1 + 1 + 3 + 4 + 7 + 8 = 24. Note that slots 2, 5, 6, and 8 are empty which is permitted.   Constraints: n == nums.length 1 <= numSlots <= 9 1 <= n <= 2 * numSlots 1 <= nums[i] <= 15
Hard
[ "array", "dynamic-programming", "bit-manipulation", "bitmask" ]
[ "const maximumANDSum = function (nums, numSlots) {\n const n = nums.length\n nums.unshift(0)\n const m = Math.pow(3, numSlots)\n\n const dp = Array.from({ length: n + 1 }, () => Array(m).fill(-Infinity))\n dp[0][0] = 0\n\n let ret = 0\n\n for (let state = 1; state < m; state++) {\n let i = 0\n let temp = state\n while (temp > 0) {\n i += temp % 3\n temp = Math.floor(temp / 3)\n }\n if (i > n) continue\n\n for (let j = 0; j < numSlots; j++) {\n if (filled(state, j) >= 1) {\n dp[i][state] = Math.max(\n dp[i][state],\n dp[i - 1][state - Math.pow(3, j)] + (nums[i] & (j + 1))\n )\n }\n }\n if (i === n) ret = Math.max(ret, dp[i][state])\n }\n\n return ret\n}\n\nfunction filled(state, k) {\n for (let i = 0; i < k; i++) state = Math.floor(state / 3)\n return state % 3\n}" ]
2,176
count-equal-and-divisible-pairs-in-an-array
[ "For every possible pair of indices (i, j) where i < j, check if it satisfies the given conditions." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var countPairs = function(nums, k) { };
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) where 0 <= i < j < n, such that nums[i] == nums[j] and (i * j) is divisible by k.   Example 1: Input: nums = [3,1,2,2,2,1,3], k = 2 Output: 4 Explanation: There are 4 pairs that meet all the requirements: - nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2. - nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2. - nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2. - nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2. Example 2: Input: nums = [1,2,3,4], k = 1 Output: 0 Explanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.   Constraints: 1 <= nums.length <= 100 1 <= nums[i], k <= 100
Easy
[ "array" ]
null
[]
2,177
find-three-consecutive-integers-that-sum-to-a-given-number
[ "Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number?", "Notice the sum of the numbers will be 3x. Can you solve for x?" ]
/** * @param {number} num * @return {number[]} */ var sumOfThree = function(num) { };
Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array.   Example 1: Input: num = 33 Output: [10,11,12] Explanation: 33 can be expressed as 10 + 11 + 12 = 33. 10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12]. Example 2: Input: num = 4 Output: [] Explanation: There is no way to express 4 as the sum of 3 consecutive integers.   Constraints: 0 <= num <= 1015
Medium
[ "math", "simulation" ]
null
[]
2,178
maximum-split-of-positive-even-integers
[ "First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers.", "Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible.", "Thus, we find the maximum sum of the first k - 1 even elements which is less than finalSum.", "We then add the difference over to the kth element." ]
/** * @param {number} finalSum * @return {number[]} */ var maximumEvenSplit = function(finalSum) { };
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. For example, given finalSum = 12, the following splits are valid (unique positive even integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split into (2 + 2 + 4 + 4) as all the numbers should be unique. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.   Example 1: Input: finalSum = 12 Output: [2,4,6] Explanation: The following are valid splits: (12), (2 + 10), (2 + 4 + 6), and (4 + 8). (2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6]. Note that [2,6,4], [6,2,4], etc. are also accepted. Example 2: Input: finalSum = 7 Output: [] Explanation: There are no valid splits for the given finalSum. Thus, we return an empty array. Example 3: Input: finalSum = 28 Output: [6,8,2,12] Explanation: The following are valid splits: (2 + 26), (6 + 8 + 2 + 12), and (4 + 24). (6 + 8 + 2 + 12) has the maximum number of integers, which is 4. Thus, we return [6,8,2,12]. Note that [10,2,4,12], [6,2,4,16], etc. are also accepted.   Constraints: 1 <= finalSum <= 1010
Medium
[ "math", "backtracking", "greedy" ]
[ "const maximumEvenSplit = function(finalSum) {\n if(finalSum % 2 === 1) return []\n const res = []\n let i = 2\n while(i <= finalSum) {\n res.push(i)\n finalSum -= i\n i += 2\n }\n \n const last = res.pop()\n res.push(finalSum + last)\n return res\n};" ]
2,179
count-good-triplets-in-an-array
[ "For every value y, how can you find the number of values x (0 ≤ x, y ≤ n - 1) such that x appears before y in both of the arrays?", "Similarly, for every value y, try finding the number of values z (0 ≤ y, z ≤ n - 1) such that z appears after y in both of the arrays.", "Now, for every value y, count the number of good triplets that can be formed if y is considered as the middle element." ]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var goodTriplets = function(nums1, nums2) { };
You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. Return the total number of good triplets.   Example 1: Input: nums1 = [2,0,1,3], nums2 = [0,1,2,3] Output: 1 Explanation: There are 4 triplets (x,y,z) such that pos1x < pos1y < pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). Out of those triplets, only the triplet (0,1,3) satisfies pos2x < pos2y < pos2z. Hence, there is only 1 good triplet. Example 2: Input: nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3] Output: 4 Explanation: The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).   Constraints: n == nums1.length == nums2.length 3 <= n <= 105 0 <= nums1[i], nums2[i] <= n - 1 nums1 and nums2 are permutations of [0, 1, ..., n - 1].
Hard
[ "array", "binary-search", "divide-and-conquer", "binary-indexed-tree", "segment-tree", "merge-sort", "ordered-set" ]
[ "const goodTriplets = function(a, b) {\n let n = a.length, m = new Map(), res = 0;\n for (let i = 0; i < n; i++) m.set(b[i], i);\n let fen = new Fenwick(n + 3);\n for (let i = 0; i < n; i++) {\n let pos = m.get(a[i]);\n let l = fen.query(pos), r = (n - 1 - pos) - (fen.query(n - 1) - fen.query(pos));\n res += l * r; \n fen.update(pos, 1);\n }\n return res;\n};\nfunction Fenwick(n) {\n let tree = Array(n).fill(0);\n return { query, update }\n function query(i) {\n let sum = 0;\n i++;\n while (i > 0) {\n sum += tree[i];\n i -= i & -i;\n }\n return sum;\n }\n function update(i, v) {\n i++;\n while (i < n) {\n tree[i] += v;\n i += i & -i;\n }\n }\n}" ]
2,180
count-integers-with-even-digit-sum
[ "Iterate through all integers from 1 to num.", "For any integer, extract the individual digits to compute their sum and check if it is even." ]
/** * @param {number} num * @return {number} */ var countEven = function(num) { };
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.   Example 1: Input: num = 4 Output: 2 Explanation: The only integers less than or equal to 4 whose digit sums are even are 2 and 4. Example 2: Input: num = 30 Output: 14 Explanation: The 14 integers less than or equal to 30 whose digit sums are even are 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.   Constraints: 1 <= num <= 1000
Easy
[ "math", "simulation" ]
[ "var countEven = function(num) {\n let res = 0\n for(let i = 1; i <= num; i++) {\n const tmp = sum(i)\n if(tmp % 2 === 0) res++\n }\n \n return res\n};\n\nfunction sum(e) {\n let res = 0\n while(e) {\n res += e % 10\n e = Math.floor(e/10)\n }\n return res\n}" ]
2,181
merge-nodes-in-between-zeros
[ "How can you use two pointers to modify the original list into the new list?", "Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified.", "Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a ‘0’. In that case, the modifying pointer is incremented to modify the next node.", "Do not forget to have the next pointer of the final node of the modified list point to 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 mergeNodes = function(head) { };
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list.   Example 1: Input: head = [0,3,1,0,4,5,2,0] Output: [4,11] Explanation: The above figure represents the given linked list. The modified list contains - The sum of the nodes marked in green: 3 + 1 = 4. - The sum of the nodes marked in red: 4 + 5 + 2 = 11. Example 2: Input: head = [0,1,0,3,0,2,2,0] Output: [1,3,4] Explanation: The above figure represents the given linked list. The modified list contains - The sum of the nodes marked in green: 1 = 1. - The sum of the nodes marked in red: 3 = 3. - The sum of the nodes marked in yellow: 2 + 2 = 4.   Constraints: The number of nodes in the list is in the range [3, 2 * 105]. 0 <= Node.val <= 1000 There are no two consecutive nodes with Node.val == 0. The beginning and end of the linked list have Node.val == 0.
Medium
[ "linked-list", "simulation" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "var mergeNodes = function(head) {\n const dummy = new ListNode()\n const arr = []\n let cur = head\n while(cur) {\n arr.push(cur)\n cur = cur.next\n }\n let tail = dummy\n let lastIdx = 0, sum = 0\n if(arr.length) {\n for(let i = 1; i < arr.length; i++) {\n const tmp = arr[i]\n if(tmp.val === 0 && sum !== 0) {\n lastIdx = i\n tail.next = new ListNode(sum)\n tail = tail.next\n sum = 0\n } else {\n sum += tmp.val\n }\n }\n }\n \n return dummy.next\n};" ]
2,182
construct-string-with-repeat-limit
[ "Start constructing the string in descending order of characters.", "When repeatLimit is reached, pick the next largest character." ]
/** * @param {string} s * @param {number} repeatLimit * @return {string} */ var repeatLimitedString = function(s, repeatLimit) { };
You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s. Return the lexicographically largest repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.   Example 1: Input: s = "cczazcc", repeatLimit = 3 Output: "zzcccac" Explanation: We use all of the characters from s to construct the repeatLimitedString "zzcccac". The letter 'a' appears at most 1 time in a row. The letter 'c' appears at most 3 times in a row. The letter 'z' appears at most 2 times in a row. Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString. The string is the lexicographically largest repeatLimitedString possible so we return "zzcccac". Note that the string "zzcccca" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString. Example 2: Input: s = "aababab", repeatLimit = 2 Output: "bbabaa" Explanation: We use only some of the characters from s to construct the repeatLimitedString "bbabaa". The letter 'a' appears at most 2 times in a row. The letter 'b' appears at most 2 times in a row. Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString. The string is the lexicographically largest repeatLimitedString possible so we return "bbabaa". Note that the string "bbabaaa" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.   Constraints: 1 <= repeatLimit <= s.length <= 105 s consists of lowercase English letters.
Medium
[ "string", "greedy", "heap-priority-queue", "counting" ]
[ "var repeatLimitedString = function(s, repeatLimit) {\n const a = 'a'.charCodeAt(0)\n const ch = Array(26).fill(0)\n for(let e of s) {\n const idx = e.charCodeAt(0)\n ch[idx - a]++\n }\n let res = '', last = ''\n while(true) {\n let len = res.length\n let h = false\n for(let i = 25; i >= 0; i--) {\n if(ch[i] >= repeatLimit && res[res.length - 1] !== String.fromCharCode(a + i)) {\n\n res += String.fromCharCode(a + i).repeat(repeatLimit)\n ch[i] -= repeatLimit\n \n if(ch[i]) {\n for(let j = i - 1; j >= 0; j--) {\n if(ch[j]) {\n res += String.fromCharCode(a + j)\n ch[j]--\n break\n }\n }\n break\n }\n\n }else if(ch[i] > 0 && res[res.length - 1] !== String.fromCharCode(a + i)) {\n \n res += String.fromCharCode(a + i).repeat(ch[i])\n ch[i] = 0\n break\n }\n }\n if(len === res.length) break\n }\n \n \n return res\n};" ]
2,183
count-array-pairs-divisible-by-k
[ "For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k?", "The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var countPairs = function(nums, k) { };
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that: 0 <= i < j <= n - 1 and nums[i] * nums[j] is divisible by k.   Example 1: Input: nums = [1,2,3,4,5], k = 2 Output: 7 Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are (0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4). Their products are 2, 4, 6, 8, 10, 12, and 20 respectively. Other pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2. Example 2: Input: nums = [1,2,3,4], k = 5 Output: 0 Explanation: There does not exist any pair of indices whose corresponding product is divisible by 5.   Constraints: 1 <= nums.length <= 105 1 <= nums[i], k <= 105
Hard
[ "array", "math", "number-theory" ]
[ "const countPairs = function (nums, k) {\n const map = new Map()\n\n let res = 0\n for(const e of nums) {\n const tmp = gcd(e, k)\n\n for(const [key, v] of map) {\n if(tmp * key % k === 0) {\n res += v\n }\n }\n if(map.get(tmp) == null) map.set(tmp, 0)\n map.set(tmp, map.get(tmp) + 1)\n }\n\n return res\n\n function gcd(a, b) {\n return b === 0 ? a : gcd(b, a % b)\n }\n}", "const coutPairs = function(nums, k) {\n let res = 0;\n let cnt = Array(1e5 + 1).fill(0);\n const n = nums.length\n for (let i = 0; i < n; ++i) {\n if (nums[i] % k == 0) {\n res += i;\n ++cnt[0];\n }\n else {\n let div = gcd(k, nums[i]);\n for (let d = 0; d <= div; ++d) res += cnt[k / div * d];\n ++cnt[div];\n } \n }\n return res;\n};\n\nfunction gcd(a, b) {\n if(b === 0) return a\n return gcd(b, a % b)\n}" ]
2,185
counting-words-with-a-given-prefix
[ "Go through each word in words and increment the answer if pref is a prefix of the word." ]
/** * @param {string[]} words * @param {string} pref * @return {number} */ var prefixCount = function(words, pref) { };
You are given an array of strings words and a string pref. Return the number of strings in words that contain pref as a prefix. A prefix of a string s is any leading contiguous substring of s.   Example 1: Input: words = ["pay","attention","practice","attend"], pref = "at" Output: 2 Explanation: The 2 strings that contain "at" as a prefix are: "attention" and "attend". Example 2: Input: words = ["leetcode","win","loops","success"], pref = "code" Output: 0 Explanation: There are no strings that contain "code" as a prefix.   Constraints: 1 <= words.length <= 100 1 <= words[i].length, pref.length <= 100 words[i] and pref consist of lowercase English letters.
Easy
[ "array", "string" ]
null
[]
2,186
minimum-number-of-steps-to-make-two-strings-anagram-ii
[ "Notice that for anagrams, the order of the letters is irrelevant.", "For each letter, we can count its frequency in s and t.", "For each letter, its contribution to the answer is the absolute difference between its frequency in s and t." ]
/** * @param {string} s * @param {string} t * @return {number} */ var minSteps = function(s, t) { };
You are given two strings s and t. In one step, you can append any character to either s or t. Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering.   Example 1: Input: s = "leetcode", t = "coats" Output: 7 Explanation: - In 2 steps, we can append the letters in "as" onto s = "leetcode", forming s = "leetcodeas". - In 5 steps, we can append the letters in "leede" onto t = "coats", forming t = "coatsleede". "leetcodeas" and "coatsleede" are now anagrams of each other. We used a total of 2 + 5 = 7 steps. It can be shown that there is no way to make them anagrams of each other with less than 7 steps. Example 2: Input: s = "night", t = "thing" Output: 0 Explanation: The given strings are already anagrams of each other. Thus, we do not need any further steps.   Constraints: 1 <= s.length, t.length <= 2 * 105 s and t consist of lowercase English letters.
Medium
[ "hash-table", "string", "counting" ]
null
[]
2,187
minimum-time-to-complete-trips
[ "For a given amount of time, how can we count the total number of trips completed by all buses within that time?", "Consider using binary search." ]
/** * @param {number[]} time * @param {number} totalTrips * @return {number} */ var minimumTime = function(time, totalTrips) { };
You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip. Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus. You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.   Example 1: Input: time = [1,2,3], totalTrips = 5 Output: 3 Explanation: - At time t = 1, the number of trips completed by each bus are [1,0,0]. The total number of trips completed is 1 + 0 + 0 = 1. - At time t = 2, the number of trips completed by each bus are [2,1,0]. The total number of trips completed is 2 + 1 + 0 = 3. - At time t = 3, the number of trips completed by each bus are [3,1,1]. The total number of trips completed is 3 + 1 + 1 = 5. So the minimum time needed for all buses to complete at least 5 trips is 3. Example 2: Input: time = [2], totalTrips = 1 Output: 2 Explanation: There is only one bus, and it will complete its first trip at t = 2. So the minimum time needed to complete 1 trip is 2.   Constraints: 1 <= time.length <= 105 1 <= time[i], totalTrips <= 107
Medium
[ "array", "binary-search" ]
null
[]
2,188
minimum-time-to-finish-the-race
[ "What is the maximum number of times we would want to go around the track without changing tires?", "Can we precompute the minimum time to go around the track x times without changing tires?", "Can we use dynamic programming to solve this efficiently using the precomputed values?" ]
/** * @param {number[][]} tires * @param {number} changeTime * @param {number} numLaps * @return {number} */ var minimumFinishTime = function(tires, changeTime, numLaps) { };
You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds. For example, if fi = 3 and ri = 2, then the tire would finish its 1st lap in 3 seconds, its 2nd lap in 3 * 2 = 6 seconds, its 3rd lap in 3 * 22 = 12 seconds, etc. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.   Example 1: Input: tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4 Output: 21 Explanation: Lap 1: Start with tire 0 and finish the lap in 2 seconds. Lap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds. Lap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds. Lap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds. Total time = 2 + 6 + 5 + 2 + 6 = 21 seconds. The minimum time to complete the race is 21 seconds. Example 2: Input: tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5 Output: 25 Explanation: Lap 1: Start with tire 1 and finish the lap in 2 seconds. Lap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds. Lap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds. Lap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds. Lap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second. Total time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds. The minimum time to complete the race is 25 seconds.   Constraints: 1 <= tires.length <= 105 tires[i].length == 2 1 <= fi, changeTime <= 105 2 <= ri <= 105 1 <= numLaps <= 1000
Hard
[ "array", "dynamic-programming" ]
[ " const minimumFinishTime = function (tires, changeTime, numLaps) {\n tires = preprocess(tires)\n let n = tires.length\n const { max, min } = Math\n // to handle the cases where numLaps is small\n // pre[i][j]: the total time to run j laps consecutively with tire i\n const pre = Array.from({ length: n }, () =>\n Array(20).fill(Infinity)\n )\n for (let i = 0; i < n; i++) {\n pre[i][1] = tires[i][0]\n for (let j = 2; j < 20; j++) {\n if (pre[i][j - 1] * tires[i][1] >= 2e9) break\n pre[i][j] = pre[i][j - 1] * tires[i][1]\n }\n // since we define it as the total time, rather than just the time for the j-th lap\n // we have to make it prefix sum\n for (let j = 2; j < 20; j++) {\n if (pre[i][j - 1] + pre[i][j] >= 2e9) break\n pre[i][j] += pre[i][j - 1]\n }\n }\n\n // dp[x]: the minimum time to finish x laps\n const dp = Array(numLaps + 1).fill(Infinity)\n for (let i = 0; i < n; i++) {\n dp[1] = min(dp[1], tires[i][0])\n }\n for (let x = 1; x <= numLaps; x++) {\n if (x < 20) {\n // x is small enough, so an optimal solution might never changes tires!\n for (let i = 0; i < n; i++) {\n dp[x] = min(dp[x], pre[i][x])\n }\n }\n for (let j = x - 1; j > 0 && j >= x - 18; j--) {\n dp[x] = min(dp[x], dp[j] + changeTime + dp[x - j])\n }\n }\n\n return dp[numLaps]\n}\n\nfunction preprocess(tires) {\n tires.sort((a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]))\n const res = []\n for (let t of tires) {\n if (res.length === 0 || res[res.length - 1][1] > t[1]) {\n res.push(t)\n }\n }\n return res\n}", "var minimumFinishTime = function (tires, changeTime, numLaps) {\n let N = tires.length,\n len = 0\n const { max, min } = Math\n const best = Array(numLaps).fill(Infinity),\n dp = Array(numLaps + 1).fill(Infinity)\n for (let i = 0; i < N; ++i) {\n // We assume we also need `changeTime` time to use the first tire\n // so that we don't need to treat the first tire as a special case\n let f = tires[i][0],\n r = tires[i][1],\n sum = changeTime,\n p = 1\n for (let j = 0; j < numLaps; ++j) {\n sum += f * p\n // If using the same tire takes no less time than changing the tire,\n // stop further using the current tire\n if (f * p >= f + changeTime) break \n best[j] = min(best[j], sum)\n len = max(len, j + 1)\n p *= r\n }\n }\n // dp[i + 1] is the minimum time to finish `numLaps` laps\n dp[0] = 0 \n for (let i = 0; i < numLaps; ++i) {\n for (let j = 0; j < len && i - j >= 0; ++j) {\n // try using the same tire in the last `j+1` laps\n dp[i + 1] = min(dp[i + 1], dp[i - j] + best[j])\n }\n }\n // minus the `changeTime` we added to the first tire\n return dp[numLaps] - changeTime \n}" ]
2,190
most-frequent-number-following-key-in-an-array
[ "Count the number of times each target value follows the key in the array.", "Choose the target with the maximum count and return it." ]
/** * @param {number[]} nums * @param {number} key * @return {number} */ var mostFrequent = function(nums, key) { };
You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: 0 <= i <= nums.length - 2, nums[i] == key and, nums[i + 1] == target. Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique.   Example 1: Input: nums = [1,100,200,1,100], key = 1 Output: 100 Explanation: For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key. No other integers follow an occurrence of key, so we return 100. Example 2: Input: nums = [2,2,2,2,3], key = 2 Output: 2 Explanation: For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key. For target = 3, there is only one occurrence at index 4 which follows an occurrence of key. target = 2 has the maximum number of occurrences following an occurrence of key, so we return 2.   Constraints: 2 <= nums.length <= 1000 1 <= nums[i] <= 1000 The test cases will be generated such that the answer is unique.
Easy
[ "array", "hash-table", "counting" ]
null
[]
2,191
sort-the-jumbled-numbers
[ "Map the original numbers to new numbers by the mapping rule and sort the new numbers.", "To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker." ]
/** * @param {number[]} mapping * @param {number[]} nums * @return {number[]} */ var sortJumbled = function(mapping, nums) { };
You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled decimal system. mapping[i] = j means digit i should be mapped to digit j in this system. The mapped value of an integer is the new integer obtained by replacing each occurrence of digit i in the integer with mapping[i] for all 0 <= i <= 9. You are also given another integer array nums. Return the array nums sorted in non-decreasing order based on the mapped values of its elements. Notes: Elements with the same mapped values should appear in the same relative order as in the input. The elements of nums should only be sorted based on their mapped values and not be replaced by them.   Example 1: Input: mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38] Output: [338,38,991] Explanation: Map the number 991 as follows: 1. mapping[9] = 6, so all occurrences of the digit 9 will become 6. 2. mapping[1] = 9, so all occurrences of the digit 1 will become 9. Therefore, the mapped value of 991 is 669. 338 maps to 007, or 7 after removing the leading zeros. 38 maps to 07, which is also 7 after removing leading zeros. Since 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38. Thus, the sorted array is [338,38,991]. Example 2: Input: mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123] Output: [123,456,789] Explanation: 789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is [123,456,789].   Constraints: mapping.length == 10 0 <= mapping[i] <= 9 All the values of mapping[i] are unique. 1 <= nums.length <= 3 * 104 0 <= nums[i] < 109
Medium
[ "array", "sorting" ]
null
[]
2,192
all-ancestors-of-a-node-in-a-directed-acyclic-graph
[ "Consider how reversing each edge of the graph can help us.", "How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?" ]
/** * @param {number} n * @param {number[][]} edges * @return {number[][]} */ var getAncestors = function(n, edges) { };
You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive). You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph. Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in ascending order. A node u is an ancestor of another node v if u can reach v via a set of edges.   Example 1: Input: n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]] Output: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]] Explanation: The above diagram represents the input graph. - Nodes 0, 1, and 2 do not have any ancestors. - Node 3 has two ancestors 0 and 1. - Node 4 has two ancestors 0 and 2. - Node 5 has three ancestors 0, 1, and 3. - Node 6 has five ancestors 0, 1, 2, 3, and 4. - Node 7 has four ancestors 0, 1, 2, and 3. Example 2: Input: n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] Output: [[],[0],[0,1],[0,1,2],[0,1,2,3]] Explanation: The above diagram represents the input graph. - Node 0 does not have any ancestor. - Node 1 has one ancestor 0. - Node 2 has two ancestors 0 and 1. - Node 3 has three ancestors 0, 1, and 2. - Node 4 has four ancestors 0, 1, 2, and 3.   Constraints: 1 <= n <= 1000 0 <= edges.length <= min(2000, n * (n - 1) / 2) edges[i].length == 2 0 <= fromi, toi <= n - 1 fromi != toi There are no duplicate edges. The graph is directed and acyclic.
Medium
[ "depth-first-search", "breadth-first-search", "graph", "topological-sort" ]
[ "const getAncestors = function(n, edges) {\n const res = Array.from({ length: n }, () => [])\n const graph = {}\n \n for(const [u, v] of edges) {\n if(graph[u] == null) graph[u] = []\n graph[u].push(v)\n }\n \n for(let i = 0; i < n; i++) {\n dfs(i, i)\n }\n \n return res\n \n function dfs(p, cur) {\n for(const nxt of (graph[cur] || [])) {\n if(res[nxt].length === 0 || res[nxt][res[nxt].length - 1] !== p) {\n res[nxt].push(p)\n dfs(p, nxt)\n }\n }\n }\n};", "const getAncestors = function(n, edges) {\n const res = Array.from({ length: n }, () => new Set())\n const inDegree = Array(n).fill(0)\n const graph = {}\n \n for(const [u, v] of edges) {\n if(graph[v] == null) graph[v] = []\n graph[v].push(u)\n inDegree[v]++\n }\n \n const visited = Array(n).fill(false)\n for (let i = 0; i < n; i++) {\n if (!visited[i]) dfs(i);\n }\n\n return res.map(set => Array.from(set).sort((a, b) => a - b))\n \n function dfs(i) {\n visited[i] = true\n for(const p of (graph[i] || [])) {\n if(visited[p] === false) dfs(p)\n res[i].add(p)\n for(const e of res[p]) res[i].add(e)\n }\n }\n};" ]
2,193
minimum-number-of-moves-to-make-palindrome
[ "Consider a greedy strategy.", "Let’s start by making the leftmost and rightmost characters match with some number of swaps.", "If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively." ]
/** * @param {string} s * @return {number} */ var minMovesToMakePalindrome = function(s) { };
You are given a string s consisting only of lowercase English letters. In one move, you can select any two adjacent characters of s and swap them. Return the minimum number of moves needed to make s a palindrome. Note that the input will be generated such that s can always be converted to a palindrome.   Example 1: Input: s = "aabb" Output: 2 Explanation: We can obtain two palindromes from s, "abba" and "baab". - We can obtain "abba" from s in 2 moves: "aabb" -> "abab" -> "abba". - We can obtain "baab" from s in 2 moves: "aabb" -> "abab" -> "baab". Thus, the minimum number of moves needed to make s a palindrome is 2. Example 2: Input: s = "letelt" Output: 2 Explanation: One of the palindromes we can obtain from s in 2 moves is "lettel". One of the ways we can obtain it is "letelt" -> "letetl" -> "lettel". Other palindromes such as "tleelt" can also be obtained in 2 moves. It can be shown that it is not possible to obtain a palindrome in less than 2 moves.   Constraints: 1 <= s.length <= 2000 s consists only of lowercase English letters. s can be converted to a palindrome using a finite number of moves.
Hard
[ "two-pointers", "string", "greedy", "binary-indexed-tree" ]
[ "const minMovesToMakePalindrome = function(s) {\n let res = 0\n const arr = s.split('')\n \n while(arr.length) {\n const idx = arr.indexOf(arr[arr.length - 1])\n if(idx === arr.length - 1) {\n res += ~~(idx / 2)\n } else {\n res += idx\n arr.splice(idx, 1)\n }\n arr.pop()\n }\n\n return res\n};" ]
2,194
cells-in-a-range-on-an-excel-sheet
[ "From the given string, find the corresponding rows and columns.", "Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order." ]
/** * @param {string} s * @return {string[]} */ var cellsInRange = function(s) { };
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: <col> denotes the column number c of the cell. It is represented by alphabetical letters. For example, the 1st column is denoted by 'A', the 2nd by 'B', the 3rd by 'C', and so on. <row> is the row number r of the cell. The rth row is represented by the integer r. You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.   Example 1: Input: s = "K1:L2" Output: ["K1","K2","L1","L2"] Explanation: The above diagram shows the cells which should be present in the list. The red arrows denote the order in which the cells should be presented. Example 2: Input: s = "A1:F1" Output: ["A1","B1","C1","D1","E1","F1"] Explanation: The above diagram shows the cells which should be present in the list. The red arrow denotes the order in which the cells should be presented.   Constraints: s.length == 5 'A' <= s[0] <= s[3] <= 'Z' '1' <= s[1] <= s[4] <= '9' s consists of uppercase English letters, digits and ':'.
Easy
[ "string" ]
null
[]
2,195
append-k-integers-with-minimal-sum
[ "The k smallest numbers that do not appear in nums will result in the minimum sum.", "Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2.", "Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var minimalKSum = function(nums, k) { };
You are given an integer array nums and an integer k. Append k unique positive integers that do not appear in nums to nums such that the resulting total sum is minimum. Return the sum of the k integers appended to nums.   Example 1: Input: nums = [1,4,25,10,25], k = 2 Output: 5 Explanation: The two unique positive integers that do not appear in nums which we append are 2 and 3. The resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum. The sum of the two integers appended is 2 + 3 = 5, so we return 5. Example 2: Input: nums = [5,6], k = 6 Output: 25 Explanation: The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8. The resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum. The sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109 1 <= k <= 108
Medium
[ "array", "math", "greedy", "sorting" ]
null
[]
2,196
create-binary-tree-from-descriptions
[ "Could you represent and store the descriptions more efficiently?", "Could you find the root node?", "The node that is not a child in any of the descriptions is the root node." ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {number[][]} descriptions * @return {TreeNode} */ var createBinaryTree = function(descriptions) { };
You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, If isLefti == 1, then childi is the left child of parenti. If isLefti == 0, then childi is the right child of parenti. Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid.   Example 1: Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]] Output: [50,20,80,15,17,19] Explanation: The root node is the node with value 50 since it has no parent. The resulting binary tree is shown in the diagram. Example 2: Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]] Output: [1,2,null,null,3,4] Explanation: The root node is the node with value 1 since it has no parent. The resulting binary tree is shown in the diagram.   Constraints: 1 <= descriptions.length <= 104 descriptions[i].length == 3 1 <= parenti, childi <= 105 0 <= isLefti <= 1 The binary tree described by descriptions is valid.
Medium
[ "array", "hash-table", "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
null
[]
2,197
replace-non-coprime-numbers-in-array
[ "Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible.", "If a new value is formed, we should recursively check if it can be merged with the value to its left.", "To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left)." ]
/** * @param {number[]} nums * @return {number[]} */ var replaceNonCoprimes = function(nums) { };
You are given an array of integers nums. Perform the following steps: Find any two adjacent numbers in nums that are non-coprime. If no such numbers are found, stop the process. Otherwise, delete the two numbers and replace them with their LCM (Least Common Multiple). Repeat this process as long as you keep finding two adjacent non-coprime numbers. Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y.   Example 1: Input: nums = [6,4,3,2,7,6,2] Output: [12,7,6] Explanation: - (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2]. - (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2]. - (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2]. - (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6]. There are no more adjacent non-coprime numbers in nums. Thus, the final modified array is [12,7,6]. Note that there are other ways to obtain the same resultant array. Example 2: Input: nums = [2,2,1,1,3,3,3] Output: [2,1,1,3] Explanation: - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3]. - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3]. - (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3]. There are no more adjacent non-coprime numbers in nums. Thus, the final modified array is [2,1,1,3]. Note that there are other ways to obtain the same resultant array.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105 The test cases are generated such that the values in the final array are less than or equal to 108.
Hard
[ "array", "math", "stack", "number-theory" ]
[ "const gcd = (a, b) => (b == 0 ? a : gcd(b, a % b));\n\nconst replaceNonCoprimes = function (nums) {\n const stk = [];\n for (let x of nums) {\n if (stk.length === 0) {\n stk.push(x);\n } else {\n while (stk.length && gcd(stk[stk.length - 1], x) !== 1) {\n // check if it can be merged with the value to its left\n const last = stk.pop(),\n g = gcd(x, last);\n x = (x / g) * last; // merge value, update lcm to x\n }\n stk.push(x);\n }\n }\n return stk;\n};" ]
2,200
find-all-k-distant-indices-in-an-array
[ "For every occurrence of key in nums, find all indices within distance k from it.", "Use a hash table to remove duplicate indices." ]
/** * @param {number[]} nums * @param {number} key * @param {number} k * @return {number[]} */ var findKDistantIndices = function(nums, key, k) { };
You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order.   Example 1: Input: nums = [3,4,9,1,3,9,5], key = 9, k = 1 Output: [1,2,3,4,5,6] Explanation: Here, nums[2] == key and nums[5] == key. - For index 0, |0 - 2| > k and |0 - 5| > k, so there is no j where |0 - j| <= k and nums[j] == key. Thus, 0 is not a k-distant index. - For index 1, |1 - 2| <= k and nums[2] == key, so 1 is a k-distant index. - For index 2, |2 - 2| <= k and nums[2] == key, so 2 is a k-distant index. - For index 3, |3 - 2| <= k and nums[2] == key, so 3 is a k-distant index. - For index 4, |4 - 5| <= k and nums[5] == key, so 4 is a k-distant index. - For index 5, |5 - 5| <= k and nums[5] == key, so 5 is a k-distant index. - For index 6, |6 - 5| <= k and nums[5] == key, so 6 is a k-distant index. Thus, we return [1,2,3,4,5,6] which is sorted in increasing order. Example 2: Input: nums = [2,2,2,2,2], key = 2, k = 2 Output: [0,1,2,3,4] Explanation: For all indices i in nums, there exists some index j such that |i - j| <= k and nums[j] == key, so every index is a k-distant index. Hence, we return [0,1,2,3,4].   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 1000 key is an integer from the array nums. 1 <= k <= nums.length
Easy
[ "array" ]
null
[]
2,201
count-artifacts-that-can-be-extracted
[ "Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time?", "Consider marking all excavated cells in a 2D boolean array." ]
/** * @param {number} n * @param {number[][]} artifacts * @param {number[][]} dig * @return {number} */ var digArtifacts = function(n, artifacts, dig) { };
There is an n x n 0-indexed grid with some artifacts buried in it. You are given the integer n and a 0-indexed 2D integer array artifacts describing the positions of the rectangular artifacts where artifacts[i] = [r1i, c1i, r2i, c2i] denotes that the ith artifact is buried in the subgrid where: (r1i, c1i) is the coordinate of the top-left cell of the ith artifact and (r2i, c2i) is the coordinate of the bottom-right cell of the ith artifact. You will excavate some cells of the grid and remove all the mud from them. If the cell has a part of an artifact buried underneath, it will be uncovered. If all the parts of an artifact are uncovered, you can extract it. Given a 0-indexed 2D integer array dig where dig[i] = [ri, ci] indicates that you will excavate the cell (ri, ci), return the number of artifacts that you can extract. The test cases are generated such that: No two artifacts overlap. Each artifact only covers at most 4 cells. The entries of dig are unique.   Example 1: Input: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1]] Output: 1 Explanation: The different colors represent different artifacts. Excavated cells are labeled with a 'D' in the grid. There is 1 artifact that can be extracted, namely the red artifact. The blue artifact has one part in cell (1,1) which remains uncovered, so we cannot extract it. Thus, we return 1. Example 2: Input: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1],[1,1]] Output: 2 Explanation: Both the red and blue artifacts have all parts uncovered (labeled with a 'D') and can be extracted, so we return 2.   Constraints: 1 <= n <= 1000 1 <= artifacts.length, dig.length <= min(n2, 105) artifacts[i].length == 4 dig[i].length == 2 0 <= r1i, c1i, r2i, c2i, ri, ci <= n - 1 r1i <= r2i c1i <= c2i No two artifacts will overlap. The number of cells covered by an artifact is at most 4. The entries of dig are unique.
Medium
[ "array", "hash-table", "simulation" ]
null
[]
2,202
maximize-the-topmost-element-after-k-moves
[ "For each index i, how can we check if nums[i] can be present at the top of the pile or not after k moves?", "For which conditions will we end up with an empty pile?" ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var maximumTop = function(nums, k) { };
You are given a 0-indexed integer array nums representing the contents of a pile, where nums[0] is the topmost element of the pile. In one move, you can perform either of the following: If the pile is not empty, remove the topmost element of the pile. If there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element. You are also given an integer k, which denotes the total number of moves to be made. Return the maximum value of the topmost element of the pile possible after exactly k moves. In case it is not possible to obtain a non-empty pile after k moves, return -1.   Example 1: Input: nums = [5,2,2,4,0,6], k = 4 Output: 5 Explanation: One of the ways we can end with 5 at the top of the pile after 4 moves is as follows: - Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6]. - Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6]. - Step 3: Remove the topmost element = 2. The pile becomes [4,0,6]. - Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6]. Note that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves. Example 2: Input: nums = [2], k = 1 Output: -1 Explanation: In the first move, our only option is to pop the topmost element of the pile. Since it is not possible to obtain a non-empty pile after one move, we return -1.   Constraints: 1 <= nums.length <= 105 0 <= nums[i], k <= 109
Medium
[ "array", "greedy" ]
null
[]
2,203
minimum-weighted-subgraph-with-the-required-paths
[ "Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution.", "It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide.", "How can algorithms for finding the shortest path between two nodes help us?" ]
/** * @param {number} n * @param {number[][]} edges * @param {number} src1 * @param {number} src2 * @param {number} dest * @return {number} */ var minimumWeight = function(n, edges, src1, src2, dest) { };
You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges.   Example 1: Input: n = 6, edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], src1 = 0, src2 = 1, dest = 5 Output: 9 Explanation: The above figure represents the input graph. The blue edges represent one of the subgraphs that yield the optimal answer. Note that the subgraph [[1,0,3],[0,5,6]] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints. Example 2: Input: n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2 Output: -1 Explanation: The above figure represents the input graph. It can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints.   Constraints: 3 <= n <= 105 0 <= edges.length <= 105 edges[i].length == 3 0 <= fromi, toi, src1, src2, dest <= n - 1 fromi != toi src1, src2, and dest are pairwise distinct. 1 <= weight[i] <= 105
Hard
[ "graph", "shortest-path" ]
null
[]
2,206
divide-array-into-equal-pairs
[ "For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x.", "The elements with equal value can be divided completely into pairs if and only if their count is even." ]
/** * @param {number[]} nums * @return {boolean} */ var divideArray = function(nums) { };
You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Each element belongs to exactly one pair. The elements present in a pair are equal. Return true if nums can be divided into n pairs, otherwise return false.   Example 1: Input: nums = [3,2,3,2,2,2] Output: true Explanation: There are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs. If nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions. Example 2: Input: nums = [1,2,3,4] Output: false Explanation: There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.   Constraints: nums.length == 2 * n 1 <= n <= 500 1 <= nums[i] <= 500
Easy
[ "array", "hash-table", "bit-manipulation", "counting" ]
null
[]
2,207
maximize-number-of-subsequences-in-a-string
[ "Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1].", "For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer." ]
/** * @param {string} text * @param {string} pattern * @return {number} */ var maximumSubsequenceCount = function(text, pattern) { };
You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.   Example 1: Input: text = "abdcdbc", pattern = "ac" Output: 4 Explanation: If we add pattern[0] = 'a' in between text[1] and text[2], we get "abadcdbc". Now, the number of times "ac" occurs as a subsequence is 4. Some other strings which have 4 subsequences "ac" after adding a character to text are "aabdcdbc" and "abdacdbc". However, strings such as "abdcadbc", "abdccdbc", and "abdcdbcc", although obtainable, have only 3 subsequences "ac" and are thus suboptimal. It can be shown that it is not possible to get more than 4 subsequences "ac" by adding only one character. Example 2: Input: text = "aabb", pattern = "ab" Output: 6 Explanation: Some of the strings which can be obtained from text and have 6 subsequences "ab" are "aaabb", "aaabb", and "aabbb".   Constraints: 1 <= text.length <= 105 pattern.length == 2 text and pattern consist only of lowercase English letters.
Medium
[ "string", "greedy", "prefix-sum" ]
null
[]
2,208
minimum-operations-to-halve-array-sum
[ "It is always optimal to halve the largest element.", "What data structure allows for an efficient query of the maximum element?", "Use a heap or priority queue to maintain the current elements." ]
/** * @param {number[]} nums * @return {number} */ var halveArray = function(nums) { };
You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half.   Example 1: Input: nums = [5,19,8,1] Output: 3 Explanation: The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33. The following is one of the ways to reduce the sum by at least half: Pick the number 19 and reduce it to 9.5. Pick the number 9.5 and reduce it to 4.75. Pick the number 8 and reduce it to 4. The final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. The sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5. Overall, 3 operations were used so we return 3. It can be shown that we cannot reduce the sum by at least half in less than 3 operations. Example 2: Input: nums = [3,8,20] Output: 3 Explanation: The initial sum of nums is equal to 3 + 8 + 20 = 31. The following is one of the ways to reduce the sum by at least half: Pick the number 20 and reduce it to 10. Pick the number 10 and reduce it to 5. Pick the number 3 and reduce it to 1.5. The final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. The sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 15.5. Overall, 3 operations were used so we return 3. It can be shown that we cannot reduce the sum by at least half in less than 3 operations.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 107
Medium
[ "array", "greedy", "heap-priority-queue" ]
null
[]
2,209
minimum-white-tiles-after-covering-with-carpets
[ "Can you think of a DP solution?", "Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets.", "The transition will be whether to put down the carpet at position i (if possible), or not." ]
/** * @param {string} floor * @param {number} numCarpets * @param {number} carpetLen * @return {number} */ var minimumWhiteTiles = function(floor, numCarpets, carpetLen) { };
You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: floor[i] = '0' denotes that the ith tile of the floor is colored black. On the other hand, floor[i] = '1' denotes that the ith tile of the floor is colored white. You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible.   Example 1: Input: floor = "10110101", numCarpets = 2, carpetLen = 2 Output: 2 Explanation: The figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible. No other way of covering the tiles with the carpets can leave less than 2 white tiles visible. Example 2: Input: floor = "11111", numCarpets = 2, carpetLen = 3 Output: 0 Explanation: The figure above shows one way of covering the tiles with the carpets such that no white tiles are visible. Note that the carpets are able to overlap one another.   Constraints: 1 <= carpetLen <= floor.length <= 1000 floor[i] is either '0' or '1'. 1 <= numCarpets <= 1000
Hard
[ "string", "dynamic-programming", "prefix-sum" ]
[ "const minimumWhiteTiles = function(floor, numCarpets, carpetLen) {\n // 0: black, 1: white\n const n = floor.length\n // dp[i][j]: the minimum number of white tiles still visible\n // when using j tiles to cover the first i tiles \n const dp = Array.from({ length: n + 1 }, () => Array(numCarpets + 1).fill(0))\n\n const ones = Array(n + 1).fill(0)\n for(let i = 1; i <= n; i++) {\n ones[i] = ones[i - 1] + (floor[i - 1] === '1' ? 1 : 0) \n }\n for(let i = 1; i <= n; i++) {\n dp[i][0] = ones[i]\n for(let j = 1; j <= numCarpets; j++) {\n const skip = dp[i - 1][j] + (floor[i - 1] === '1' ? 1 : 0)\n const cover = dp[Math.max(i - carpetLen, 0)][j - 1]\n dp[i][j] = Math.min(skip, cover)\n }\n }\n\n return dp[n][numCarpets]\n};" ]
2,210
count-hills-and-valleys-in-an-array
[ "For each index, could you find the closest non-equal neighbors?", "Ensure that adjacent indices that are part of the same hill or valley are not double-counted." ]
/** * @param {number[]} nums * @return {number} */ var countHillValley = function(nums) { };
You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums.   Example 1: Input: nums = [2,4,1,1,6,5] Output: 3 Explanation: At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley. At index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill. At index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley. At index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2. At index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill. At index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. There are 3 hills and valleys so we return 3. Example 2: Input: nums = [6,6,5,5,4,1] Output: 0 Explanation: At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley. At index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley. At index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley. At index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley. At index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley. At index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley. There are 0 hills and valleys so we return 0.   Constraints: 3 <= nums.length <= 100 1 <= nums[i] <= 100
Easy
[ "array" ]
[ "const countHillValley = function(nums) {\n const arr = [nums[0]], n = nums.length\n for(let i = 1; i < n; i++) {\n if(nums[i] !== nums[i - 1]) arr.push(nums[i])\n }\n let res = 0\n for(let i = 1; i < arr.length - 1; i++) {\n if(\n arr[i] > arr[i - 1] && arr[i] > arr[i + 1] ||\n arr[i] < arr[i - 1] && arr[i] < arr[i + 1]\n ) res++\n }\n \n return res\n};" ]
2,211
count-collisions-on-a-road
[ "In what circumstances does a moving car not collide with another car?", "If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer?", "Will stationary cars contribute towards the answer?" ]
/** * @param {string} directions * @return {number} */ var countCollisions = function(directions) { };
There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: When two cars moving in opposite directions collide with each other, the number of collisions increases by 2. When a moving car collides with a stationary car, the number of collisions increases by 1. After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road.   Example 1: Input: directions = "RLRSLL" Output: 5 Explanation: The collisions that will happen on the road are: - Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2. - Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3. - Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4. - Cars 4 and 5 will collide with each other. After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The number of collisions becomes 4 + 1 = 5. Thus, the total number of collisions that will happen on the road is 5. Example 2: Input: directions = "LLRR" Output: 0 Explanation: No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.   Constraints: 1 <= directions.length <= 105 directions[i] is either 'L', 'R', or 'S'.
Medium
[ "string", "stack" ]
[ "const countCollisions = function(directions) {\n let res = 0, n = directions.length\n\n let flag = false\n // left -> right\n for(let i = 0; i < n; i++) {\n if(directions[i] !== 'L') {\n flag = true\n } else {\n res += flag ? 1 : 0\n }\n }\n flag = false\n // right -> left\n for(let i = n - 1; i >= 0; i--) {\n if(directions[i] !== 'R') {\n flag = true\n } else {\n res += flag ? 1 : 0\n }\n }\n\n return res\n};", " const countCollisions = function(directions) {\n let res = 0, n = directions.length\n let left = 0, right = n - 1\n while(left < n && directions[left] === 'L') left++\n while(right >= 0 && directions[right] === 'R') right--\n for(let i = left; i <= right; i++) res += directions[i] === 'S' ? 0 : 1\n return res\n};" ]
2,212
maximum-points-in-an-archery-competition
[ "To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot?", "Given the small number of sections, can we brute force which sections Bob wants to win?", "For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection." ]
/** * @param {number} numArrows * @param {number[]} aliceArrows * @return {number[]} */ var maximumBobPoints = function(numArrows, aliceArrows) { };
Alice and Bob are opponents in an archery competition. The competition has set the following rules: Alice first shoots numArrows arrows and then Bob shoots numArrows arrows. The points are then calculated as follows: The target has integer scoring sections ranging from 0 to 11 inclusive. For each section of the target with score k (in between 0 to 11), say Alice and Bob have shot ak and bk arrows on that section respectively. If ak >= bk, then Alice takes k points. If ak < bk, then Bob takes k points. However, if ak == bk == 0, then nobody takes k points. For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them.   Example 1: Input: numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0] Output: [0,0,0,0,1,1,0,0,1,2,3,1] Explanation: The table above shows how the competition is scored. Bob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47. It can be shown that Bob cannot obtain a score higher than 47 points. Example 2: Input: numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2] Output: [0,0,0,0,0,0,0,0,1,1,1,0] Explanation: The table above shows how the competition is scored. Bob earns a total point of 8 + 9 + 10 = 27. It can be shown that Bob cannot obtain a score higher than 27 points.   Constraints: 1 <= numArrows <= 105 aliceArrows.length == bobArrows.length == 12 0 <= aliceArrows[i], bobArrows[i] <= numArrows sum(aliceArrows[i]) == numArrows
Medium
[ "array", "backtracking", "bit-manipulation", "enumeration" ]
[ "const maximumBobPoints = function(numArrows, aliceArrows) {\n let bestScore = 0, res = null\n const sum = arr => arr.reduce((ac, e) => ac + e, 0)\n bt(0, numArrows, 0, Array(12).fill(0))\n res[0] += numArrows - sum(res)\n return res\n\n function bt(k, remain, score, bobArrows) {\n if(k == 12) {\n if(score > bestScore) {\n bestScore = score\n res = bobArrows.slice(0)\n }\n return\n }\n bt(k + 1, remain, score, bobArrows)\n let arrowsNeeded = aliceArrows[k] + 1\n if(remain >= arrowsNeeded) {\n let bak = bobArrows[k]\n bobArrows[k] = arrowsNeeded\n bt(k + 1, remain - arrowsNeeded, score + k, bobArrows)\n bobArrows[k] = bak\n }\n }\n};" ]
2,213
longest-substring-of-one-repeating-character
[ "Use a segment tree to perform fast point updates and range queries.", "We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character.", "We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character.", "Use this information to properly merge the two segment tree nodes together." ]
/** * @param {string} s * @param {string} queryCharacters * @param {number[]} queryIndices * @return {number[]} */ var longestRepeating = function(s, queryCharacters, queryIndices) { };
You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed.   Example 1: Input: s = "babacc", queryCharacters = "bcb", queryIndices = [1,3,3] Output: [3,3,4] Explanation: - 1st query updates s = "bbbacc". The longest substring consisting of one repeating character is "bbb" with length 3. - 2nd query updates s = "bbbccc". The longest substring consisting of one repeating character can be "bbb" or "ccc" with length 3. - 3rd query updates s = "bbbbcc". The longest substring consisting of one repeating character is "bbbb" with length 4. Thus, we return [3,3,4]. Example 2: Input: s = "abyzz", queryCharacters = "aa", queryIndices = [2,1] Output: [2,3] Explanation: - 1st query updates s = "abazz". The longest substring consisting of one repeating character is "zz" with length 2. - 2nd query updates s = "aaazz". The longest substring consisting of one repeating character is "aaa" with length 3. Thus, we return [2,3].   Constraints: 1 <= s.length <= 105 s consists of lowercase English letters. k == queryCharacters.length == queryIndices.length 1 <= k <= 105 queryCharacters consists of lowercase English letters. 0 <= queryIndices[i] < s.length
Hard
[ "array", "string", "segment-tree", "ordered-set" ]
[ "const longestRepeating = function(s, queryCharacters, queryIndices) {\n let n = queryCharacters.length\n const ans = []\n\n const segmentTree = new SegmentTree(s)\n for (let i = 0; i < n; i++) {\n segmentTree.update(1, 0, s.length - 1, queryIndices[i], queryCharacters[i])\n ans.push(segmentTree.getMax())\n }\n\n return ans\n};\n\nclass TreeNode {\n constructor(max, preStart, preEnd, sufStart, sufEnd) {\n this.max = max\n this.preStart = preStart\n this.preEnd = preEnd\n this.sufStart = sufStart\n this.sufEnd = sufEnd\n }\n}\n\nclass SegmentTree {\n constructor(s) {\n this.n = s.length\n this.s = s.split('')\n this.tree = new Array(4 * s.length)\n this.build(s, 1, 0, s.length - 1)\n }\n\n build(s, treeIndex, left, right) {\n if (left === right) {\n this.tree[treeIndex] = new TreeNode(1, left, left, right, right)\n return\n }\n\n let mid = left + Math.floor((right - left) / 2)\n this.build(s, treeIndex * 2, left, mid)\n this.build(s, treeIndex * 2 + 1, mid + 1, right)\n\n this.tree[treeIndex] = this.merge(\n this.tree[treeIndex * 2],\n this.tree[treeIndex * 2 + 1],\n left,\n mid,\n right\n )\n }\n\n update(treeIndex, left, right, index, val) {\n if (left === right) {\n this.tree[treeIndex] = new TreeNode(1, left, left, right, right)\n this.s[index] = val\n return\n }\n\n let mid = left + Math.floor((right - left) / 2)\n if (mid < index) {\n this.update(treeIndex * 2 + 1, mid + 1, right, index, val)\n } else {\n this.update(treeIndex * 2, left, mid, index, val)\n }\n\n this.tree[treeIndex] = this.merge(\n this.tree[treeIndex * 2],\n this.tree[treeIndex * 2 + 1],\n left,\n mid,\n right\n )\n }\n\n merge(l, r, left, mid, right) {\n let max = Math.max(l.max, r.max)\n let preStart = l.preStart\n let preEnd = l.preEnd\n let sufStart = r.sufStart\n let sufEnd = r.sufEnd\n\n if (this.s[mid] === this.s[mid + 1]) {\n max = Math.max(max, r.preEnd - l.sufStart + 1)\n if (l.preEnd - l.preStart + 1 === mid - left + 1) {\n preEnd = r.preEnd\n }\n if (r.sufEnd - r.sufStart + 1 === right - mid) {\n sufStart = l.sufStart\n }\n }\n\n return new TreeNode(max, preStart, preEnd, sufStart, sufEnd)\n }\n\n getMax() {\n return this.tree[1].max\n }\n}" ]
2,215
find-the-difference-of-two-arrays
[ "For each integer in nums1, check if it exists in nums2.", "Do the same for each integer in nums2." ]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[][]} */ var findDifference = function(nums1, nums2) { };
Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where: answer[0] is a list of all distinct integers in nums1 which are not present in nums2. answer[1] is a list of all distinct integers in nums2 which are not present in nums1. Note that the integers in the lists may be returned in any order.   Example 1: Input: nums1 = [1,2,3], nums2 = [2,4,6] Output: [[1,3],[4,6]] Explanation: For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3]. For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6]. Example 2: Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2] Output: [[3],[]] Explanation: For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3]. Every integer in nums2 is present in nums1. Therefore, answer[1] = [].   Constraints: 1 <= nums1.length, nums2.length <= 1000 -1000 <= nums1[i], nums2[i] <= 1000
Easy
[ "array", "hash-table" ]
[ "var findDifference = function(nums1, nums2) {\n const set1 = new Set(nums1), set2 = new Set(nums2)\n const res = [new Set(), new Set()]\n for(let e of nums1) {\n if(set2.has(e)) continue\n else res[0].add(e)\n }\n for(let e of nums2) {\n if(set1.has(e)) continue\n else res[1].add(e)\n }\n res[0] = Array.from(res[0])\n res[1] = Array.from(res[1])\n return res\n};" ]
2,216
minimum-deletions-to-make-array-beautiful
[ "Delete as many adjacent equal elements as necessary.", "If the length of nums is odd after the entire process, delete the last element." ]
/** * @param {number[]} nums * @return {number} */ var minDeletion = function(nums) { };
You are given a 0-indexed integer array nums. The array nums is beautiful if: nums.length is even. nums[i] != nums[i + 1] for all i % 2 == 0. Note that an empty array is considered beautiful. You can delete any number of elements from nums. When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged. Return the minimum number of elements to delete from nums to make it beautiful.   Example 1: Input: nums = [1,1,2,3,5] Output: 1 Explanation: You can delete either nums[0] or nums[1] to make nums = [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to make nums beautiful. Example 2: Input: nums = [1,1,2,2,3,3] Output: 2 Explanation: You can delete nums[0] and nums[5] to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful.   Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 105
Medium
[ "array", "stack", "greedy" ]
[ "const minDeletion = function(nums) {\n let res = 0, n = nums.length\n\n for(let i = 0; i < n; i += 2) {\n while(i < n - 1 && nums[i] === nums[i + 1]) {\n i++\n res++\n }\n }\n if((n - res) % 2 === 1) res++\n return res\n};", "const minDeletion = function(nums) {\n let res = 0, i = 0\n for(i = 0, n = nums.length; i < n - 1;) {\n if(nums[i] === nums[i + 1]) {\n res++\n i++\n }else{\n i += 2\n }\n }\n if((nums.length - res) % 2 === 1) res++\n \n return res\n};" ]
2,217
find-palindrome-with-fixed-length
[ "For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength?", "Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome." ]
/** * @param {number[]} queries * @param {number} intLength * @return {number[]} */ var kthPalindrome = function(queries, intLength) { };
Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists. A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.   Example 1: Input: queries = [1,2,3,4,5,90], intLength = 3 Output: [101,111,121,131,141,999] Explanation: The first few palindromes of length 3 are: 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ... The 90th palindrome of length 3 is 999. Example 2: Input: queries = [2,4,6], intLength = 4 Output: [1111,1331,1551] Explanation: The first six palindromes of length 4 are: 1001, 1111, 1221, 1331, 1441, and 1551.   Constraints: 1 <= queries.length <= 5 * 104 1 <= queries[i] <= 109 1 <= intLength <= 15
Medium
[ "array", "math" ]
[ "var kthPalindrome = function(queries, intLength) {\n if (intLength == 1) {\n let res = []\n for (let item of queries) {\n if (item <= 9) res.push(item)\n else res.push(-1) \n }\n return res \n }\n\n let n = Math.floor(intLength / 2)\n let ref = +(\"1\"+\"0\".repeat(n-1))\n\n if (intLength % 2 == 0) {\n let res = []\n for (let item of queries) res.push(gen_even(item))\n return res \n } else {\n let res = []\n for (let item of queries) res.push(gen_odd(item))\n return res\n }\n\n function gen_even(val) {\n let part = ref + val - 1\n part = '' + part\n if (part.length != n) return -1\n return +(part + part.split('').reverse().join('')) \n }\n\n\n function gen_odd(val) {\n let mod = (val - 1) % 10\n let div = Math.floor((val - 1) / 10)\n let part = ref + div\n mod = '' + mod, part = '' + part\n if (part.length != n) return -1\n return +(part + mod + part.split('').reverse().join('')) \n }\n};" ]