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
1,696
jump-game-vi
[ "Let dp[i] be \"the maximum score to reach the end starting at index i\". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution.", "Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value in the heap is out of bounds of the current index, remove it and keep checking." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var maxResult = function(nums, k) { };
You are given a 0-indexed integer array nums and an integer k. You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive. You want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array. Return the maximum score you can get.   Example 1: Input: nums = [1,-1,-2,4,-7,3], k = 2 Output: 7 Explanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7. Example 2: Input: nums = [10,-5,-2,4,0,3], k = 3 Output: 17 Explanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17. Example 3: Input: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2 Output: 0   Constraints: 1 <= nums.length, k <= 105 -104 <= nums[i] <= 104
Medium
[ "array", "dynamic-programming", "queue", "heap-priority-queue", "monotonic-queue" ]
[ "const maxResult = function (nums, k) {\n const n = nums.length\n const f = Array(n).fill(0)\n f[0] = nums[0]\n const q = [0]\n for (let i = 1; i < n; ++i) {\n while (i - q[0] > k) {\n q.shift()\n }\n f[i] = f[q[0]] + nums[i]\n while (q.length && f[i] >= f[q[q.length - 1]]) {\n q.pop()\n }\n q.push(i)\n }\n return f[n - 1]\n}" ]
1,697
checking-existence-of-edge-length-limited-paths
[ "All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?" ]
/** * @param {number} n * @param {number[][]} edgeList * @param {number[][]} queries * @return {boolean[]} */ var distanceLimitedPathsExist = function(n, edgeList, queries) { };
An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes. Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj . Return a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j] is true, and false otherwise.   Example 1: Input: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]] Output: [false,true] Explanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16. For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query. For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query. Example 2: Input: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]] Output: [true,false] Explanation: The above figure shows the given graph.   Constraints: 2 <= n <= 105 1 <= edgeList.length, queries.length <= 105 edgeList[i].length == 3 queries[j].length == 3 0 <= ui, vi, pj, qj <= n - 1 ui != vi pj != qj 1 <= disi, limitj <= 109 There may be multiple edges between two nodes.
Hard
[ "array", "union-find", "graph", "sorting" ]
[ "const distanceLimitedPathsExist = function (n, edgeList, queries) {\n edgeList.sort((a, b) => a[2] - b[2])\n const m = queries.length\n const res = Array(m).fill(false)\n const order = Array(m).fill(0)\n for (let i = 0; i < m; ++i) order[i] = i\n order.sort((i, j) => queries[i][2] - queries[j][2])\n const uf = new UF(n)\n let idx = 0\n for (let i of order) {\n const limit = queries[i][2]\n while (idx < edgeList.length && edgeList[idx][2] < limit) {\n const [u, v] = edgeList[idx]\n uf.union(u, v)\n idx++\n }\n const [u0, v0] = queries[i]\n if (uf.find(u0) === uf.find(v0)) res[i] = true\n }\n return res\n}\n\nclass UF {\n constructor(n) {\n this.root = Array(n)\n .fill(null)\n .map((_, i) => i)\n }\n find(x) {\n if (this.root[x] !== x) {\n this.root[x] = this.find(this.root[x])\n }\n return this.root[x]\n }\n union(x, y) {\n const xr = this.find(x)\n const yr = this.find(y)\n this.root[yr] = xr\n }\n}", "const distanceLimitedPathsExist = function (n, edgeList, queries) {\n edgeList.sort((a, b) => a[2] - b[2])\n const m = queries.length\n const ans = Array(m).fill(false)\n const order = Array(m).fill(0)\n for (let i = 0; i < m; ++i) order[i] = i\n order.sort((i, j) => queries[i][2] - queries[j][2])\n const uf = new UnionFind(n)\n let idx = 0\n for (let i of order) {\n const limit = queries[i][2]\n while (idx < edgeList.length && edgeList[idx][2] < limit) {\n const [u, v] = edgeList[idx]\n uf.union(u, v)\n idx++\n }\n const [u0, v0] = queries[i]\n if (uf.find(u0) === uf.find(v0)) ans[i] = true\n }\n return ans\n}\nclass UnionFind {\n constructor(n) {\n this.parents = Array(n)\n .fill(0)\n .map((e, i) => i)\n this.ranks = Array(n).fill(0)\n }\n root(x) {\n while (x !== this.parents[x]) {\n this.parents[x] = this.parents[this.parents[x]]\n x = this.parents[x]\n }\n return x\n }\n find(x) {\n return this.root(x)\n }\n check(x, y) {\n return this.root(x) === this.root(y)\n }\n union(x, y) {\n const [rx, ry] = [this.find(x), this.find(y)]\n if (this.ranks[rx] >= this.ranks[ry]) {\n this.parents[ry] = rx\n this.ranks[rx] += this.ranks[ry]\n } else if (this.ranks[ry] > this.ranks[rx]) {\n this.parents[rx] = ry\n this.ranks[ry] += this.ranks[rx]\n }\n }\n}" ]
1,700
number-of-students-unable-to-eat-lunch
[ "Simulate the given in the statement", "Calculate those who will eat instead of those who will not." ]
/** * @param {number[]} students * @param {number[]} sandwiches * @return {number} */ var countStudents = function(students, sandwiches) { };
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step: If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue. Otherwise, they will leave it and go to the queue's end. This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.   Example 1: Input: students = [1,1,0,0], sandwiches = [0,1,0,1] Output: 0 Explanation: - Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1]. - Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0]. - Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [0,1]. - Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1]. - Front student takes the top sandwich and leaves the line making students = [] and sandwiches = []. Hence all students are able to eat. Example 2: Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1] Output: 3   Constraints: 1 <= students.length, sandwiches.length <= 100 students.length == sandwiches.length sandwiches[i] is 0 or 1. students[i] is 0 or 1.
Easy
[ "array", "stack", "queue", "simulation" ]
[ "const countStudents = function(students, sandwiches) {\n const n = students.length\n let res = n\n while(helper(students, sandwiches)) {\n const len = students.length\n for(let i = 0; i < len; i++) {\n if (students[0] === sandwiches[0]) {\n students.shift()\n sandwiches.shift()\n res--\n } else {\n const tmp = students[0]\n students.shift()\n students.push(tmp)\n }\n }\n }\n return res\n};\n\nfunction helper(stu, san) {\n const n = stu.length\n let res = false\n for(let i = 0; i < n; i++) {\n if (stu[i] === san[0]) {\n return true\n }\n }\n return res\n}" ]
1,701
average-waiting-time
[ "Iterate on the customers, maintaining the time the chef will finish the previous orders.", "If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts.", "Update the running time by the time when the chef starts preparing + preparation time." ]
/** * @param {number[][]} customers * @return {number} */ var averageWaitingTime = function(customers) { };
There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrivali, timei]: arrivali is the arrival time of the ith customer. The arrival times are sorted in non-decreasing order. timei is the time needed to prepare the order of the ith customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input. Return the average waiting time of all customers. Solutions within 10-5 from the actual answer are considered accepted.   Example 1: Input: customers = [[1,2],[2,5],[4,3]] Output: 5.00000 Explanation: 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. Example 2: Input: customers = [[5,2],[5,4],[10,3],[20,1]] Output: 3.25000 Explanation: 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.   Constraints: 1 <= customers.length <= 105 1 <= arrivali, timei <= 104 arrivali <= arrivali+1
Medium
[ "array", "simulation" ]
[ "const averageWaitingTime = function(customers) {\n const n = customers.length\n let start = customers[0][0], end = start + customers[0][1]\n let sum = end - start\n for(let i = 1; i < n; i++) {\n end = end > customers[i][0] ? end + customers[i][1] : customers[i][0] + customers[i][1]\n sum += (end - customers[i][0])\n }\n \n let res = sum / n\n \n return res\n};" ]
1,702
maximum-binary-string-after-change
[ "Note that with the operations, you can always make the string only contain at most 1 zero." ]
/** * @param {string} binary * @return {string} */ var maximumBinaryString = function(binary) { };
You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times: Operation 1: If the number contains the substring "00", you can replace it with "10". For example, "00010" -> "10010" Operation 2: If the number contains the substring "10", you can replace it with "01". For example, "00010" -> "00001" Return the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation.   Example 1: Input: binary = "000110" Output: "111011" Explanation: A valid transformation sequence can be: "000110" -> "000101" "000101" -> "100101" "100101" -> "110101" "110101" -> "110011" "110011" -> "111011" Example 2: Input: binary = "01" Output: "01" Explanation: "01" cannot be transformed any further.   Constraints: 1 <= binary.length <= 105 binary consist of '0' and '1'.
Medium
[ "string", "greedy" ]
null
[]
1,703
minimum-adjacent-swaps-for-k-consecutive-ones
[ "Choose k 1s and determine how many steps are required to move them into 1 group.", "Maintain a sliding window of k 1s, and maintain the steps required to group them.", "When you slide the window across, should you move the group to the right? Once you move the group to the right, it will never need to slide to the left again." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var minMoves = function(nums, k) { };
You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values. Return the minimum number of moves required so that nums has k consecutive 1's.   Example 1: Input: nums = [1,0,0,1,0,1], k = 2 Output: 1 Explanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's. Example 2: Input: nums = [1,0,0,0,0,0,1,1], k = 3 Output: 5 Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1]. Example 3: Input: nums = [1,1,0,1], k = 2 Output: 0 Explanation: nums already has 2 consecutive 1's.   Constraints: 1 <= nums.length <= 105 nums[i] is 0 or 1. 1 <= k <= sum(nums)
Hard
[ "array", "greedy", "sliding-window", "prefix-sum" ]
[ "const minMoves = function (nums, k) {\n const pos = [],\n pre = []\n const n = nums.length,\n { min, floor: fl } = Math\n for (let i = 0; i < n; i++) {\n if (nums[i] === 1) pos.push(i)\n }\n let res = Infinity\n\n pre.push(0)\n for (let i = 0, len = pos.length; i < len; i++) {\n pre.push(pre[i] + pos[i])\n }\n\n for (let i = fl(k / 2), limit = pos.length - fl((k - 1) / 2); i <limit; i++) {\n const lcnt = fl(k / 2),\n rcnt = fl((k - 1) / 2)\n let current =\n lcnt * pos[i] - (pre[i] - pre[i - lcnt]) - (lcnt * (lcnt + 1)) / 2\n current +=\n pre[i + 1 + rcnt] - pre[i + 1] - rcnt * pos[i] - (rcnt * (rcnt + 1)) / 2\n\n res = min(res, current)\n }\n return res\n}", "const minMoves = function (nums, k) {\n if (k === 1) return 0\n let n = 0\n const pos = []\n for (let i = 0; i < nums.length; ++i) {\n if (nums[i]) pos.push(i - n++)\n }\n const sums = []\n sums[0] = pos[0]\n for (let i = 1; i < n; ++i) sums[i] = pos[i] + sums[i - 1]\n let res = Number.MAX_VALUE\n let l = (k / 2) >> 0,\n r = k - l - 1\n for (let i = 0; i + k <= n; ++i) {\n const m = i + ((k / 2) >>> 0)\n const cur =\n pos[m] * l -\n (sums[m - 1] - sums[i] + pos[i]) -\n pos[m] * r +\n sums[i + k - 1] -\n sums[m]\n res = Math.min(cur, res)\n }\n return res\n}" ]
1,704
determine-if-string-halves-are-alike
[ "Create a function that checks if a character is a vowel, either uppercase or lowercase." ]
/** * @param {string} s * @return {boolean} */ var halvesAreAlike = function(s) { };
You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. Return true if a and b are alike. Otherwise, return false.   Example 1: Input: s = "book" Output: true Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. Example 2: Input: s = "textbook" Output: false Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice.   Constraints: 2 <= s.length <= 1000 s.length is even. s consists of uppercase and lowercase letters.
Easy
[ "string", "counting" ]
[ "const halvesAreAlike = function(s) {\n const set = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])\n const n = s.length\n const mid = n / 2\n const first = s.slice(0, mid), second = s.slice(mid)\n return chk(first, set) === chk(second, set)\n};\n\nfunction chk(str, set) {\n let res = 0\n for(let i = 0, len = str.length; i < len; i++) {\n if(set.has(str[i])) res++\n }\n return res\n}" ]
1,705
maximum-number-of-eaten-apples
[ "It's optimal to finish the apples that will rot first before those that will rot last", "You need a structure to keep the apples sorted by their finish time" ]
/** * @param {number[]} apples * @param {number[]} days * @return {number} */ var eatenApples = function(apples, days) { };
There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0. You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n, return the maximum number of apples you can eat.   Example 1: Input: apples = [1,2,3,5,2], days = [3,2,1,4,2] Output: 7 Explanation: You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. Example 2: Input: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2] Output: 5 Explanation: You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day.   Constraints: n == apples.length == days.length 1 <= n <= 2 * 104 0 <= apples[i], days[i] <= 2 * 104 days[i] = 0 if and only if apples[i] = 0.
Medium
[ "array", "greedy", "heap-priority-queue" ]
[ "const eatenApples = function (apples, days) {\n const n = apples.length\n let fin = 0,\n i = 0\n const q = new PriorityQueue()\n while (i < n || !q.isEmpty()) {\n if (i < n && apples[i] > 0) q.push([i + days[i], apples[i]])\n while (!q.isEmpty() && (q.peek()[0] <= i || q.peek()[1] === 0)) q.pop()\n if (!q.isEmpty()) {\n q.peek()[1] -= 1\n if(q.peek()[1] <= 0) q.pop()\n fin += 1\n }\n i += 1\n }\n return fin\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a[0] < b[0]) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}" ]
1,706
where-will-the-ball-fall
[ "Use DFS.", "Traverse the path of the ball downwards until you reach the bottom or get stuck." ]
/** * @param {number[][]} grid * @return {number[]} */ var findBall = function(grid) { };
You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1. A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box.   Example 1: Input: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]] Output: [1,-1,-1,-1,-1] Explanation: This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. Example 2: Input: grid = [[-1]] Output: [-1] Explanation: The ball gets stuck against the left wall. Example 3: Input: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]] Output: [0,1,2,3,4,-1]   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 grid[i][j] is 1 or -1.
Medium
[ "array", "dynamic-programming", "depth-first-search", "matrix", "simulation" ]
[ "const findBall = function (grid) {\n const res = new Array(grid[0].length).fill(0)\n for (let i = 0; i < res.length; i++) {\n let start = i\n let state = 1\n for (let j = 0; j < grid.length; j++) {\n if (grid[j][start] === 1) {\n if (start >= grid[0].length - 1 || grid[j][start + 1] === -1) {\n state = -1\n break\n }\n start++\n } else {\n if (start <= 0 || grid[j][start - 1] == 1) {\n state = -1\n break\n }\n start--\n }\n }\n res[i] = state === -1 ? state : start\n }\n return res\n}" ]
1,707
maximum-xor-with-an-element-from-array
[ "In problems involving bitwise operations, we often think on the bits level. In this problem, we can think that to maximize the result of an xor operation, we need to maximize the most significant bit, then the next one, and so on.", "If there's some number in the array that is less than m and whose the most significant bit is different than that of x, then xoring with this number maximizes the most significant bit, so I know this bit in the answer is 1.", "To check the existence of such numbers and narrow your scope for further bits based on your choice, you can use trie.", "You can sort the array and the queries, and maintain the trie such that in each query the trie consists exactly of the valid elements." ]
/** * @param {number[]} nums * @param {number[][]} queries * @return {number[]} */ var maximizeXor = function(nums, queries) { };
You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi]. The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1. Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.   Example 1: Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]] Output: [3,3,7] Explanation: 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3. 2) 1 XOR 2 = 3. 3) 5 XOR 2 = 7. Example 2: Input: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]] Output: [15,-1,5]   Constraints: 1 <= nums.length, queries.length <= 105 queries[i].length == 2 0 <= nums[j], xi, mi <= 109
Hard
[ "array", "bit-manipulation", "trie" ]
[ "const maximizeXor = function (nums, queries) {\n nums.sort((a, b) => a - b)\n const numOfBits = 1 + Math.floor(Math.log2(nums[nums.length - 1]))\n const maxMask = (1 << numOfBits) - 1\n return queries.map(([x, m]) => query(x, m))\n function query(x, m) {\n if (m < nums[0]) return -1\n let l = 0,\n r = nums.length\n while (l < r) {\n let mid = l + ((r - l) >> 1)\n if (m < nums[mid])r = mid\n else l = mid + 1\n }\n r--\n l = 0\n let ans = x & ~maxMask\n for (let bit = numOfBits - 1; bit >= 0; bit--) {\n const mask = 1 << bit\n if (x & mask) {\n if ((nums[l] & mask) === 0) {\n ans |= 1 << bit\n r = search(l, r, mask) - 1\n }\n } else {\n if (nums[r] & mask) {\n ans |= 1 << bit\n l = search(l, r, mask)\n }\n }\n }\n return ans\n }\n function search(l, r, mask) {\n while (l <= r) {\n const m = l + ((r - l) >> 1)\n if ((nums[m] & mask) === 0) l = m + 1 \n else r = m - 1\n }\n return l\n }\n}", "const maximizeXor = function (nums, queries) {\n const n = queries.length\n const result = new Array(n)\n const trie = [null, null]\n for (let num of nums) {\n let node = trie\n for (let i = 30; i >= 0; i--) {\n const b = 1 << i\n if (b & num) {\n if (!node[1]) node[1] = [null, null]\n node = node[1]\n } else {\n if (!node[0]) node[0] = [null, null]\n node = node[0]\n }\n }\n }\n const min = Math.min(...nums)\n const dfs = (node, num, i, val, max) => {\n if (!node || val > max) return -1\n if (i === -1) return val\n const bit = 1 << i\n i--\n if (bit > max) return dfs(node[0], num, i, val, max)\n if (num & bit) {\n let x = dfs(node[0], num, i, val, max)\n if (x > -1) return x\n return dfs(node[1], num, i, val | bit, max)\n } else {\n let y = dfs(node[1], num, i, val | bit, max)\n if (y > -1) return y\n return dfs(node[0], num, i, val, max)\n }\n }\n\n for (let i = 0; i < n; i++) {\n const [num, max] = queries[i]\n if (max < min) {\n result[i] = -1\n continue\n }\n result[i] = dfs(trie, num, 30, 0, max) ^ num\n }\n return result\n}" ]
1,710
maximum-units-on-a-truck
[ "If we have space for at least one box, it's always optimal to put the box with the most units.", "Sort the box types with the number of units per box non-increasingly.", "Iterate on the box types and take from each type as many as you can." ]
/** * @param {number[][]} boxTypes * @param {number} truckSize * @return {number} */ var maximumUnits = function(boxTypes, truckSize) { };
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: numberOfBoxesi is the number of boxes of type i. numberOfUnitsPerBoxi is the number of units in each box of the type i. You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize. Return the maximum total number of units that can be put on the truck.   Example 1: Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 Output: 8 Explanation: There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8. Example 2: Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 Output: 91   Constraints: 1 <= boxTypes.length <= 1000 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000 1 <= truckSize <= 106
Easy
[ "array", "greedy", "sorting" ]
[ "const maximumUnits = function (boxTypes, truckSize) {\n boxTypes.sort((a, b) => b[1] - a[1])\n let res = 0\n\n for (let i = 0; i < boxTypes.length && truckSize > 0; ++i) {\n let used = Math.min(boxTypes[i][0], truckSize)\n truckSize -= used\n res += used * boxTypes[i][1]\n }\n return res\n}" ]
1,711
count-good-meals
[ "Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values", "You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers" ]
/** * @param {number[]} deliciousness * @return {number} */ var countPairs = function(deliciousness) { };
A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i​​​​​​th​​​​​​​​ item of food, return the number of different good meals you can make from this list modulo 109 + 7. Note that items with different indices are considered different even if they have the same deliciousness value.   Example 1: Input: deliciousness = [1,3,5,7,9] Output: 4 Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. Example 2: Input: deliciousness = [1,1,1,3,3,3,7] Output: 15 Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.   Constraints: 1 <= deliciousness.length <= 105 0 <= deliciousness[i] <= 220
Medium
[ "array", "hash-table" ]
[ "const countPairs = function (deliciousness) {\n const N = deliciousness.length\n deliciousness.sort((a, b) => a - b)\n const mp = {},\n mod = 10 ** 9 + 7\n let ret = 0\n for (let i = 0; i < N; i++) {\n if (deliciousness[i] !== 0) {\n let sum = 1 << (32 - __builtin_clz(deliciousness[i]) - 1)\n ret += mp[sum - deliciousness[i]] || 0\n ret += mp[(sum << 1) - deliciousness[i]] || 0\n if (ret >= mod) ret -= mod\n }\n if (mp[deliciousness[i]] == null) mp[deliciousness[i]] = 0\n mp[deliciousness[i]]++\n }\n return ret\n}\n\nfunction __builtin_clz(num) {\n if (num === 0) return 32\n return 32 - dec2bin(num).length\n}\n\nfunction dec2bin(num) {\n return (num >>> 0).toString(2)\n}" ]
1,712
ways-to-split-array-into-three-subarrays
[ "Create a prefix array to efficiently find the sum of subarrays.", "As we are dividing the array into three subarrays, there are two \"walls\". Iterate over the right wall positions and find where the left wall could be for each right wall position.", "Use binary search to find the left-most position and right-most position the left wall could be." ]
/** * @param {number[]} nums * @return {number} */ var waysToSplit = function(nums) { };
A split of an integer array is good if: The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right. The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right. Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7.   Example 1: Input: nums = [1,1,1] Output: 1 Explanation: The only good way to split nums is [1] [1] [1]. Example 2: Input: nums = [1,2,2,2,5,0] Output: 3 Explanation: There are three good ways of splitting nums: [1] [2] [2,2,5,0] [1] [2,2] [2,5,0] [1,2] [2,2] [5,0] Example 3: Input: nums = [3,2,1] Output: 0 Explanation: There is no good way to split nums.   Constraints: 3 <= nums.length <= 105 0 <= nums[i] <= 104
Medium
[ "array", "two-pointers", "binary-search", "prefix-sum" ]
[ "const waysToSplit = function (nums) {\n const N = nums.length\n let ret = 0\n const presum = Array(N + 1).fill(0), MOD = 10 ** 9 + 7\n for (let i = 0; i < N; i++) presum[i + 1] = presum[i] + nums[i]\n let avg = (presum[N] / 3 + 1) >> 0\n for (let l = 1, m = 2, r = 2; l < N - 1; l++) {\n if (presum[l] > avg) break\n while (m < N && presum[l] > presum[m] - presum[l]) m++\n m = Math.max(m, l + 1)\n if (m > r) r = m\n while (r < N && presum[N] - presum[r] >= presum[r] - presum[l]) r++\n ret += r - m\n if (ret >= MOD) ret -= MOD\n }\n return ret\n}" ]
1,713
minimum-operations-to-make-a-subsequence
[ "The problem can be reduced to computing Longest Common Subsequence between both arrays.", "Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array.", "Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n)." ]
/** * @param {number[]} target * @param {number[]} arr * @return {number} */ var minOperations = function(target, arr) { };
You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr. A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.   Example 1: Input: target = [5,1,3], arr = [9,4,2,3,4] Output: 2 Explanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr. Example 2: Input: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1] Output: 3   Constraints: 1 <= target.length, arr.length <= 105 1 <= target[i], arr[i] <= 109 target contains no duplicates.
Hard
[ "array", "hash-table", "binary-search", "greedy" ]
[ "const minOperations = function(target, arr) {\n const hash = {}\n for (let i = 0, n = target.length; i < n; i++) {\n hash[target[i]] = i\n }\n const stk = []\n for(let e of arr) {\n if(hash[e] == null) continue\n let l = 0, r = stk.length\n while(l < r) {\n const mid = l + (~~((r - l) / 2))\n if(stk[mid] < hash[e]) l = mid + 1\n else r = mid\n }\n stk[l] = hash[e]\n }\n return target.length - stk.length\n};", "const minOperations = function (target, arr) {\n let length1 = target.length,\n length2 = arr.length\n const targetMap = new Map()\n for (let i = 0; i < length1; i++) targetMap.set(target[i], i)\n const list = new Array()\n for (let i = 0; i < length2; i++) {\n let num = arr[i]\n if (targetMap.has(num)) list.push(targetMap.get(num))\n }\n let longestIncreasing = lengthOfLIS(list)\n return target.length - longestIncreasing\n\n function lengthOfLIS(list) {\n let length = 1,\n size = list.length\n if (size == 0) return 0\n const d = new Array(size + 1).fill(0)\n d[length] = list[0]\n for (let i = 1; i < size; ++i) {\n if (list[i] > d[length]) {\n d[++length] = list[i]\n } else {\n let left = 1,\n right = length,\n pos = 0\n while (left <= right) {\n let mid = (left + right) >> 1\n if (d[mid] < list[i]) {\n pos = mid\n left = mid + 1\n } else {\n right = mid - 1\n }\n }\n d[pos + 1] = list[i]\n }\n }\n return length\n }\n}", "const minOperations = function(target, arr) {\n const map = new Map()\n for(let i = 0, len = target.length; i < len; i++) {\n map.set(target[i], i)\n }\n const stack = []\n for(let a of arr) {\n if(!map.has(a)) continue\n if(stack.length === 0 || map.get(a) > stack[stack.length - 1]) {\n stack.push(map.get(a))\n continue\n }\n let left = 0, right = stack.length - 1, mid\n while(left < right) {\n mid = left + ((right - left) >> 1)\n if(stack[mid] < map.get(a)) left = mid + 1\n else right = mid\n }\n stack[left] = map.get(a)\n }\n\n return target.length - stack.length\n};", "const minOperations = function(target, arr) {\n const hash = {}\n for(let i = 0, n = target.length; i < n; i++) {\n hash[target[i]] = i\n }\n const stack = []\n \n for(let e of arr) {\n if(hash[e] == null) continue\n const cur = hash[e]\n if(stack.length && cur > stack[stack.length - 1]) {\n stack.push(cur)\n continue\n }\n \n let l = 0, r = stack.length - 1\n \n while(l < r) {\n const mid = ~~((l + r) / 2)\n if(stack[mid] < cur) {\n l = mid + 1\n } else r = mid\n }\n \n stack[l] = cur\n \n }\n \n return target.length - stack.length\n};" ]
1,716
calculate-money-in-leetcode-bank
[ "Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day." ]
/** * @param {number} n * @return {number} */ var totalMoney = function(n) { };
Hercy wants to save money for his first car. He puts money in the Leetcode bank every day. He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday. Given n, return the total amount of money he will have in the Leetcode bank at the end of the nth day.   Example 1: Input: n = 4 Output: 10 Explanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10. Example 2: Input: n = 10 Output: 37 Explanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. Example 3: Input: n = 20 Output: 96 Explanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.   Constraints: 1 <= n <= 1000
Easy
[ "math" ]
[ "const totalMoney = function(n) {\n let total = 0\n for(let i = 0 ; i < n; i++) {\n const base = (i / 7) >> 0\n const remain = i % 7 + 1\n total += base + remain\n }\n\n return total\n};" ]
1,717
maximum-score-from-removing-substrings
[ "Note that it is always more optimal to take one type of substring before another", "You can use a stack to handle erasures" ]
/** * @param {string} s * @param {number} x * @param {number} y * @return {number} */ var maximumGain = function(s, x, y) { };
You are given a string s and two integers x and y. You can perform two types of operations any number of times. Remove substring "ab" and gain x points. For example, when removing "ab" from "cabxbae" it becomes "cxbae". Remove substring "ba" and gain y points. For example, when removing "ba" from "cabxbae" it becomes "cabxe". Return the maximum points you can gain after applying the above operations on s.   Example 1: Input: s = "cdbcbbaaabab", x = 4, y = 5 Output: 19 Explanation: - Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score. - Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score. - Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score. - Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19. Example 2: Input: s = "aabbaaxybbaabb", x = 5, y = 4 Output: 20   Constraints: 1 <= s.length <= 105 1 <= x, y <= 104 s consists of lowercase English letters.
Medium
[ "string", "stack", "greedy" ]
[ "const maximumGain = function (s, x, y) {\n let sb = s.split('')\n if (x > y) {\n return remove(sb, 'ab', x) + remove(sb, 'ba', y)\n }\n return remove(sb, 'ba', y) + remove(sb, 'ab', x)\n function remove(sb, pattern, point) {\n let i = 0,\n res = 0\n for (let j = 0; j < sb.length; j++) {\n sb[i++] = sb[j]\n if (\n i > 1 &&\n sb[i - 2] == pattern.charAt(0) &&\n sb[i - 1] == pattern.charAt(1)\n ) {\n i -= 2\n res += point\n }\n }\n sb.splice(i)\n return res\n }\n}", "const maximumGain = function (s, x, y) {\n return Math.max(go(s, x, y, 'a', 'b'), go(s, y, x, 'b', 'a'))\n}\n\nfunction go(s, x, y, a, b) {\n const n = s.length\n const st = new Array(n)\n let sc = 0\n let p = 0\n for (let c of s) {\n if (p - 1 >= 0 && st[p - 1] === a && c === b) {\n sc += x\n p--\n } else {\n st[p++] = c\n }\n }\n const st2 = new Array(p)\n let q = 0\n for (let u = 0; u < p; u++) {\n let c = st[u]\n if (q - 1 >= 0 && st2[q - 1] === b && c === a) {\n sc += y\n q--\n } else {\n st2[q++] = c\n }\n }\n return sc\n}" ]
1,718
construct-the-lexicographically-largest-valid-sequence
[ "Heuristic algorithm may work." ]
/** * @param {number} n * @return {number[]} */ var constructDistancedSequence = function(n) { };
Given an integer n, find a sequence that satisfies all of the following: The integer 1 occurs once in the sequence. Each integer between 2 and n occurs twice in the sequence. For every integer i between 2 and n, the distance between the two occurrences of i is exactly i. The distance between two numbers on the sequence, a[i] and a[j], is the absolute difference of their indices, |j - i|. Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution. A sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b. For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5.   Example 1: Input: n = 3 Output: [3,1,2,3,2] Explanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence. Example 2: Input: n = 5 Output: [5,3,1,4,3,5,2,4,2]   Constraints: 1 <= n <= 20
Medium
[ "array", "backtracking" ]
[ "const constructDistancedSequence = function(n) {\n const ans = Array(2 * n - 1).fill(0)\n const used = Array(n + 1).fill(0)\n dfs(ans, 0)\n return ans\n \n function dfs(ans, i) {\n if(i === ans.length) return true\n if(ans[i]) return dfs(ans, i + 1)\n for(let j = used.length - 1; j > 0; j--) {\n if(used[j]) continue\n if(j !== 1 && (i + j >= ans.length || ans[i + j])) continue\n used[j] = 1\n ans[i] = j\n if(j !== 1) ans[i + j] = j\n if(dfs(ans, i + 1)) return true\n ans[i] = 0\n if(j !== 1) ans[i + j] = 0\n used[j] = 0\n }\n return false\n }\n};" ]
1,719
number-of-ways-to-reconstruct-a-tree
[ "Think inductively. The first step is to get the root. Obviously, the root should be in pairs with all the nodes. If there isn't exactly one such node, then there are 0 ways.", "The number of pairs involving a node must be less than or equal to that number of its parent.", "Actually, if it's equal, then there is not exactly 1 way, because they can be swapped.", "Recursively, given a set of nodes, get the node with the most pairs, then this must be a root and have no parents in the current set of nodes." ]
/** * @param {number[][]} pairs * @return {number} */ var checkWays = function(pairs) { };
You are given an array pairs, where pairs[i] = [xi, yi], and: There are no duplicates. xi < yi Let ways be the number of rooted trees that satisfy the following conditions: The tree consists of nodes whose values appeared in pairs. A pair [xi, yi] exists in pairs if and only if xi is an ancestor of yi or yi is an ancestor of xi. Note: the tree does not have to be a binary tree. Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: 0 if ways == 0 1 if ways == 1 2 if ways > 1 A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.   Example 1: Input: pairs = [[1,2],[2,3]] Output: 1 Explanation: There is exactly one valid rooted tree, which is shown in the above figure. Example 2: Input: pairs = [[1,2],[2,3],[1,3]] Output: 2 Explanation: There are multiple valid rooted trees. Three of them are shown in the above figures. Example 3: Input: pairs = [[1,2],[2,3],[2,4],[1,5]] Output: 0 Explanation: There are no valid rooted trees.   Constraints: 1 <= pairs.length <= 105 1 <= xi < yi <= 500 The elements in pairs are unique.
Hard
[ "tree", "graph" ]
[ "class 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}\n\nconst checkWays = function (pairs) {\n const adj = {}\n for (let i = 0; i < pairs.length; i++) {\n if (adj[pairs[i][0]] == null) adj[pairs[i][0]] = new Set()\n if (adj[pairs[i][1]] == null) adj[pairs[i][1]] = new Set()\n adj[pairs[i][0]].add(pairs[i][1])\n adj[pairs[i][1]].add(pairs[i][0])\n }\n\n const q = new PriorityQueue((a, b) => a[0] < b[0])\n Object.keys(adj).forEach((k) => {\n q.push([-adj[k].size, +k])\n })\n\n const n = q.size()\n let multiple = false\n const seen = new Set()\n while (!q.isEmpty()) {\n let [sz, v] = q.peek()\n q.pop()\n sz = -sz\n let u = 0\n let usz = n + 1\n if (seen.size) {\n for (let x of adj[v]) {\n if (adj[x].size < usz && seen.has(x)) {\n u = x\n usz = adj[x].size\n }\n }\n }\n\n seen.add(v)\n if (u === 0) {\n if (sz !== n - 1) {\n return 0\n }\n continue\n }\n\n for (let x of adj[v]) {\n if (x == u) {\n continue\n }\n\n if (!adj[u].has(x)) {\n return 0\n }\n }\n\n if (usz == sz) {\n multiple = true\n }\n }\n\n if (multiple) {\n return 2\n }\n\n return 1\n}" ]
1,720
decode-xored-array
[ "Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i].", "Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i]." ]
/** * @param {number[]} encoded * @param {number} first * @return {number[]} */ var decode = function(encoded, first) { };
There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3]. You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0]. Return the original array arr. It can be proved that the answer exists and is unique.   Example 1: Input: encoded = [1,2,3], first = 1 Output: [1,0,2,1] Explanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3] Example 2: Input: encoded = [6,2,7,3], first = 4 Output: [4,2,0,7,4]   Constraints: 2 <= n <= 104 encoded.length == n - 1 0 <= encoded[i] <= 105 0 <= first <= 105
Easy
[ "array", "bit-manipulation" ]
[ "const decode = function(encoded, first) {\n const res = [first]\n \n for(let i = 0, len = encoded.length; i < len; i++) {\n res[i + 1] = res[i] ^ encoded[i]\n }\n \n return res\n};" ]
1,721
swapping-nodes-in-a-linked-list
[ "We can traverse the linked list and store the elements in an array.", "Upon conversion to an array, we can swap the required elements by indexing the array.", "We can rebuild the linked list using the order of the elements in the array." ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @param {number} k * @return {ListNode} */ var swapNodes = function(head, k) { };
You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).   Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [1,4,3,2,5] Example 2: Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5 Output: [7,9,6,6,8,7,3,0,9,5]   Constraints: The number of nodes in the list is n. 1 <= k <= n <= 105 0 <= Node.val <= 100
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 swapNodes = function(head, k) {\n const dummy = new ListNode()\n dummy.next = head\n const arr = []\n let cur = head\n while(cur) {\n arr.push(cur)\n cur = cur.next\n }\n const n = arr.length\n if(k < 1 || k > n) return dummy.next\n let first = arr[k - 1], second = arr[n - k]\n \n arr[k - 1] = second\n arr[n - k] = first\n \n dummy.next = arr[0]\n let pre = arr[0]\n for(let i = 1, len = arr.length; i < len; i++) {\n const tmp = arr[i]\n pre.next = tmp\n pre = tmp\n }\n \n pre.next = null\n \n return dummy.next\n};" ]
1,722
minimize-hamming-distance-after-swap-operations
[ "The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge.", "Nodes within the same component can be freely swapped with each other.", "For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance." ]
/** * @param {number[]} source * @param {number[]} target * @param {number[][]} allowedSwaps * @return {number} */ var minimumHammingDistance = function(source, target, allowedSwaps) { };
You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order. The Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed). Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source.   Example 1: Input: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]] Output: 1 Explanation: source can be transformed the following way: - Swap indices 0 and 1: source = [2,1,3,4] - Swap indices 2 and 3: source = [2,1,4,3] The Hamming distance of source and target is 1 as they differ in 1 position: index 3. Example 2: Input: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = [] Output: 2 Explanation: There are no allowed swaps. The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. Example 3: Input: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]] Output: 0   Constraints: n == source.length == target.length 1 <= n <= 105 1 <= source[i], target[i] <= 105 0 <= allowedSwaps.length <= 105 allowedSwaps[i].length == 2 0 <= ai, bi <= n - 1 ai != bi
Medium
[ "array", "depth-first-search", "union-find" ]
[ "class UnionFind {\n constructor(n) {\n this.parents = Array(n)\n .fill(0)\n .map((e, i) => i)\n this.ranks = Array(n).fill(0)\n }\n root(x) {\n while (x !== this.parents[x]) {\n this.parents[x] = this.parents[this.parents[x]]\n x = this.parents[x]\n }\n return x\n }\n find(x) {\n return this.root(x)\n }\n check(x, y) {\n return this.root(x) === this.root(y)\n }\n union(x, y) {\n const [rx, ry] = [this.find(x), this.find(y)]\n if (this.ranks[rx] >= this.ranks[ry]) {\n this.parents[ry] = rx\n this.ranks[rx] += this.ranks[ry]\n } else if (this.ranks[ry] > this.ranks[rx]) {\n this.parents[rx] = ry\n this.ranks[ry] += this.ranks[rx]\n }\n }\n}\n\nconst minimumHammingDistance = function (source, target, allowedSwaps) {\n const n = target.length\n const uf = new UnionFind(n)\n for (let A of allowedSwaps) {\n const i = A[0],\n j = A[1]\n uf.union(i, j)\n }\n const M = {}\n for (let i = 0; i < n; i++) {\n const j = uf.find(i)\n if (M[j] == null) M[j] = {}\n if (M[j][source[i]] == null) M[j][source[i]] = 0\n M[j][source[i]]++\n }\n let res = 0\n for (let i = 0; i < n; i++) {\n const j = uf.find(i)\n if (M[j][target[i]]) {\n if (!--M[j][target[i]]) {\n delete M[j][target[i]]\n }\n } else res++\n }\n return res\n}" ]
1,723
find-minimum-time-to-finish-all-jobs
[ "We can select a subset of tasks and assign it to a worker then solve the subproblem on the remaining tasks" ]
/** * @param {number[]} jobs * @param {number} k * @return {number} */ var minimumTimeRequired = function(jobs, k) { };
You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized. Return the minimum possible maximum working time of any assignment.   Example 1: Input: jobs = [3,2,3], k = 3 Output: 3 Explanation: By assigning each person one job, the maximum time is 3. Example 2: Input: jobs = [1,2,4,7,8], k = 2 Output: 11 Explanation: Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11.   Constraints: 1 <= k <= jobs.length <= 12 1 <= jobs[i] <= 107
Hard
[ "array", "dynamic-programming", "backtracking", "bit-manipulation", "bitmask" ]
[ "const minimumTimeRequired = function(jobs, k) {\n const n = jobs.length\n const limit = 1 << n\n const sum = Array(limit).fill(0)\n const { min, max } = Math\n \n for(let mask = 0; mask < limit; mask++) {\n for(let i = 0; i < n; i++) {\n if((mask & (1 << i))) sum[mask] += jobs[i]\n }\n }\n \n const dp = Array.from({ length: k + 1 }, () => Array(limit).fill(0))\n for(let i = 0; i < limit; i++) dp[1][i] = sum[i]\n \n for(let i = 2; i <= k; i++) {\n for(let mask = 0; mask < limit; mask++) {\n dp[i][mask] = dp[i - 1][mask]\n for(let sub = mask; sub; sub = (sub - 1) & mask) {\n dp[i][mask] = min(dp[i][mask], max(dp[i - 1][mask - sub], sum[sub]))\n }\n }\n }\n \n return dp[k][limit - 1]\n};", "const minimumTimeRequired = function(jobs, k) {\n const workers = Array(k).fill(0)\n let res = Infinity\n const n = jobs.length\n\n dfs(0)\n \n return res\n\n function dfs(idx) {\n if(idx === n) {\n res = Math.min(res, Math.max(...workers))\n return\n }\n const e = jobs[idx]\n for(let i = 0; i < k; i++) {\n if(workers[i] + e >= res) continue\n workers[i] += e\n dfs(idx + 1)\n workers[i] -= e\n if(workers[i] === 0) break\n }\n }\n};", "const minimumTimeRequired = function (jobs, k) {\n if (jobs.length <= k) {\n return Math.max(...jobs)\n }\n\n // create a store to hold the number of hours each worker worked\n const workers = new Array(k).fill(0)\n\n let minLongestWorkingTime = Infinity\n const dfs = (i) => {\n if (i === jobs.length) {\n // if we assigned all the jobs, see if we have a better result\n minLongestWorkingTime = Math.min(\n minLongestWorkingTime,\n Math.max(...workers)\n )\n return\n }\n const lengthOfWork = jobs[i]\n\n for (let worker = 0; worker < k; worker++) {\n workers[worker] += lengthOfWork\n\n // if this combination is has a chance of decreasing our\n // answer, try it, otherwise skip it to save on time.\n if (workers[worker] <= minLongestWorkingTime) {\n dfs(i + 1)\n }\n workers[worker] -= lengthOfWork\n\n // We want to minimize the width of the tree\n // so if the worker has gotten their first job\n // don't try any workers after this worker.\n // All other workers after this worker will be 0 as well\n // so the combination is exactly the same.\n if (workers[worker] === 0) break\n }\n }\n\n dfs(0)\n return minLongestWorkingTime\n}", "const minimumTimeRequired = function(jobs, k) {\n return solution(jobs, k)\n};\n\nfunction solution(jobs, k) {\n const n = jobs.length\n let res = Infinity, arr = Array(k).fill(0)\n\n let start = 0\n bt(0)\n return res\n\n function bt(idx) {\n start++\n if(idx === n) {\n res = Math.min(res, Math.max(...arr))\n return\n }\n const visited = new Set()\n for(let j = start; j < start + k; j++) {\n const i = j % k\n if(visited.has(arr[i])) continue\n if(arr[i] + jobs[idx] > res) continue\n visited.add(arr[i])\n arr[i] += jobs[idx]\n bt(idx + 1)\n arr[i] -= jobs[idx]\n }\n } \n}" ]
1,725
number-of-rectangles-that-can-form-the-largest-square
[ "What is the length of the largest square the can be cut out of some rectangle? It'll be equal to min(rectangle.length, rectangle.width). Replace each rectangle with this value.", "Calculate maxSize by iterating over the given rectangles and maximizing the answer with their values denoted in the first hint.", "Then iterate again on the rectangles and calculate the number whose values = maxSize." ]
/** * @param {number[][]} rectangles * @return {number} */ var countGoodRectangles = function(rectangles) { };
You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi. You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4. Let maxLen be the side length of the largest square you can obtain from any of the given rectangles. Return the number of rectangles that can make a square with a side length of maxLen.   Example 1: Input: rectangles = [[5,8],[3,9],[5,12],[16,5]] Output: 3 Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5]. The largest possible square is of length 5, and you can get it out of 3 rectangles. Example 2: Input: rectangles = [[2,3],[3,7],[4,3],[3,7]] Output: 3   Constraints: 1 <= rectangles.length <= 1000 rectangles[i].length == 2 1 <= li, wi <= 109 li != wi
Easy
[ "array" ]
[ "const countGoodRectangles = function(A) {\n const arr = []\n let max = 0\n A.forEach(e => {\n const tmp = Math.min(...e)\n if(tmp > max) max=tmp\n arr.push(tmp)\n })\n let res = 0\n for(let e of arr) {\n if(e >= max) res++\n }\n return res\n};" ]
1,726
tuple-with-same-product
[ "Note that all of the integers are distinct. This means that each time a product is formed it must be formed by two unique integers.", "Count the frequency of each product of 2 distinct numbers. Then calculate the permutations formed." ]
/** * @param {number[]} nums * @return {number} */ var tupleSameProduct = function(nums) { };
Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d.   Example 1: Input: nums = [2,3,4,6] Output: 8 Explanation: There are 8 valid tuples: (2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) (3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2) Example 2: Input: nums = [1,2,4,5,10] Output: 16 Explanation: There are 16 valid tuples: (1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2) (2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1) (2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4) (4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 104 All elements in nums are distinct.
Medium
[ "array", "hash-table" ]
[ "const tupleSameProduct = function(nums) {\n const m = {}\n const len = nums.length\n for(let i = 0; i < len - 1; i++) {\n for(let j = i + 1; j < len; j++) {\n const tmp = nums[i] * nums[j]\n if(m[tmp] == null) m[tmp] = 0\n m[tmp]++\n } \n }\n let res = 0\n Object.keys(m).forEach(e => {\n if(m[e] > 1) res += m[e] * (m[e] - 1) * 4\n })\n \n return res\n};" ]
1,727
largest-submatrix-with-rearrangements
[ "For each column, find the number of consecutive ones ending at each position.", "For each row, sort the cumulative ones in non-increasing order and \"fit\" the largest submatrix." ]
/** * @param {number[][]} matrix * @return {number} */ var largestSubmatrix = function(matrix) { };
You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.   Example 1: Input: matrix = [[0,0,1],[1,1,1],[1,0,1]] Output: 4 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. Example 2: Input: matrix = [[1,0,1,0,1]] Output: 3 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. Example 3: Input: matrix = [[1,1,0],[1,0,1]] Output: 2 Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.   Constraints: m == matrix.length n == matrix[i].length 1 <= m * n <= 105 matrix[i][j] is either 0 or 1.
Medium
[ "array", "greedy", "sorting", "matrix" ]
[ "const largestSubmatrix = function(matrix) {\n const n = matrix.length;\n const m = matrix[0].length;\n const cols = Array(m).fill(0)\n let res = 0\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < m; j++) {\n cols[j] = matrix[i][j] === 1 ? cols[j] + 1 : 0\n }\n const tmp = cols.slice()\n tmp.sort((a, b) => b - a)\n for(let j = 0; j < m; j++) {\n res = Math.max(res, (j + 1) * tmp[j])\n }\n }\n return res\n};" ]
1,728
cat-and-mouse-ii
[ "Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing." ]
/** * @param {string[]} grid * @param {number} catJump * @param {number} mouseJump * @return {boolean} */ var canMouseWin = function(grid, catJump, mouseJump) { };
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a grid of size rows x cols, where each element is a wall, floor, player (Cat, Mouse), or food. Players are represented by the characters 'C'(Cat),'M'(Mouse). Floors are represented by the character '.' and can be walked on. Walls are represented by the character '#' and cannot be walked on. Food is represented by the character 'F' and can be walked on. There is only one of each character 'C', 'M', and 'F' in grid. Mouse and Cat play according to the following rules: Mouse moves first, then they take turns to move. During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the grid. catJump, mouseJump are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. Staying in the same position is allowed. Mouse can jump over Cat. The game can end in 4 ways: If Cat occupies the same position as Mouse, Cat wins. If Cat reaches the food first, Cat wins. If Mouse reaches the food first, Mouse wins. If Mouse cannot get to the food within 1000 turns, Cat wins. Given a rows x cols matrix grid and two integers catJump and mouseJump, return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false.   Example 1: Input: grid = ["####F","#C...","M...."], catJump = 1, mouseJump = 2 Output: true Explanation: Cat cannot catch Mouse on its turn nor can it get the food before Mouse. Example 2: Input: grid = ["M.C...F"], catJump = 1, mouseJump = 4 Output: true Example 3: Input: grid = ["M.C...F"], catJump = 1, mouseJump = 3 Output: false   Constraints: rows == grid.length cols = grid[i].length 1 <= rows, cols <= 8 grid[i][j] consist only of characters 'C', 'M', 'F', '.', and '#'. There is only one of each character 'C', 'M', and 'F' in grid. 1 <= catJump, mouseJump <= 8
Hard
[ "array", "math", "dynamic-programming", "graph", "topological-sort", "memoization", "matrix", "game-theory" ]
[ "const canMouseWin = function(grid, catJump, mouseJump) {\n let n,m,k,lim,cache,mpos = -1, cpos = -1, fpos = -1\n n = grid.length\n m = grid[0].length\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < m; j++) {\n if(grid[i][j] === 'M') mpos = i * m + j\n else if(grid[i][j] === 'C') cpos = i * m + j\n else if(grid[i][j] === 'F') fpos = i * m + j\n }\n }\n mnei = Array(n * m), cnei = Array(n * m)\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < m; j++) {\n mnei[i * m + j] = traj(i, j, mouseJump)\n }\n }\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < m; j++) {\n cnei[i * m + j] = traj(i, j, catJump)\n }\n }\n k = m * n\n lim = 100\n cache = Array.from({ length: lim }, () => Array(k * k).fill(0))\n\n for(let i = 0; i < lim; i++) {\n for(let j = 0; j < k * k; j++) {\n cache[i][j] = -1\n }\n }\n\n return mouseWin(mpos, cpos, 0)\n\n function traj(i, j, d) {\n if(grid[i][j] === '#') return []\n let pos = i * m + j\n let change = []\n change.push(pos)\n for(let k = 1; k < d + 1; k++) {\n if(i + k >= n || grid[i + k][j] === '#') break\n change.push(pos + k * m)\n }\n for(let k = 1; k < d + 1; k++) {\n if(i - k < 0 || grid[i - k][j] === '#') break\n change.push(pos - k * m) \n }\n for(let k = 1; k < d + 1; k++) {\n if(j + k >= m || grid[i][j + k] === '#') break\n change.push(pos + k)\n }\n for(let k = 1; k < d + 1; k++) {\n if(j - k < 0 || grid[i][j - k] === '#') break\n change.push(pos - k)\n }\n return change\n }\n \n function mouseWin(mpos, cpos, turn) {\n if(turn === lim) return false\n let e = mpos * k + cpos\n if(cache[turn][e] >= 0) return cache[turn][e] === 1\n if(cpos === fpos || cpos === mpos) return false\n if(mpos === fpos) return true\n if((turn & 1) !== 0) {\n let b = 0\n for(let newCpos of cnei[cpos]) {\n if(!mouseWin(mpos, newCpos, turn + 1)) b = 1\n }\n if(b===0) cache[turn][e] = 1\n else cache[turn][e] = 0\n } else {\n let b = 0\n for(let newMpos of mnei[mpos]) {\n if(mouseWin(newMpos, cpos, turn + 1)) b = 1\n }\n if(b === 1) cache[turn][e] = 1\n else cache[turn][e] = 0\n }\n return cache[turn][e] === 1\n }\n};" ]
1,732
find-the-highest-altitude
[ "Let's note that the altitude of an element is the sum of gains of all the elements behind it", "Getting the altitudes can be done by getting the prefix sum array of the given array" ]
/** * @param {number[]} gain * @return {number} */ var largestAltitude = function(gain) { };
There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0. You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i​​​​​​ and i + 1 for all (0 <= i < n). Return the highest altitude of a point.   Example 1: Input: gain = [-5,1,5,0,-7] Output: 1 Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. Example 2: Input: gain = [-4,-3,-2,-1,4,3,2] Output: 0 Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.   Constraints: n == gain.length 1 <= n <= 100 -100 <= gain[i] <= 100
Easy
[ "array", "prefix-sum" ]
[ "const largestAltitude = function(gain) {\n const h = [0]\n for(let e of gain) {\n h.push(h[h.length - 1] + e)\n }\n let max = 0\n for(let e of h) {\n max = Math.max(max, e)\n }\n return max\n};" ]
1,733
minimum-number-of-people-to-teach
[ "You can just use brute force and find out for each language the number of users you need to teach", "Note that a user can appear in multiple friendships but you need to teach that user only once" ]
/** * @param {number} n * @param {number[][]} languages * @param {number[][]} friendships * @return {number} */ var minimumTeachings = function(n, languages, friendships) { };
On a social network consisting of m users and some friendships between users, two users can communicate with each other if they know a common language. You are given an integer n, an array languages, and an array friendships where: There are n languages numbered 1 through n, languages[i] is the set of languages the i​​​​​​th​​​​ user knows, and friendships[i] = [u​​​​​​i​​​, v​​​​​​i] denotes a friendship between the users u​​​​​​​​​​​i​​​​​ and vi. You can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach. Note that friendships are not transitive, meaning if x is a friend of y and y is a friend of z, this doesn't guarantee that x is a friend of z.   Example 1: Input: n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]] Output: 1 Explanation: You can either teach user 1 the second language or user 2 the first language. Example 2: Input: n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]] Output: 2 Explanation: Teach the third language to users 1 and 3, yielding two users to teach.   Constraints: 2 <= n <= 500 languages.length == m 1 <= m <= 500 1 <= languages[i].length <= n 1 <= languages[i][j] <= n 1 <= u​​​​​​i < v​​​​​​i <= languages.length 1 <= friendships.length <= 500 All tuples (u​​​​​i, v​​​​​​i) are unique languages[i] contains only unique values
Medium
[ "array", "greedy" ]
[ "var minimumTeachings = function(n, languages, friendships) {\n let cnt_people = languages.length;\n\n const knows = Array.from({length: cnt_people}, () => Array(n).fill(0))\n for(let who = 0; who < cnt_people; ++who) {\n for(let x of languages[who]) {\n knows[who][x-1] = true;\n }\n }\n let req = Array(n).fill(0);\n let s = new Set();\n for(let edge of friendships) {\n let a = edge[0] - 1;\n let b = edge[1] - 1;\n let yes = false;\n for(let x of languages[a]) {\n if(knows[b][x-1]) {\n yes = true;\n }\n }\n if(yes) {\n continue;\n }\n s.add(a);\n s.add(b);\n }\n let best = Infinity;\n for(let i = 0; i < n; ++i) {\n let needed = 0;\n for(let person of s) {\n if(!knows[person][i]) {\n needed++;\n }\n }\n best = Math.min(best, needed);\n }\n return best; \n};" ]
1,734
decode-xored-permutation
[ "Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x.", "Think why n is odd.", "perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ...", "perm[i] = perm[i-1] XOR encoded[i-1]" ]
/** * @param {number[]} encoded * @return {number[]} */ var decode = function(encoded) { };
There is an integer array perm that is a permutation of the first n positive integers, where n is always odd. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1]. Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.   Example 1: Input: encoded = [3,1] Output: [1,2,3] Explanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1] Example 2: Input: encoded = [6,5,4,6] Output: [2,4,1,5,3]   Constraints: 3 <= n < 105 n is odd. encoded.length == n - 1
Medium
[ "array", "bit-manipulation" ]
[ "const decode = function(encoded) {\n const n = encoded.length + 1\n let xor = 0\n for(let i = 1; i <= n; i++) xor ^= i\n for(let i = 1; i < n - 1; i += 2) xor ^= encoded[i]\n const res = [xor]\n let pre = xor\n for(let i = 0; i < n - 1; i++) {\n res.push(encoded[i] ^ pre)\n pre = res[res.length - 1]\n }\n \n return res\n};", "const decode = function(encoded) {\n let a = 0\n const n = encoded.length + 1\n for(let i = 0; i <= n; i++) {\n a ^= i\n if(i < n && i % 2 === 1) a ^= encoded[i]\n }\n const res = [a]\n for(let i = 0; i < n - 1; i++) {\n res[i + 1] = res[i] ^ encoded[i]\n }\n \n return res\n};", "const decode = function(A) {\n let xor = 0\n const len = A.length\n const permLen = len + 1\n for(let i = 1; i <= permLen; i++) {\n xor ^= i\n }\n // except first\n for(let i = 1; i < len; i += 2) xor ^= A[i]\n const first = xor\n const res = [xor]\n let pre = xor\n for(let i = 1; i < permLen; i++) {\n res[i] = A[i - 1] ^ pre\n pre = res[i]\n }\n return res; \n};" ]
1,735
count-ways-to-make-array-with-product
[ "Prime-factorize ki and count how many ways you can distribute the primes among the ni positions.", "After prime factorizing ki, suppose there are x amount of prime factor. There are (x + n - 1) choose (n - 1) ways to distribute the x prime factors into k positions, allowing repetitions." ]
/** * @param {number[][]} queries * @return {number[]} */ var waysToFillArray = function(queries) { };
You are given a 2D integer array, queries. For each queries[i], where queries[i] = [ni, ki], find the number of different ways you can place positive integers into an array of size ni such that the product of the integers is ki. As the number of ways may be too large, the answer to the ith query is the number of ways modulo 109 + 7. Return an integer array answer where answer.length == queries.length, and answer[i] is the answer to the ith query.   Example 1: Input: queries = [[2,6],[5,1],[73,660]] Output: [4,1,50734910] Explanation: Each query is independent. [2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1]. [5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1]. [73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910. Example 2: Input: queries = [[1,1],[2,2],[3,3],[4,4],[5,5]] Output: [1,2,3,10,5]   Constraints: 1 <= queries.length <= 104 1 <= ni, ki <= 104
Hard
[ "array", "math", "dynamic-programming", "combinatorics", "number-theory" ]
[ "var waysToFillArray = function (queries) {\n const nax = 10123\n const C = Array.from({ length: nax }, () => Array(15).fill(0n))\n const mod = BigInt(10 ** 9 + 7)\n if (C[1][1] == 0n) {\n for (let i = 0; i < nax; ++i) {\n C[i][0] = 1n\n if (i < 15) {\n C[i][i] = 1n\n }\n for (let j = 1; j < i && j < 15; ++j) {\n C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod\n }\n }\n }\n const answer = []\n for (let query of queries) {\n let n = query[0]\n let k = query[1]\n let total = 1n\n const consider = (cnt) => {\n total = (total * C[n + cnt - 1][cnt]) % mod\n }\n for (let i = 2; i * i <= k; ++i) {\n if (k % i == 0) {\n let cnt = 0\n while (k % i == 0) {\n k = (k / i) >> 0\n cnt++\n }\n consider(cnt)\n }\n }\n if (k != 1) {\n consider(1)\n }\n answer.push(total)\n }\n return answer\n}" ]
1,736
latest-time-by-replacing-hidden-digits
[ "Trying out all possible solutions from biggest to smallest would fit in the time limit.", "To check if the solution is okay, you need to find out if it's valid and matches every character" ]
/** * @param {string} time * @return {string} */ var maximumTime = function(time) { };
You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?). The valid times are those inclusively between 00:00 and 23:59. Return the latest valid time you can get from time by replacing the hidden digits.   Example 1: Input: time = "2?:?0" Output: "23:50" Explanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50. Example 2: Input: time = "0?:3?" Output: "09:39" Example 3: Input: time = "1?:22" Output: "19:22"   Constraints: time is in the format hh:mm. It is guaranteed that you can produce a valid time from the given string.
Easy
[ "string", "greedy" ]
[ "var maximumTime = function(time) {\n const arr = time.split('')\n let idx = time.indexOf('?')\n if(idx < 0) return time\n while(arr.indexOf('?') >= 0) {\n idx = arr.indexOf('?')\n let e\n if(idx === 0) {\n if(time[1] === '?') e = 2\n else if(+time[1] < 4) e =2\n else e = 1\n arr[0] = '' + e\n\n } else if(idx === 1) {\n if(+arr[0] > 1) e = 3\n else e = 9\n arr[1] = '' + e\n } else if(idx === 3) {\n e = 5\n arr[3] = '' + e\n } else if(idx === 4) {\n e = 9\n arr[4] = '' + e\n } \n }\n\n return arr.join('')\n};" ]
1,737
change-minimum-characters-to-satisfy-one-of-three-conditions
[ "Iterate on each letter in the alphabet, and check the smallest number of operations needed to make it one of the following: the largest letter in a and smaller than the smallest one in b, vice versa, or let a and b consist only of this letter.", "For the first 2 conditions, take care that you can only change characters to lowercase letters, so you can't make 'z' the smallest letter in one of the strings or 'a' the largest letter in one of them." ]
/** * @param {string} a * @param {string} b * @return {number} */ var minCharacters = function(a, b) { };
You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter. Your goal is to satisfy one of the following three conditions: Every letter in a is strictly less than every letter in b in the alphabet. Every letter in b is strictly less than every letter in a in the alphabet. Both a and b consist of only one distinct letter. Return the minimum number of operations needed to achieve your goal.   Example 1: Input: a = "aba", b = "caa" Output: 2 Explanation: Consider the best way to make each condition true: 1) Change b to "ccc" in 2 operations, then every letter in a is less than every letter in b. 2) Change a to "bbb" and b to "aaa" in 3 operations, then every letter in b is less than every letter in a. 3) Change a to "aaa" and b to "aaa" in 2 operations, then a and b consist of one distinct letter. The best way was done in 2 operations (either condition 1 or condition 3). Example 2: Input: a = "dabadd", b = "cda" Output: 3 Explanation: The best way is to make condition 1 true by changing b to "eee".   Constraints: 1 <= a.length, b.length <= 105 a and b consist only of lowercase letters.
Medium
[ "hash-table", "string", "counting", "prefix-sum" ]
[ "const minCharacters = function (a, b) {\n const n1 = a.length,\n n2 = b.length\n const cnt1 = Array(26).fill(0)\n const cnt2 = Array(26).fill(0)\n const aCode = 'a'.charCodeAt(0)\n for (let c of a) ++cnt1[c.charCodeAt(0) - aCode]\n for (let c of b) ++cnt2[c.charCodeAt(0) - aCode]\n let res = n1 - Math.max(...cnt1) + n2 - Math.max(...cnt2)\n for (let i = 0; i < 25; ++i) {\n let cur1 = 0,\n cur2 = 0\n for (let j = 0; j < 26; ++j) {\n if (j <= i) {\n cur1 += cnt2[j]\n cur2 += cnt1[j]\n } else {\n cur1 += cnt1[j]\n cur2 += cnt2[j]\n }\n }\n res = Math.min(Math.min(cur1, cur2), res)\n }\n return res\n}", "const minCharacters = function(a, b) {\n return Math.min(method1(a, b), method1(b, a), method3(a, b))\n};\n\nfunction method1(str1, str2) {\n let res = Infinity, a = 'a'.charCodeAt(0)\n for(let i = 1; i < 26; i++) {\n let cnt1 = 0, cnt2 = 0, mid = String.fromCharCode(a + i)\n for(let ch of str1) {\n if(ch >= mid) cnt1++ \n }\n for(let ch of str2) {\n if(ch < mid) cnt2++\n }\n res = Math.min(res, cnt1 + cnt2)\n }\n return res\n}\n\nfunction method3(str1, str2) {\n const a = 'a'.charCodeAt(0)\n const cnt1 = Array(26).fill(0), cnt2 = Array(26).fill(0)\n for(let ch of str1) cnt1[ch.charCodeAt(0) - a]++\n for(let ch of str2) cnt2[ch.charCodeAt(0) - a]++\n return str1.length + str2.length - Math.max(...cnt1) - Math.max(...cnt2)\n}", "const minCharacters = function (a, b) {\n const m = a.length, n = b.length\n let res = m + n\n const cnt1 = Array(26).fill(0), cnt2 = Array(26).fill(0)\n const ac = 'a'.charCodeAt(0)\n for(let ch of a) cnt1[ch.charCodeAt(0) - ac]++\n for(let ch of b) cnt2[ch.charCodeAt(0) - ac]++\n const c3 = res - Math.max(...cnt1) - Math.max(...cnt2)\n for(let i = 0; i < 26; i++) {\n if(i > 0) {\n cnt1[i] += cnt1[i - 1]\n cnt2[i] += cnt2[i - 1] \n }\n\n if(i < 25) {\n res = Math.min(res, m - cnt1[i] + cnt2[i])\n res = Math.min(res, n - cnt2[i] + cnt1[i])\n }\n }\n \n return Math.min(res, c3)\n}" ]
1,738
find-kth-largest-xor-coordinate-value
[ "Use a 2D prefix sum to precalculate the xor-sum of the upper left submatrix." ]
/** * @param {number[][]} matrix * @param {number} k * @return {number} */ var kthLargestValue = function(matrix, k) { };
You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k. The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed). Find the kth largest value (1-indexed) of all the coordinates of matrix.   Example 1: Input: matrix = [[5,2],[1,6]], k = 1 Output: 7 Explanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value. Example 2: Input: matrix = [[5,2],[1,6]], k = 2 Output: 5 Explanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value. Example 3: Input: matrix = [[5,2],[1,6]], k = 3 Output: 4 Explanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.   Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 1000 0 <= matrix[i][j] <= 106 1 <= k <= m * n
Medium
[ "array", "divide-and-conquer", "bit-manipulation", "heap-priority-queue", "matrix", "prefix-sum", "quickselect" ]
[ "var kthLargestValue = function(matrix, k) {\n let m = matrix.length;\n let n = matrix[0].length;\n const v = [], d = Array(n).fill(0);\n d[0] = matrix[0][0];\n v.push(d[0]);\n for (let i = 1; i < n; ++i) {\n d[i] = matrix[0][i] ^ d[i - 1];\n v.push(d[i]);\n }\n for (let i = 1; i < m; ++i) {\n let cur = matrix[i][0];\n d[0] ^= cur;\n v.push(d[0]);\n for (let j = 1; j < n; ++j) {\n cur ^= matrix[i][j];\n d[j] ^= cur;\n v.push(d[j]);\n }\n }\n v.sort((a, b) => b - a)\n return v[k - 1];\n};", "const kthLargestValue = function(matrix, k) {\n const tmp = []\n const n = matrix.length, m = matrix[0].length\n const dp = Array.from({ length: n }, () => Array(m).fill(0))\n dp[0][0] = matrix[0][0]\n tmp.push(dp[0][0])\n for(let j = 1; j < m; j++) {\n dp[0][j] = dp[0][j - 1] ^ matrix[0][j]\n tmp.push(dp[0][j])\n }\n for(let i = 1; i < n; i++) {\n dp[i][0] = dp[i - 1][0] ^ matrix[i][0]\n tmp.push(dp[i][0])\n }\n for(let i = 1; i < n; i++) {\n for(let j = 1; j < m; j++) {\n dp[i][j] = dp[i][j - 1] ^ dp[i - 1][j] ^ matrix[i][j] ^ dp[i - 1][j - 1]\n tmp.push(dp[i][j])\n }\n }\n tmp.sort((a, b) => b - a)\n return tmp[k - 1]\n};", "const kthLargestValue = function(matrix, k) {\n if(matrix == null || matrix[0] == null) return 0\n const m = matrix.length, n = matrix[0].length\n const res = Array.from({ length: m }, () => Array(n).fill(0))\n res[0][0] = matrix[0][0]\n for(let i = 1; i < m; i++) {\n res[i][0] = res[i - 1][0] ^ matrix[i][0]\n }\n for(let j = 1; j < n; j++) {\n res[0][j] = res[0][j - 1] ^ matrix[0][j]\n }\n \n for(let i = 1; i < m; i++) {\n for(let j = 1; j < n; j++) {\n res[i][j] = res[i][j - 1] ^ res[i - 1][j] ^ res[i - 1][j - 1] ^ matrix[i][j]\n }\n }\n \n const pq = new PriorityQueue((a, b) => a < b)\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n pq.push(res[i][j])\n if(pq.size() > k) pq.pop()\n }\n }\n \n return pq.pop()\n \n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}" ]
1,739
building-boxes
[ "Suppose We can put m boxes on the floor, within all the ways to put the boxes, what’s the maximum number of boxes we can put in?", "The first box should always start in the corner" ]
/** * @param {number} n * @return {number} */ var minimumBoxes = function(n) { };
You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: You can place the boxes anywhere on the floor. If box x is placed on top of the box y, then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall. Given an integer n, return the minimum possible number of boxes touching the floor.   Example 1: Input: n = 3 Output: 3 Explanation: The figure above is for the placement of the three boxes. These boxes are placed in the corner of the room, where the corner is on the left side. Example 2: Input: n = 4 Output: 3 Explanation: The figure above is for the placement of the four boxes. These boxes are placed in the corner of the room, where the corner is on the left side. Example 3: Input: n = 10 Output: 6 Explanation: The figure above is for the placement of the ten boxes. These boxes are placed in the corner of the room, where the corner is on the back side.   Constraints: 1 <= n <= 109
Hard
[ "math", "binary-search", "greedy" ]
[ "const minimumBoxes = function(n) {\n let i = 1, c = 1, s = 1\n while(s < n) {\n i += 1, c += i, s += c\n }\n while(s - i >= n) {\n s -= i, c -= 1, i -= 1\n }\n return c\n};", "const minimumBoxes = function(n) {\n let sum = 1n, base = 1n, row = 1n;\n n = BigInt(n)\n while (sum < n) {\n base += (++row);\n sum += base;\n }\n while (sum > n) {\n --base;\n sum -= (row--);\n if (sum < n) return base + 1n;\n }\n return base;\n};" ]
1,742
maximum-number-of-balls-in-a-box
[ "Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them", "You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number" ]
/** * @param {number} lowLimit * @param {number} highLimit * @return {number} */ var countBalls = function(lowLimit, highLimit) { };
You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls.   Example 1: Input: lowLimit = 1, highLimit = 10 Output: 2 Explanation: Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... Box 1 has the most number of balls with 2 balls. Example 2: Input: lowLimit = 5, highLimit = 15 Output: 2 Explanation: Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... Boxes 5 and 6 have the most number of balls with 2 balls in each. Example 3: Input: lowLimit = 19, highLimit = 28 Output: 2 Explanation: Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... Box 10 has the most number of balls with 2 balls.   Constraints: 1 <= lowLimit <= highLimit <= 105
Easy
[ "hash-table", "math", "counting" ]
[ "const countBalls = function(lowLimit, highLimit) {\n const m = {}\n for(let i = lowLimit; i <= highLimit; i++) {\n const tmp = (i + '').split('').map(e => +e).reduce((ac, e) => ac + e, 0)\n if(m[tmp] == null) m[tmp] = 0\n m[tmp]++\n }\n const arr = Object.values(m)\n arr.sort((a, b) => b - a)\n return arr[0]\n};" ]
1,743
restore-the-array-from-adjacent-pairs
[ "Find the first element of nums - it will only appear once in adjacentPairs.", "The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element." ]
/** * @param {number[][]} adjacentPairs * @return {number[]} */ var restoreArray = function(adjacentPairs) { };
There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums. You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums. It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order. Return the original array nums. If there are multiple solutions, return any of them.   Example 1: Input: adjacentPairs = [[2,1],[3,4],[3,2]] Output: [1,2,3,4] Explanation: This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs[i] may not be in left-to-right order. Example 2: Input: adjacentPairs = [[4,-2],[1,4],[-3,1]] Output: [-2,4,1,-3] Explanation: There can be negative numbers. Another solution is [-3,1,4,-2], which would also be accepted. Example 3: Input: adjacentPairs = [[100000,-100000]] Output: [100000,-100000]   Constraints: nums.length == n adjacentPairs.length == n - 1 adjacentPairs[i].length == 2 2 <= n <= 105 -105 <= nums[i], ui, vi <= 105 There exists some nums that has adjacentPairs as its pairs.
Medium
[ "array", "hash-table" ]
[ "const restoreArray = function(pairs) {\n const m = {}\n for(let e of pairs) {\n const [k, v] = e\n if(m[k] == null) m[k] = new Set()\n if(m[v] == null) m[v] = new Set()\n m[k].add(v)\n m[v].add(k)\n }\n const q = [pairs[0]]\n let res = pairs[0]\n m[res[0]].delete(res[1])\n m[res[1]].delete(res[0])\n let n = pairs.length\n while(n) {\n const front = res[0], rear = res[res.length - 1]\n \n if(m[front]) {\n const newf = [...m[front].values()][0]\n if(m[front].size) res.unshift(newf)\n if(m[front]) m[front].delete(newf)\n if(m[newf]) m[newf].delete(front)\n if(m[front].size === 0) delete m[front]\n }\n \n if(m[rear]) {\n const newr = [...m[rear].values()][0]\n if(m[rear].size) res.push(newr)\n if(m[rear]) m[rear].delete(newr)\n if(m[newr]) m[newr].delete(rear)\n if(m[rear].size === 0) delete m[rear]\n }\n n--\n }\n \n return res\n};" ]
1,744
can-you-eat-your-favorite-candy-on-your-favorite-day
[ "The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy.", "To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day.", "The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1.", "The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap." ]
/** * @param {number[]} candiesCount * @param {number[][]} queries * @return {boolean[]} */ var canEat = function(candiesCount, queries) { };
You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have. You are also given a 2D array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]. You play a game with the following rules: You start eating candies on day 0. You cannot eat any candy of type i unless you have eaten all candies of type i - 1. You must eat at least one candy per day until you have eaten all the candies. Construct a boolean array answer such that answer.length == queries.length and answer[i] is true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi candies on any day, and false otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return the constructed array answer.   Example 1: Input: candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]] Output: [true,false,true] Explanation: 1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2. 2- You can eat at most 4 candies each day. If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1. On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2. 3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13. Example 2: Input: candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]] Output: [false,true,true,false,false]   Constraints: 1 <= candiesCount.length <= 105 1 <= candiesCount[i] <= 105 1 <= queries.length <= 105 queries[i].length == 3 0 <= favoriteTypei < candiesCount.length 0 <= favoriteDayi <= 109 1 <= dailyCapi <= 109
Medium
[ "array", "prefix-sum" ]
[ "const canEat = function(candiesCount, queries) {\n const n = candiesCount.length\n const pre = Array(n).fill(0)\n for(let i = 1; i < n; i++) {\n pre[i] = pre[i - 1] + candiesCount[i - 1]\n }\n return queries.map((e, i) => {\n const [t, d, c] = e\n const num = candiesCount[t]\n const min = d, max = (d + 1) * c\n\n if(pre[t] + num > min && pre[t] < max) {\n return true\n } else {\n return false\n }\n })\n};" ]
1,745
palindrome-partitioning-iv
[ "Preprocess checking palindromes in O(1)", "Note that one string is a prefix and another one is a suffix you can try brute forcing the rest" ]
/** * @param {string} s * @return {boolean} */ var checkPartitioning = function(s) { };
Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.​​​​​ A string is said to be palindrome if it the same string when reversed.   Example 1: Input: s = "abcbdd" Output: true Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes. Example 2: Input: s = "bcbddxy" Output: false Explanation: s cannot be split into 3 palindromes.   Constraints: 3 <= s.length <= 2000 s​​​​​​ consists only of lowercase English letters.
Hard
[ "string", "dynamic-programming" ]
[ "const checkPartitioning = function(s) {\n const map = manacher(s);\n return checkPartitioningDfs(map, s, 0);\n};\n\nfunction checkPartitioningDfs(map, word, i, path = []) {\n if (path.length > 3) return false;\n if (path.length == 3 && path.join('') == word) return true;\n let found = false;\n const length = map.get(i);\n path.push(word.substr(i, length));\n found = found || checkPartitioningDfs(map, word, i + length, path);\n path.pop();\n\n path.push(word.substr(i, 1));\n found = found || checkPartitioningDfs(map, word, i + 1, path);\n path.pop();\n \n return found;\n}\n\nfunction manacher(s) {\n const t = '^#' + s.split('').join('#') + '#$';\n let r = 0;\n let c = 0;\n let maxC = 0;\n const rad = new Array(t.length).fill(0);\n for (let i = 1; i < t.length - 1; ++i) {\n if (r > i) rad[i] = Math.min(rad[2 * c - i], r - i);\n while (t[i - rad[i] - 1] == t[i + rad[i] + 1]) rad[i]++;\n if (i + rad[i] > r) {\n c = i;\n r = i + rad[i];\n }\n if (rad[c] > rad[maxC]) maxC = c;\n }\n const ans = new Map();\n for (let i = 0; i < rad.length; ++i) {\n if (rad[i] > 0) {\n ans.set((i - rad[i] - 1) >>> 1, rad[i]);\n }\n }\n return ans;\n}", "const checkPartitioning = function (s) {\n const n = s.length\n const dp = Array.from({ length: n }, () => Array(n).fill(false))\n for(let i = n - 1; i >= 0; i--) {\n for(let j = i; j < n; j++) {\n if(s[i] === s[j]) {\n dp[i][j] = i + 1 <= j - 1 ? dp[i + 1][j - 1] : true\n } else dp[i][j] = false\n }\n }\n for(let i = 1; i < n - 1; i++) {\n for(let j = i; j < n - 1; j++) {\n if(dp[0][i - 1] && dp[i][j] && dp[j + 1][n - 1]) return true\n }\n }\n return false\n}", "const checkPartitioning = function(s) {\n for(let i = 1, len = s.length; i < len - 1; i++) {\n for(let j = i + 1; j < len; j++) {\n const s1 = s.slice(0, i), s2 = s.slice(i, j), s3 = s.slice(j)\n if(chk(s1) && chk(s2) && chk(s3)) return true\n }\n }\n return false\n};\n\nfunction chk(s) {\n let l = 0, r = s.length - 1\n for(;l <= r;) {\n if(s[l] === s[r]) {\n l++\n r--\n } else return false\n }\n return true\n}" ]
1,748
sum-of-unique-elements
[ "Use a dictionary to count the frequency of each number." ]
/** * @param {number[]} nums * @return {number} */ var sumOfUnique = function(nums) { };
You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array. Return the sum of all the unique elements of nums.   Example 1: Input: nums = [1,2,3,2] Output: 4 Explanation: The unique elements are [1,3], and the sum is 4. Example 2: Input: nums = [1,1,1,1,1] Output: 0 Explanation: There are no unique elements, and the sum is 0. Example 3: Input: nums = [1,2,3,4,5] Output: 15 Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.   Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100
Easy
[ "array", "hash-table", "counting" ]
[ "const sumOfUnique = function(nums) {\n const m = {}\n for(let e of nums) {\n if(m[e] == null) m[e] = 0\n m[e]++\n }\n let res = 0\n // console.log(m)\n Object.entries(m).forEach(e => {\n const [k, v] = e\n if(v === 1) res += +k\n })\n return res\n};" ]
1,749
maximum-absolute-sum-of-any-subarray
[ "What if we asked for maximum sum, not absolute sum?", "It's a standard problem that can be solved by Kadane's algorithm.", "The key idea is the max absolute sum will be either the max sum or the min sum.", "So just run kadane twice, once calculating the max sum and once calculating the min sum." ]
/** * @param {number[]} nums * @return {number} */ var maxAbsoluteSum = function(nums) { };
You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr). Return the maximum absolute sum of any (possibly empty) subarray of nums. Note that abs(x) is defined as follows: If x is a negative integer, then abs(x) = -x. If x is a non-negative integer, then abs(x) = x.   Example 1: Input: nums = [1,-3,2,3,-4] Output: 5 Explanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5. Example 2: Input: nums = [2,-5,1,-4,3,-2] Output: 8 Explanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.   Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104
Medium
[ "array", "dynamic-programming" ]
[ "const maxAbsoluteSum = function (nums) {\n let min = 0,\n max = 0,\n sum = 0\n for(let e of nums) {\n sum += e\n min = Math.min(sum, min)\n max = Math.max(sum, max)\n }\n return max - min\n}", "const maxAbsoluteSum = function (nums) {\n let min = Infinity,\n max = -Infinity\n let positiveSum = 0,\n negativeSum = 0\n for (let num of nums) {\n positiveSum += num\n if (positiveSum > max) {\n max = positiveSum\n }\n\n if (positiveSum < 0) {\n positiveSum = 0\n }\n negativeSum += num\n if (negativeSum < min) {\n min = negativeSum\n }\n if (negativeSum > 0) {\n negativeSum = 0\n }\n }\n\n return Math.max(Math.abs(min), max)\n}" ]
1,750
minimum-length-of-string-after-deleting-similar-ends
[ "If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can.", "Note that if the length is equal 1 the answer is 1" ]
/** * @param {string} s * @return {number} */ var minimumLength = function(s) { };
Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times: Pick a non-empty prefix from the string s where all the characters in the prefix are equal. Pick a non-empty suffix from the string s where all the characters in this suffix are equal. The prefix and the suffix should not intersect at any index. The characters from the prefix and suffix must be the same. Delete both the prefix and the suffix. Return the minimum length of s after performing the above operation any number of times (possibly zero times).   Example 1: Input: s = "ca" Output: 2 Explanation: You can't remove any characters, so the string stays as is. Example 2: Input: s = "cabaabac" Output: 0 Explanation: An optimal sequence of operations is: - Take prefix = "c" and suffix = "c" and remove them, s = "abaaba". - Take prefix = "a" and suffix = "a" and remove them, s = "baab". - Take prefix = "b" and suffix = "b" and remove them, s = "aa". - Take prefix = "a" and suffix = "a" and remove them, s = "". Example 3: Input: s = "aabccabba" Output: 3 Explanation: An optimal sequence of operations is: - Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb". - Take prefix = "b" and suffix = "bb" and remove them, s = "cca".   Constraints: 1 <= s.length <= 105 s only consists of characters 'a', 'b', and 'c'.
Medium
[ "two-pointers", "string" ]
[ "const minimumLength = function(s) {\n const n = s.length\n let l = 0, r = n - 1\n while(l < r && s[l] === s[r]) {\n while(l < r - 1 && s[r] === s[r - 1]) r--\n while(l + 1 < r && s[l] === s[l + 1]) l++\n l++\n r--\n }\n return r - l + 1\n};" ]
1,751
maximum-number-of-events-that-can-be-attended-ii
[ "Sort the events by its startTime.", "For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search." ]
/** * @param {number[][]} events * @param {number} k * @return {number} */ var maxValue = function(events, k) { };
You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return the maximum sum of values that you can receive by attending events.   Example 1: Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2 Output: 7 Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. Example 2: Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2 Output: 10 Explanation: Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events. Example 3: Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3 Output: 9 Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.   Constraints: 1 <= k <= events.length 1 <= k * events.length <= 106 1 <= startDayi <= endDayi <= 109 1 <= valuei <= 106
Hard
[ "array", "binary-search", "dynamic-programming", "sorting" ]
[ "const maxValue = function (events, k) {\n const n = events.length\n const memo = Array.from({ length: n + 1 }, () => Array(k + 1).fill(-1))\n events.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])\n return helper(memo, events, n, 0, k)\n}\n\nfunction helper(memo, events, n, i, k) {\n if(i === n || k === 0) return 0\n if(memo[i][k] !== -1) return memo[i][k]\n let ni = i + 1\n for(; ni < n; ni++) {\n if(events[ni][0] > events[i][1]) break\n }\n\n return memo[i][k] = Math.max(\n helper(memo, events, n, i + 1, k),\n events[i][2] + helper(memo, events, n, ni, k - 1)\n )\n}", "const maxValue = function (events, k) {\n // d[i][j] 表示以 events[i]结尾的取最多j个最大值\n // d[i][j-1], Math.max( d[m][j-1] + v[i]) for m ending < start[i]\n events.sort((a, b) => a[1] - b[1])\n const n = events.length\n let d = []\n for (let j = 0; j <= k; j++) {\n const newD = []\n for (let i = 0; i < n; i++) {\n if (j === 0) {\n newD[i] = 0\n } else if (j === 1) {\n newD[i] = events[i][2]\n } else if (i === 0) {\n newD[i] = events[i][2]\n } else {\n newD[i] = d[i] // 以i结尾最多取j-1次的最大值\n const v = events[i][2]\n const start = events[i][0]\n for (let m = 0; m < i; m++) {\n if (events[m][1] < start) {\n if (d[m] + v > newD[i]) {\n newD[i] = d[m] + v\n }\n } else {\n break\n }\n }\n }\n }\n d = [...newD]\n }\n return Math.max(...d)\n}", "const maxValue = function(events, k) {\n\n cache = new Map();\n events.sort((a,b) => a[0] - b[0]);\n return dfs(events, 0, -1, k);\n \n function dfs(events, idx, end, k){\n let key = idx + \",\" + end + \",\" + k;\n if(cache.has(key)){\n return cache.get(key);\n }\n if(idx >= events.length){\n return 0;\n }\n if(k == 0) {\n return 0;\n }\n let max = 0;\n if(events[idx][0] > end){\n max = Math.max(max, dfs(events, idx+1, events[idx][1], k-1) + events[idx][2]);\n }\n \n max = Math.max(max, dfs(events, idx+1, end, k));\n cache.set(key, max);\n return max;\n }\n};" ]
1,752
check-if-array-is-sorted-and-rotated
[ "Brute force and check if it is possible for a sorted array to start from each position." ]
/** * @param {number[]} nums * @return {boolean} */ var check = function(nums) { };
Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false. There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.   Example 1: Input: nums = [3,4,5,1,2] Output: true Explanation: [1,2,3,4,5] is the original sorted array. You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2]. Example 2: Input: nums = [2,1,3,4] Output: false Explanation: There is no sorted array once rotated that can make nums. Example 3: Input: nums = [1,2,3] Output: true Explanation: [1,2,3] is the original sorted array. You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.   Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100
Easy
[ "array" ]
[ "const check = function(nums) {\n let prev = -1, mark = 0\n for(let e of nums) {\n \n if(e >= prev) prev = e\n else {\n mark++\n prev = e\n }\n if(mark > 1) return false\n }\n if(mark === 1 && nums[0] < nums[nums.length - 1]) {\n return false\n }\n return true\n};" ]
1,753
maximum-score-from-removing-stones
[ "It's optimal to always remove one stone from the biggest 2 piles", "Note that the limits are small enough for simulation" ]
/** * @param {number} a * @param {number} b * @param {number} c * @return {number} */ var maximumScore = function(a, b, c) { };
You are playing a solitaire game with three piles of stones of sizes a​​​​​​, b,​​​​​​ and c​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves). Given three integers a​​​​​, b,​​​​​ and c​​​​​, return the maximum score you can get.   Example 1: Input: a = 2, b = 4, c = 6 Output: 6 Explanation: The starting state is (2, 4, 6). One optimal set of moves is: - Take from 1st and 3rd piles, state is now (1, 4, 5) - Take from 1st and 3rd piles, state is now (0, 4, 4) - Take from 2nd and 3rd piles, state is now (0, 3, 3) - Take from 2nd and 3rd piles, state is now (0, 2, 2) - Take from 2nd and 3rd piles, state is now (0, 1, 1) - Take from 2nd and 3rd piles, state is now (0, 0, 0) There are fewer than two non-empty piles, so the game ends. Total: 6 points. Example 2: Input: a = 4, b = 4, c = 6 Output: 7 Explanation: The starting state is (4, 4, 6). One optimal set of moves is: - Take from 1st and 2nd piles, state is now (3, 3, 6) - Take from 1st and 3rd piles, state is now (2, 3, 5) - Take from 1st and 3rd piles, state is now (1, 3, 4) - Take from 1st and 3rd piles, state is now (0, 3, 3) - Take from 2nd and 3rd piles, state is now (0, 2, 2) - Take from 2nd and 3rd piles, state is now (0, 1, 1) - Take from 2nd and 3rd piles, state is now (0, 0, 0) There are fewer than two non-empty piles, so the game ends. Total: 7 points. Example 3: Input: a = 1, b = 8, c = 8 Output: 8 Explanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty. After that, there are fewer than two non-empty piles, so the game ends.   Constraints: 1 <= a, b, c <= 105
Medium
[ "math", "greedy", "heap-priority-queue" ]
[ "const maximumScore = function(a, b, c) {\n const arr = [a, b, c]\n arr.sort((a, b) => a - b)\n \n\n if (arr[0] + arr[1] <= arr[2]) {\n return arr[0] + arr[1];\n } else {\n const min = Math.min(arr[0], Math.floor((arr[1] + arr[0] - arr[2]) / 2));\n return arr[2] + min;\n }\n};" ]
1,754
largest-merge-of-two-strings
[ "Build the result character by character. At each step, you choose a character from one of the two strings.", "If the next character of the first string is larger than that of the second string, or vice versa, it's optimal to use the larger one.", "If both are equal, think of a criteria that lets you decide which string to consume the next character from.", "You should choose the next character from the larger string." ]
/** * @param {string} word1 * @param {string} word2 * @return {string} */ var largestMerge = function(word1, word2) { };
You are given two strings word1 and word2. You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options: If word1 is non-empty, append the first character in word1 to merge and delete it from word1. For example, if word1 = "abc" and merge = "dv", then after choosing this operation, word1 = "bc" and merge = "dva". If word2 is non-empty, append the first character in word2 to merge and delete it from word2. For example, if word2 = "abc" and merge = "", then after choosing this operation, word2 = "bc" and merge = "a". Return the lexicographically largest merge you can construct. A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, "abcd" is lexicographically larger than "abcc" because the first position they differ is at the fourth character, and d is greater than c.   Example 1: Input: word1 = "cabaa", word2 = "bcaaa" Output: "cbcabaaaaa" Explanation: One way to get the lexicographically largest merge is: - Take from word1: merge = "c", word1 = "abaa", word2 = "bcaaa" - Take from word2: merge = "cb", word1 = "abaa", word2 = "caaa" - Take from word2: merge = "cbc", word1 = "abaa", word2 = "aaa" - Take from word1: merge = "cbca", word1 = "baa", word2 = "aaa" - Take from word1: merge = "cbcab", word1 = "aa", word2 = "aaa" - Append the remaining 5 a's from word1 and word2 at the end of merge. Example 2: Input: word1 = "abcabc", word2 = "abdcaba" Output: "abdcabcabcaba"   Constraints: 1 <= word1.length, word2.length <= 3000 word1 and word2 consist only of lowercase English letters.
Medium
[ "two-pointers", "string", "greedy" ]
[ "var largestMerge = function(word1, word2) {\n let merge = \"\";\n \n while(word1.length && word2.length) {\n if (word1[0] > word2[0]) {\n merge += word1[0];\n word1 = word1.slice(1);\n } else if (word1[0] < word2[0]) {\n merge += word2[0];\n word2 = word2.slice(1);\n } else {\n if (word1 > word2) {\n merge += word1[0];\n word1 = word1.slice(1);\n } else {\n merge += word2[0];\n word2 = word2.slice(1);\n }\n }\n }\n \n if (word1.length) {\n merge += word1;\n } else if (word2.length) {\n merge += word2;\n }\n \n return merge; \n};", "const largestMerge = function(word1, word2) {\n const stack1 = word1.split(''), stack2 = word2.split('')\n const arr = []\n \n while(stack1.length && stack2.length) {\n const c1 = stack1[0], c2 = stack2[0]\n if(c1 > c2) {\n stack1.shift()\n arr.push(c1)\n } else if(c1 < c2) {\n stack2.shift()\n arr.push(c2)\n } else {\n if(stack1.join('') > stack2.join('')) {\n stack1.shift()\n arr.push(c1)\n } else {\n stack2.shift()\n arr.push(c2)\n }\n }\n }\n if(stack1.length) {\n arr.push(...stack1)\n }\n if(stack2.length) {\n arr.push(...stack2)\n } \n \n return arr.join('')\n};" ]
1,755
closest-subsequence-sum
[ "The naive solution is to check all possible subsequences. This works in O(2^n).", "Divide the array into two parts of nearly is equal size.", "Consider all subsets of one part and make a list of all possible subset sums and sort this list.", "Consider all subsets of the other part, and for each one, let its sum = x, do binary search to get the nearest possible value to goal - x in the first part." ]
/** * @param {number[]} nums * @param {number} goal * @return {number} */ var minAbsDifference = function(nums, goal) { };
You are given an integer array nums and an integer goal. You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal). Return the minimum possible value of abs(sum - goal). Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.   Example 1: Input: nums = [5,-7,3,5], goal = 6 Output: 0 Explanation: Choose the whole array as a subsequence, with a sum of 6. This is equal to the goal, so the absolute difference is 0. Example 2: Input: nums = [7,-9,15,-2], goal = -5 Output: 1 Explanation: Choose the subsequence [7,-9,-2], with a sum of -4. The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum. Example 3: Input: nums = [1,2,3], goal = -7 Output: 7   Constraints: 1 <= nums.length <= 40 -107 <= nums[i] <= 107 -109 <= goal <= 109
Hard
[ "array", "two-pointers", "dynamic-programming", "bit-manipulation", "bitmask" ]
[ "const minAbsDifference = function (nums, goal) {\n let min = Math.abs(goal)\n if (!nums.length) return min\n const generateSums = (a) => {\n let sums = []\n for (let i = 0; i < a.length; i++) {\n const l = sums.length\n for (let j = 0; j < l; j++) {\n sums.push(sums[j] + a[i])\n min = Math.min(min, Math.abs(sums[j] + a[i] - goal))\n if (min === 0) return\n }\n sums.push(a[i])\n min = Math.min(min, Math.abs(a[i] - goal))\n if (min === 0) return\n }\n return sums\n }\n\n const n1 = nums.slice(0, Math.ceil(nums.length / 2))\n const n2 = nums.slice(Math.ceil(nums.length / 2), nums.length)\n const sums1 = generateSums(n1)\n if (min === 0) return min\n const sums2 = generateSums(n2)\n if (min === 0) return min\n\n sums2.sort((a, b) => a - b)\n for (let i = 0; i < sums1.length; i++) {\n if (min === 0) return min\n let l = 0\n let r = sums2.length\n let sum\n while (l < r) {\n const h = Math.floor((l + r) / 2)\n sum = sums1[i] + sums2[h]\n min = Math.min(min, Math.abs(sum - goal))\n if (min === 0) return min\n if (sum - goal < 0) {\n l = h + 1\n } else {\n r = h\n }\n }\n }\n return min\n}", "var minAbsDifference = function(a, b) {\n let n = a.length, m = (n / 2) >> 0, r = n - m;\n let ans = 2e9;\n const {max, min, abs} = Math\n const va = [], vb = [];\n for(let i=0;i<1<<m;++i) {\n let tmp=0;\n for(let j=0;j<m;++j) {\n if(i>>j&1) tmp+=a[j];\n }\n ans=min(ans,abs(tmp-b));\n va.push(tmp);\n }\n // sort(va.begin(), va.end());\n va.sort((a, b) => a - b)\n for(let i=0;i<1<<r;++i) {\n let tmp=0;\n for(let j=0;j<r;++j) {\n if(i>>j&1) tmp+=a[j+m];\n }\n ans=min(ans,abs(tmp-b));\n let k=b-tmp;\n let pos=lower_bound(va, k);\n for(let j=pos-1;j<=pos+1;++j) {\n if(j>=0 && j<va.length) {\n ans=min(ans, abs(va[j]+tmp-b));\n }\n }\n }\n return ans;\n};\n\nfunction lower_bound(array, arg1, arg2, arg3, arg4) {\n let first;\n let last;\n let value;\n let less;\n if (arg3 === undefined) {\n first = 0;\n last = array.length;\n value = arg1;\n less = arg2;\n } else {\n first = arg1;\n last = arg2;\n value = arg3;\n less = arg4;\n }\n\n if (less === undefined) {\n less = function (a, b) { return a < b; };\n }\n\n let len = last - first;\n let middle;\n let step;\n while (len > 0) {\n step = Math.floor(len / 2);\n middle = first + step;\n if (less(array[middle], value, middle)) {\n first = middle;\n first += 1;\n len = len - step - 1;\n } else {\n len = step;\n }\n }\n return first;\n};" ]
1,758
minimum-changes-to-make-alternating-binary-string
[ "Think about how the final string will look like.", "It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..'", "Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways." ]
/** * @param {string} s * @return {number} */ var minOperations = function(s) { };
You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not. Return the minimum number of operations needed to make s alternating.   Example 1: Input: s = "0100" Output: 1 Explanation: If you change the last character to '1', s will be "0101", which is alternating. Example 2: Input: s = "10" Output: 0 Explanation: s is already alternating. Example 3: Input: s = "1111" Output: 2 Explanation: You need two operations to reach "0101" or "1010".   Constraints: 1 <= s.length <= 104 s[i] is either '0' or '1'.
Easy
[ "string" ]
[ "const minOperations = function(s) {\n const arr = s.split('')\n return Math.min(helper(arr, 0, '0'), helper(arr, 0, '1'))\n \n function helper(arr, idx, ch) {\n if(idx === arr.length) return 0\n if(arr[idx] !== ch) return 1 + helper(arr, idx + 1, ch === '0' ? '1' : '0')\n else return helper(arr, idx + 1, ch === '0' ? '1' : '0')\n }\n};" ]
1,759
count-number-of-homogenous-substrings
[ "A string of only 'a's of length k contains k choose 2 homogenous substrings.", "Split the string into substrings where each substring contains only one letter, and apply the formula on each substring's length." ]
/** * @param {string} s * @return {number} */ var countHomogenous = function(s) { };
Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7. A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "abbcccaa" Output: 13 Explanation: The homogenous substrings are listed as below: "a" appears 3 times. "aa" appears 1 time. "b" appears 2 times. "bb" appears 1 time. "c" appears 3 times. "cc" appears 2 times. "ccc" appears 1 time. 3 + 1 + 2 + 1 + 3 + 2 + 1 = 13. Example 2: Input: s = "xy" Output: 2 Explanation: The homogenous substrings are "x" and "y". Example 3: Input: s = "zzzzz" Output: 15   Constraints: 1 <= s.length <= 105 s consists of lowercase letters.
Medium
[ "math", "string" ]
[ "const countHomogenous = function(s) {\n const mod = 10 ** 9 + 7\n let pre = s[0], res = 0, curL = 1\n for(let i = 1, len = s.length; i < len; i++) {\n if(s[i] === pre) {\n curL++\n } else {\n res = (res + helper(curL)) % mod\n pre = s[i]\n curL = 1\n }\n }\n if(curL === 1) res = (res + 1) % mod\n else res = (res + helper(curL)) % mod\n return res\n\n function helper(num) {\n return (num * (num + 1)) / 2\n }\n};" ]
1,760
minimum-limit-of-balls-in-a-bag
[ "Let's change the question if we know the maximum size of a bag what is the minimum number of bags you can make", "note that as the maximum size increases the minimum number of bags decreases so we can binary search the maximum size" ]
/** * @param {number[]} nums * @param {number} maxOperations * @return {number} */ var minimumSize = function(nums, maxOperations) { };
You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations. You can perform the following operation at most maxOperations times: Take any bag of balls and divide it into two new bags with a positive number of balls. For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls. Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations. Return the minimum possible penalty after performing the operations.   Example 1: Input: nums = [9], maxOperations = 2 Output: 3 Explanation: - Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3]. - Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3]. The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3. Example 2: Input: nums = [2,4,8,2], maxOperations = 4 Output: 2 Explanation: - Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2]. The bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2.   Constraints: 1 <= nums.length <= 105 1 <= maxOperations, nums[i] <= 109
Medium
[ "array", "binary-search" ]
[ "const minimumSize = function(nums, maxOperations) {\n let L = 1, R = 10 ** 9;\n while(L < R){\n let M = (L + (R - L) / 2) >> 0, cnt = 0;\n for(let x of nums) cnt += ((x + M - 1) / M - 1) >> 0;\n if(cnt > maxOperations) L = M + 1;\n else R = M;\n }\n return L;\n};" ]
1,761
minimum-degree-of-a-connected-trio-in-a-graph
[ "Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation.", "To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other." ]
/** * @param {number} n * @param {number[][]} edges * @return {number} */ var minTrioDegree = function(n, edges) { };
You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. A connected trio is a set of three nodes where there is an edge between every pair of them. The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.   Example 1: Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]] Output: 3 Explanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above. Example 2: Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]] Output: 0 Explanation: There are exactly three trios: 1) [1,4,3] with degree 0. 2) [2,5,6] with degree 2. 3) [5,6,7] with degree 2.   Constraints: 2 <= n <= 400 edges[i].length == 2 1 <= edges.length <= n * (n-1) / 2 1 <= ui, vi <= n ui != vi There are no repeated edges.
Hard
[ "graph" ]
[ "const minTrioDegree = function (n, edges) {\n let ans = 10 ** 8\n const adj = []\n const deg = {}\n\n function incDeg(u) {\n if (deg[u] == null) deg[u] = 0\n deg[u]++\n }\n for (let i = 0; i < n; i++) {\n adj.push(Array(n).fill(false))\n }\n\n for (let [u, v] of edges) {\n adj[u - 1][v - 1] = true\n adj[v - 1][u - 1] = true\n incDeg(u - 1)\n incDeg(v - 1)\n }\n for (let u1 = 0; u1 < n; u1++) {\n for (let u2 = u1 + 1; u2 < n; u2++) {\n for (let u3 = u2 + 1; u3 < n; u3++) {\n if (adj[u1][u2] && adj[u2][u3] && adj[u3][u1]) {\n let tmp = deg[u1] + deg[u2] + deg[u3] - 6\n ans = Math.min(ans, tmp)\n }\n }\n }\n }\n\n if (ans > 10000000) ans = -1\n return ans\n}" ]
1,763
longest-nice-substring
[ "Brute force and check each substring to see if it is nice." ]
/** * @param {string} s * @return {string} */ var longestNiceSubstring = function(s) { };
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.   Example 1: Input: s = "YazaAay" Output: "aAa" Explanation: "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear. "aAa" is the longest nice substring. Example 2: Input: s = "Bb" Output: "Bb" Explanation: "Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring. Example 3: Input: s = "c" Output: "" Explanation: There are no nice substrings.   Constraints: 1 <= s.length <= 100 s consists of uppercase and lowercase English letters.
Easy
[ "hash-table", "string", "divide-and-conquer", "bit-manipulation", "sliding-window" ]
[ "const longestNiceSubstring = function(s) {\n let res = ''\n const n = s.length\n \n const arr = Array(26).fill(null)\n for(let i = 0; i < n - 1; i++) {\n for(let j = i + 1; j < n; j++) {\n const tmp = s.slice(i, j + 1)\n if(helper(tmp)) {\n if(tmp.length > res.length) res = tmp\n }\n }\n }\n \n \n return res\n};\n\nfunction helper(s) {\n const arr = Array(26).fill(null)\n const a = 'a'.charCodeAt(0), A = 'A'.charCodeAt(0)\n for(let e of s) {\n const ecode = e.charCodeAt(0)\n if(arr[ecode - a] === 0 || arr[ecode - A] === 0) continue\n if(ecode - a < 26 && ecode - a >= 0) arr[ecode - a] = arr[ecode - a] === 1 ? 0 : -1\n if(ecode - A < 26 && ecode - A >= 0) arr[ecode - A] = arr[ecode - A] === -1 ? 0 : 1\n }\n for(let e of arr) {\n if(e === -1 || e === 1) return false\n }\n \n return true\n}" ]
1,764
form-array-by-concatenating-subarrays-of-another-array
[ "When we use a subarray, the room for the next subarrays will be the suffix after the used subarray.", "If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays." ]
/** * @param {number[][]} groups * @param {number[]} nums * @return {boolean} */ var canChoose = function(groups, nums) { };
You are given a 2D integer array groups of length n. You are also given an integer array nums. You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups). Return true if you can do this task, and false otherwise. Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.   Example 1: Input: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0] Output: true Explanation: You can choose the 0th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,3,-2,0]. These subarrays are disjoint as they share no common nums[k] element. Example 2: Input: groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2] Output: false Explanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups. [10,-2] must come before [1,2,3,4]. Example 3: Input: groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7] Output: false Explanation: Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint. They share a common elements nums[4] (0-indexed).   Constraints: groups.length == n 1 <= n <= 103 1 <= groups[i].length, sum(groups[i].length) <= 103 1 <= nums.length <= 103 -107 <= groups[i][j], nums[k] <= 107
Medium
[ "array", "greedy", "string-matching" ]
[ "const canChoose = function (groups, nums) {\n const m = nums.length\n let index = 0\n for (let group of groups) {\n const n = group.length\n // Step-1 Generate LPS\n const lps = Array(n).fill(0)\n for (let i = 1; i < n; i++) {\n let j = lps[i - 1]\n while (j > 0 && group[i] !== group[j]) {\n j = lps[j - 1]\n }\n if (group[i] === group[j]) {\n j++\n }\n lps[i] = j\n }\n\n // Step-2 - Matching\n let j = 0\n while (index < m) {\n if (nums[index] === group[j]) {\n j++\n index++\n }\n if (j === n) break\n else if (index < m && nums[index] != group[j]) {\n if (j > 0) {\n j = lps[j - 1]\n } else {\n index++\n }\n }\n }\n if (j !== n) return false\n }\n return true\n}", "const canChoose = function(groups, nums) {\n let gi = 0, ni = 0\n const n = groups.length, m = nums.length\n while(gi < n && ni < m) {\n const len = groups[gi].length\n let pass = true\n if(nums[ni] !== groups[gi][0]) {\n ni++\n continue\n }\n for(let i = 1; i < len; i++) {\n if(nums[ni + i] !== groups[gi][i]) {\n pass = false\n break\n }\n }\n if(pass) {\n gi++\n ni += len\n } else {\n ni++\n }\n }\n if(gi >= n) return true\n\n return false\n\n};" ]
1,765
map-of-highest-peak
[ "Set each water cell to be 0. The height of each cell is limited by its closest water cell.", "Perform a multi-source BFS with all the water cells as sources." ]
/** * @param {number[][]} isWater * @return {number[][]} */ var highestPeak = function(isWater) { };
You are given an integer matrix isWater of size m x n that represents a map of land and water cells. If isWater[i][j] == 0, cell (i, j) is a land cell. If isWater[i][j] == 1, cell (i, j) is a water cell. You must assign each cell a height in a way that follows these rules: The height of each cell must be non-negative. If the cell is a water cell, its height must be 0. Any two adjacent cells must have an absolute height difference of at most 1. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is maximized. Return an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them.   Example 1: Input: isWater = [[0,1],[0,0]] Output: [[1,0],[2,1]] Explanation: The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. Example 2: Input: isWater = [[0,0,1],[1,0,0],[0,0,0]] Output: [[1,1,0],[0,1,1],[1,2,2]] Explanation: A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.   Constraints: m == isWater.length n == isWater[i].length 1 <= m, n <= 1000 isWater[i][j] is 0 or 1. There is at least one water cell.
Medium
[ "array", "breadth-first-search", "matrix" ]
[ "const highestPeak = function(isWater) {\n let q = []\n const visited = new Set()\n const m = isWater.length, n = isWater[0].length\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(isWater[i][j] === 1) {\n q.push([i, j, 0])\n visited.add(`${i},${j}`)\n }\n }\n }\n const res = Array.from({ length: m }, () => Array(n).fill(0))\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n \n while(q.length) {\n const size = q.length\n const next = []\n // Array.shift time complexity: O(n)\n for(let i = 0; i < size; i++) {\n const cur = q[i]\n const [row, col, val] = cur\n for(let dir of dirs) {\n const newRow = row + dir[0], newCol = col + dir[1]\n const key = `${newRow},${newCol}`\n if(newRow < 0 || newRow >= m || newCol < 0 || newCol >= n || visited.has(key) || res[newRow][newCol] !== 0) continue\n next.push([newRow, newCol, val + 1])\n res[newRow][newCol] = val + 1\n visited.add(key)\n }\n }\n q = next\n\n }\n return res\n};" ]
1,766
tree-of-coprimes
[ "Note that for a node, it's not optimal to consider two nodes with the same value.", "Note that the values are small enough for you to iterate over them instead of iterating over the parent nodes." ]
/** * @param {number[]} nums * @param {number[][]} edges * @return {number[]} */ var getCoprimes = function(nums, edges) { };
There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0. To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree. Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y. An ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself. Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor.   Example 1: Input: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]] Output: [-1,0,0,1] Explanation: In the above figure, each node's value is in parentheses. - Node 0 has no coprime ancestors. - Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1). - Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor. - Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its closest valid ancestor. Example 2: Input: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]] Output: [-1,0,-1,0,0,0,-1]   Constraints: nums.length == n 1 <= nums[i] <= 50 1 <= n <= 105 edges.length == n - 1 edges[j].length == 2 0 <= uj, vj < n uj != vj
Hard
[ "math", "tree", "depth-first-search", "breadth-first-search" ]
[ "const getCoprimes = function (nums, edges) {\n const output = Array(nums.length).fill(null)\n const graph = new Map()\n for (let [u, v] of edges) {\n if (!graph.has(u)) graph.set(u, [])\n if (!graph.has(v)) graph.set(v, [])\n graph.get(u).push(v)\n graph.get(v).push(u)\n }\n\n function getGCD(a, b) {\n if (!b) return a\n return getGCD(b, a % b)\n }\n\n // ancestors is an array of unique ancestors from the recent to the farthest\n // indices maps the index of each ancestor\n function dfs(i, ancestors, indices) {\n for (let num of ancestors) {\n const gcd = getGCD(nums[i], num)\n if (gcd === 1) {\n output[i] = indices[num]\n break\n }\n }\n\n if (output[i] === null) output[i] = -1\n ancestors = [nums[i], ...ancestors.filter((x) => x !== nums[i])]\n indices[nums[i]] = i\n for (let next of graph.get(i)) {\n if (output[next] === null) {\n dfs(next, ancestors, [...indices])\n }\n }\n }\n\n dfs(0, [], Array(51))\n return output\n}" ]
1,768
merge-strings-alternately
[ "Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards." ]
/** * @param {string} word1 * @param {string} word2 * @return {string} */ var mergeAlternately = function(word1, word2) { };
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string.   Example 1: Input: word1 = "abc", word2 = "pqr" Output: "apbqcr" Explanation: The merged string will be merged as so: word1: a b c word2: p q r merged: a p b q c r Example 2: Input: word1 = "ab", word2 = "pqrs" Output: "apbqrs" Explanation: Notice that as word2 is longer, "rs" is appended to the end. word1: a b word2: p q r s merged: a p b q r s Example 3: Input: word1 = "abcd", word2 = "pq" Output: "apbqcd" Explanation: Notice that as word1 is longer, "cd" is appended to the end. word1: a b c d word2: p q merged: a p b q c d   Constraints: 1 <= word1.length, word2.length <= 100 word1 and word2 consist of lowercase English letters.
Easy
[ "two-pointers", "string" ]
[ "var mergeAlternately = function(word1, word2) {\n let res = '', mark = 0, i = 0, j = 0\n while(i < word1.length && j < word2.length) {\n if(mark === 0) {\n res += word1[i++]\n mark = 1\n } else {\n res += word2[j++]\n mark = 0\n }\n }\n while(i < word1.length) res += word1[i++]\n while(j < word2.length) res += word2[j++]\n \n return res\n};" ]
1,769
minimum-number-of-operations-to-move-all-balls-to-each-box
[ "If you want to move a ball from box i to box j, you'll need abs(i-j) moves.", "To move all balls to some box, you can move them one by one.", "For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i]." ]
/** * @param {string} boxes * @return {number[]} */ var minOperations = function(boxes) { };
You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball. In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes. Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box. Each answer[i] is calculated considering the initial state of the boxes.   Example 1: Input: boxes = "110" Output: [1,1,3] Explanation: The answer for each box is as follows: 1) First box: you will have to move one ball from the second box to the first box in one operation. 2) Second box: you will have to move one ball from the first box to the second box in one operation. 3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation. Example 2: Input: boxes = "001011" Output: [11,8,5,4,3,4]   Constraints: n == boxes.length 1 <= n <= 2000 boxes[i] is either '0' or '1'.
Medium
[ "array", "string" ]
[ "const minOperations = function(boxes) {\n const n = boxes.length\n const res = Array(n).fill(0)\n let cum = 0, sum = 0\n for(let i = 0; i < n; i++) {\n res[i] += sum\n cum += +boxes[i]\n sum += cum\n }\n cum = 0, sum = 0\n for(let i = n - 1; i >= 0; i--) {\n res[i] += sum\n cum += +boxes[i]\n sum += cum\n }\n return res\n};", "const minOperations = function(boxes) {\n const res = []\n for(let i = 0, len = boxes.length; i < len; i++) {\n res[i] = helper(boxes, i)\n }\n\n return res\n};\n\nfunction helper(str, idx) {\n let res = 0\n for(let i = 0, len = str.length; i < len; i++) {\n if(i === idx || str[i] === '0') continue\n res += Math.abs(i - idx)\n }\n return res\n}", " const minOperations = function(boxes) {\n const n = boxes.length\n const res = Array(n).fill(0)\n let cnt = 0, sum = 0\n for(let i = 0; i < n; i++) {\n res[i] = sum\n cnt += boxes[i] === '1' ? 1 : 0\n sum += cnt\n }\n cnt = 0, sum = 0\n for(let i = n - 1; i >= 0; i--) {\n res[i] += sum\n cnt += boxes[i] === '1' ? 1 : 0\n sum += cnt\n }\n return res\n};" ]
1,770
maximum-score-from-performing-multiplication-operations
[ "At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal.", "You should try all scenarios but this will be costy.", "Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence dp is a perfect choice here." ]
/** * @param {number[]} nums * @param {number[]} multipliers * @return {number} */ var maximumScore = function(nums, multipliers) { };
You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, where n >= m. You begin with a score of 0. You want to perform exactly m operations. On the ith operation (0-indexed) you will: Choose one integer x from either the start or the end of the array nums. Add multipliers[i] * x to your score. Note that multipliers[0] corresponds to the first operation, multipliers[1] to the second operation, and so on. Remove x from nums. Return the maximum score after performing m operations.   Example 1: Input: nums = [1,2,3], multipliers = [3,2,1] Output: 14 Explanation: An optimal solution is as follows: - Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score. - Choose from the end, [1,2], adding 2 * 2 = 4 to the score. - Choose from the end, [1], adding 1 * 1 = 1 to the score. The total score is 9 + 4 + 1 = 14. Example 2: Input: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6] Output: 102 Explanation: An optimal solution is as follows: - Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score. - Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score. - Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score. - Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score. - Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. The total score is 50 + 15 - 9 + 4 + 42 = 102.   Constraints: n == nums.length m == multipliers.length 1 <= m <= 300 m <= n <= 105 -1000 <= nums[i], multipliers[i] <= 1000
Hard
[ "array", "dynamic-programming" ]
[ "const maximumScore = function(nums, multipliers) {\n const n = nums.length, m = multipliers.length\n const { max } = Math\n const dp = Array.from({ length: m + 1 }, () => Array(m + 1).fill(-Infinity))\n return helper(0, 0)\n function helper(l, i) {\n if(i === m) return 0\n if(dp[l][i] !== -Infinity) return dp[l][i]\n const pickLeft = helper(l + 1, i + 1) + nums[l] * multipliers[i]\n const pickRight = helper(l, i + 1) + nums[n - (i - l) - 1] * multipliers[i]\n return dp[l][i] = max(pickLeft, pickRight)\n }\n\n};" ]
1,771
maximize-palindrome-length-from-subsequences
[ "Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming.", "Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty." ]
/** * @param {string} word1 * @param {string} word2 * @return {number} */ var longestPalindrome = function(word1, word2) { };
You are given two strings, word1 and word2. You want to construct a string in the following manner: Choose some non-empty subsequence subsequence1 from word1. Choose some non-empty subsequence subsequence2 from word2. Concatenate the subsequences: subsequence1 + subsequence2, to make the string. Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0. A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters. A palindrome is a string that reads the same forward as well as backward.   Example 1: Input: word1 = "cacb", word2 = "cbba" Output: 5 Explanation: Choose "ab" from word1 and "cba" from word2 to make "abcba", which is a palindrome. Example 2: Input: word1 = "ab", word2 = "ab" Output: 3 Explanation: Choose "ab" from word1 and "a" from word2 to make "aba", which is a palindrome. Example 3: Input: word1 = "aa", word2 = "bb" Output: 0 Explanation: You cannot construct a palindrome from the described method, so return 0.   Constraints: 1 <= word1.length, word2.length <= 1000 word1 and word2 consist of lowercase English letters.
Hard
[ "string", "dynamic-programming" ]
[ "const longestPalindrome = function(word1, word2) {\n const str = word1 + word2\n const len = str.length, m = word1.length, n = word2.length\n const dp = LPS(str)\n let res = 0\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(word1[i] !== word2[j]) continue\n res = Math.max(res, 2 + dp[i + 1][j + m - 1])\n }\n }\n return res\n}\n\nfunction LPS(str) {\n const n = str.length\n const dp = Array.from({ length: n }, () => Array(n).fill(0))\n for(let i = n - 1; i >= 0; i--) {\n dp[i][i] = 1\n for(let j = i + 1; j < n; j++) {\n if(str[i] === str[j]) dp[i][j] = 2 + dp[i + 1][j - 1]\n else dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1])\n }\n }\n return dp\n}", "const longestPalindrome = function(word1, word2) {\n const sz = word1.length + word2.length\n let res = 0;\n const dp = Array.from({ length: sz + 1 }, () => Array(sz + 1).fill(0))\n longestPalindromeSubseq(word1 + word2, dp);\n for (let i = 0; i < word1.length; ++i)\n for (let j = word2.length - 1; j >= 0; --j)\n if (word1[i] == word2[j]) {\n res = Math.max(res, dp[i][word1.length + j + 1]);\n break;\n }\n return res;\n\n}\nfunction longestPalindromeSubseq( s, dp) {\n for (let len = 1; len <= s.length; ++len) \n for (let i = 0; i + len <= s.length; ++i) \n dp[i][i + len] = s[i] == s[i + len - 1] ? \n dp[i + 1][i + len - 1] + (len == 1 ? 1 : 2) : \n Math.max(dp[i][i + len - 1], dp[i + 1][i + len]);\n return dp[0][s.length];\n} " ]
1,773
count-items-matching-a-rule
[ "Iterate on each item, and check if each one matches the rule according to the statement." ]
/** * @param {string[][]} items * @param {string} ruleKey * @param {string} ruleValue * @return {number} */ var countMatches = function(items, ruleKey, ruleValue) { };
You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue. The ith item is said to match the rule if one of the following is true: ruleKey == "type" and ruleValue == typei. ruleKey == "color" and ruleValue == colori. ruleKey == "name" and ruleValue == namei. Return the number of items that match the given rule.   Example 1: Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver" Output: 1 Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"]. Example 2: Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone" Output: 2 Explanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match.   Constraints: 1 <= items.length <= 104 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10 ruleKey is equal to either "type", "color", or "name". All strings consist only of lowercase letters.
Easy
[ "array", "string" ]
[ "const countMatches = function(items, ruleKey, ruleValue) {\n let res = 0\n for(let e of items) {\n if(helper(e, ruleKey, ruleValue)) res++\n }\n return res\n};\n\nfunction helper(e, k, v) {\n const [t, c, n] = e\n if(k === 'type' && v === t) {\n return true\n } else if(k === 'color' && v === c) {\n return true\n } else if(k === 'name' && v === n) {\n return true\n }\n \n return false\n \n}" ]
1,774
closest-dessert-cost
[ "As the constraints are not large, you can brute force and enumerate all the possibilities." ]
/** * @param {number[]} baseCosts * @param {number[]} toppingCosts * @param {number} target * @return {number} */ var closestCost = function(baseCosts, toppingCosts, target) { };
You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert: There must be exactly one ice cream base. You can add one or more types of topping or have no toppings at all. There are at most two of each type of topping. You are given three inputs: baseCosts, an integer array of length n, where each baseCosts[i] represents the price of the ith ice cream base flavor. toppingCosts, an integer array of length m, where each toppingCosts[i] is the price of one of the ith topping. target, an integer representing your target price for dessert. You want to make a dessert with a total cost as close to target as possible. Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.   Example 1: Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10 Output: 10 Explanation: Consider the following combination (all 0-indexed): - Choose base 1: cost 7 - Take 1 of topping 0: cost 1 x 3 = 3 - Take 0 of topping 1: cost 0 x 4 = 0 Total: 7 + 3 + 0 = 10. Example 2: Input: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18 Output: 17 Explanation: Consider the following combination (all 0-indexed): - Choose base 1: cost 3 - Take 1 of topping 0: cost 1 x 4 = 4 - Take 2 of topping 1: cost 2 x 5 = 10 - Take 0 of topping 2: cost 0 x 100 = 0 Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18. Example 3: Input: baseCosts = [3,10], toppingCosts = [2,5], target = 9 Output: 8 Explanation: It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.   Constraints: n == baseCosts.length m == toppingCosts.length 1 <= n, m <= 10 1 <= baseCosts[i], toppingCosts[i] <= 104 1 <= target <= 104
Medium
[ "array", "dynamic-programming", "backtracking" ]
[ "const closestCost = function(baseCosts, toppingCosts, target) {\n let res = baseCosts[0], n = baseCosts.length, m = toppingCosts.length\n const { abs } = Math\n for (let i = 0; i < n; i++) {\n helper(0, baseCosts[i])\n }\n return res\n function helper(i, cur) {\n if(\n abs(cur - target) < abs(res - target)\n || (abs(cur - target) === abs(res - target) && cur < res)\n ) {\n res = cur\n }\n if(i === m || cur > target) return\n helper(i + 1, cur)\n helper(i + 1, cur + toppingCosts[i])\n helper(i + 1, cur + toppingCosts[i] * 2)\n }\n};", "const closestCost = function(baseCosts, toppingCosts, target) {\n let n = baseCosts.length, m = toppingCosts.length;\n const { abs } = Math\n const costs = new Set();\n for (let i = 0; i < n; i++) {\n dfs(toppingCosts, 0, m, baseCosts[i], costs);\n }\n const nums = [];\n for (let x of costs) nums.push(x);\n nums.sort((a, b) => abs(a - target) == abs(b - target) ? a - b : abs(a - target) - abs(b - target))\n return nums[0];\n \n};\n\nfunction dfs(toppingCosts, ind, m, cost, costs) {\n costs.add(cost);\n if (ind >= m) return;\n dfs(toppingCosts, ind + 1, m, cost, costs);\n dfs(toppingCosts, ind + 1, m, cost + toppingCosts[ind], costs);\n dfs(toppingCosts, ind + 1, m, cost + toppingCosts[ind] * 2, costs);\n}" ]
1,775
equal-sum-arrays-with-minimum-number-of-operations
[ "Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum.", "You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one." ]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var minOperations = function(nums1, nums2) { };
You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive. Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1​​​​​ if it is not possible to make the sum of the two arrays equal.   Example 1: Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2] Output: 3 Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. - Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2]. - Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2]. - Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2]. Example 2: Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6] Output: -1 Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal. Example 3: Input: nums1 = [6,6], nums2 = [1] Output: 3 Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. - Change nums1[0] to 2. nums1 = [2,6], nums2 = [1]. - Change nums1[1] to 2. nums1 = [2,2], nums2 = [1]. - Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].   Constraints: 1 <= nums1.length, nums2.length <= 105 1 <= nums1[i], nums2[i] <= 6
Medium
[ "array", "hash-table", "greedy", "counting" ]
[ "const minOperations = function(nums1, nums2) {\n const m = nums1.length, n = nums2.length\n if(m > n * 6 || n > m * 6) return -1\n let sum1 = sum(nums1), sum2 = sum(nums2)\n if(sum1 > sum2) return minOperations(nums2, nums1)\n\n const arr = Array(6).fill(0)\n nums1.forEach(e => arr[6 - e]++)\n nums2.forEach(e => arr[e - 1]++)\n\n let res = 0, i = 5\n while(sum1 < sum2) {\n while(arr[i] === 0) i--\n sum1 += i\n res++\n arr[i]--\n }\n\n return res\n};\n\nfunction sum(arr) {\n return arr.reduce((ac, e) => ac + e, 0)\n}", "const minOperations = function(nums1, nums2) {\n const m = nums1.length, n = nums2.length\n if(m > n * 6 || n > m * 6) return -1\n const sum1 = nums1.reduce((ac, e) => ac + e, 0)\n const sum2 = nums2.reduce((ac, e) => ac + e, 0)\n let largerArr, smallerArr\n if(sum1 === sum2) return 0\n if(sum1 > sum2) {\n largerArr = nums1\n smallerArr = nums2\n } else {\n largerArr = nums2\n smallerArr = nums1\n }\n \n const gain = []\n for(let e of largerArr) gain.push(e - 1)\n for(let e of smallerArr) gain.push(6 - e)\n gain.sort((a, b) => b - a)\n let diff = Math.abs(sum2 - sum1)\n let cnt = 0\n for(let e of gain) {\n diff -= e\n cnt++\n if(diff <= 0) return cnt\n }\n return -1\n};", "const minOperations = function(nums1, nums2) {\n const len1 = nums1.length, len2 = nums2.length;\n if (len1 > 6 * len2 || len2 > 6 * len1) return -1;\n let sum1 = 0, sum2 = 0;\n for (let x of nums1) sum1 += x;\n for (let x of nums2) sum2 += x;\n if (sum1 === sum2) return 0;\n nums1.sort((a, b) => a - b)\n nums2.sort((a, b) => a - b)\n let cnt = 0;\n if (sum1 > sum2) {\n let ind1 = len1 - 1, ind2 = 0;\n while (sum1 > sum2) { \n if (ind2 === len2 || nums1[ind1] - 1 > 6 - nums2[ind2]) sum1 -= nums1[ind1--] - 1;\n else sum2 += 6 - nums2[ind2++];\n cnt++;\n }\n return cnt;\n }\n let ind1 = 0, ind2 = len2 - 1;\n while (sum1 < sum2) {\n if (ind1 === len1 || nums2[ind2] - 1 > 6 - nums1[ind1]) sum2 -= nums2[ind2--] - 1;\n else sum1 += 6 - nums1[ind1++];\n cnt++;\n }\n return cnt;\n};" ]
1,776
car-fleet-ii
[ "We can simply ignore the merging of any car fleet, simply assume they cross each other. Now the aim is to find the first car to the right, which intersects with the current car before any other.", "Assume we have already considered all cars to the right already, now the current car is to be considered. Let’s ignore all cars with speeds higher than the current car since the current car cannot intersect with those ones. Now, all cars to the right having speed strictly less than current car are to be considered. Now, for two cars c1 and c2 with positions p1 and p2 (p1 < p2) and speed s1 and s2 (s1 > s2), if c1 and c2 intersect before the current car and c2, then c1 can never be the first car of intersection for any car to the left of current car including current car. So we can remove that car from our consideration.", "We can see that we can maintain candidate cars in this way using a stack, removing cars with speed greater than or equal to current car, and then removing cars which can never be first point of intersection. The first car after this process (if any) would be first point of intersection." ]
/** * @param {number[][]} cars * @return {number[]} */ var getCollisionTimes = function(cars) { };
There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents: positioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1. speedi is the initial speed of the ith car in meters per second. For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet. Return an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted.   Example 1: Input: cars = [[1,2],[2,1],[4,3],[7,2]] Output: [1.00000,-1.00000,3.00000,-1.00000] Explanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s. Example 2: Input: cars = [[3,4],[5,4],[6,3],[9,1]] Output: [2.00000,1.00000,1.50000,-1.00000]   Constraints: 1 <= cars.length <= 105 1 <= positioni, speedi <= 106 positioni < positioni+1
Hard
[ "array", "math", "stack", "heap-priority-queue", "monotonic-stack" ]
[ "const getCollisionTimes = function(cars) {\n const n = cars.length;\n const stack = [];\n const res = Array(n)\n for(let i = n - 1; i >= 0; i--) {\n const [p, s] = cars[i]\n res[i] = -1\n while(stack.length) {\n const j = stack[stack.length - 1]\n const [p2, s2] = cars[j]\n if(s2 >= s || res[j] > 0 && (p2 - p) / (s - s2) >= res[j]) stack.pop()\n else break\n }\n if(stack.length) {\n const j = stack[stack.length - 1]\n const [p2, s2] = cars[j]\n res[i] = (p2 - p) / (s - s2)\n }\n stack.push(i)\n }\n \n return res\n};", "var getCollisionTimes = function(cars) {\n //这道题必须想清楚一点,那就是如果ans[i]有正值,那么一定是cars[i]和某个cars[j](j>i且speed[j]<speed[i])\n //相撞之后,所谓的融合,其实可以理解为cars[i]消失了,cars[j]状态不变\n //所以我们只关注一辆车后面,不关注其前面,它的前面对它没有任何影响。可以考虑从后往前遍历\n const n = cars.length\n const ans = Array(n).fill(0)\n //设立一个类似单调栈的栈,栈底最慢,栈顶最快\n const stack = []\n for(let i = n - 1; i >= 0; i--) {\n while(stack.length) {\n //如果栈顶比我快,我追不上它,可以考虑等它消失之后我去撞它前面的,所以将它pop\n if(cars[stack[stack.length - 1]][1] >= cars[i][1]) stack.pop()\n //如果栈顶比我慢,我就决定去碰它了\n else {\n //如果它不会消失,那我肯定能碰它,break\n if(ans[stack[stack.length - 1]] < 0) break\n //如果它会消失,我需要计算一下在它消失之前能否追上它\n const d = ans[stack[stack.length - 1]] * (cars[i][1] - cars[stack[stack.length - 1]][1])\n //能追上,那我肯定碰它,break\n if(d > cars[stack[stack.length - 1]][0] - cars[i][0]) break\n //追不上,那算了,追它前面的车\n else stack.pop()\n }\n }\n if(stack.length === 0) ans[i] = -1\n else {\n //相对距离除以相对速度\n const t = (cars[stack[stack.length - 1]][0]-cars[i][0])/(cars[i][1]-cars[stack[stack.length - 1]][1])\n ans[i] = t\n }\n stack.push(i)\n }\n return ans\n};", "var getCollisionTimes = function (cars) {\n let n = cars.length,\n t = 0,\n i\n const ans = Array(n)\n for (let i = 0; i < n; i++) ans[i] = -1\n const s = []\n s[++t] = n - 1\n for (let i = n - 2; ~i; i--) {\n while (t && cars[s[t]][1] >= cars[i][1]) t--\n while (\n t > 1 &&\n (cars[s[t]][0] - cars[i][0]) * (cars[i][1] - cars[s[t - 1]][1]) >\n (cars[s[t - 1]][0] - cars[i][0]) * (cars[i][1] - cars[s[t]][1])\n )\n t--\n if (t) ans[i] = (cars[s[t]][0] - cars[i][0]) / (cars[i][1] - cars[s[t]][1])\n s[++t] = i\n }\n return ans\n}" ]
1,779
find-nearest-point-that-has-the-same-x-or-y-coordinate
[ "Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location." ]
/** * @param {number} x * @param {number} y * @param {number[][]} points * @return {number} */ var nearestValidPoint = function(x, y, points) { };
You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location. Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1. The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).   Example 1: Input: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]] Output: 2 Explanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2. Example 2: Input: x = 3, y = 4, points = [[3,4]] Output: 0 Explanation: The answer is allowed to be on the same location as your current location. Example 3: Input: x = 3, y = 4, points = [[2,3]] Output: -1 Explanation: There are no valid points.   Constraints: 1 <= points.length <= 104 points[i].length == 2 1 <= x, y, ai, bi <= 104
Easy
[ "array" ]
[ "const nearestValidPoint = function(x, y, points) {\n let idx = -1, dis = Infinity\n const {min, max, abs} = Math\n for(let i = 0; i < points.length; i++) {\n const e = points[i]\n const [tx, ty] = e\n if(tx === x || ty === y) {\n const tmp = abs(tx - x) + abs(ty - y)\n if(tmp < dis) {\n idx = i\n dis = tmp\n }\n }\n }\n \n return idx === -1 ? -1 : idx\n};" ]
1,780
check-if-number-is-a-sum-of-powers-of-three
[ "Let's note that the maximum power of 3 you'll use in your soln is 3^16", "The number can not be represented as a sum of powers of 3 if it's ternary presentation has a 2 in it" ]
/** * @param {number} n * @return {boolean} */ var checkPowersOfThree = function(n) { };
Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false. An integer y is a power of three if there exists an integer x such that y == 3x.   Example 1: Input: n = 12 Output: true Explanation: 12 = 31 + 32 Example 2: Input: n = 91 Output: true Explanation: 91 = 30 + 32 + 34 Example 3: Input: n = 21 Output: false   Constraints: 1 <= n <= 107
Medium
[ "math" ]
[ "const checkPowersOfThree = function(n) {\n const num = ~~(n / 3)\n const rem = n % 3\n if(num === 0 && rem === 1) return true\n if(rem === 2) return false\n return checkPowersOfThree(num)\n};" ]
1,781
sum-of-beauty-of-all-substrings
[ "Maintain a prefix sum for the frequencies of characters.", "You can iterate over all substring then iterate over the alphabet and find which character appears most and which appears least using the prefix sum array" ]
/** * @param {string} s * @return {number} */ var beautySum = function(s) { };
The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. For example, the beauty of "abaacc" is 3 - 1 = 2. Given a string s, return the sum of beauty of all of its substrings.   Example 1: Input: s = "aabcb" Output: 5 Explanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1. Example 2: Input: s = "aabcbaa" Output: 17   Constraints: 1 <= s.length <= 500 s consists of only lowercase English letters.
Medium
[ "hash-table", "string", "counting" ]
[ "const beautySum = function(s) {\n let ans = 0\n const a = 'a'.charCodeAt(0)\n const min = arr => {\n let res = Infinity\n for(let e of arr) {\n if(e !== 0) res = Math.min(e, res)\n }\n return res\n }\n for(let i = 0, n = s.length; i < n; i++) {\n let freq = Array(26).fill(0)\n for(let j = i; j < n; j++) {\n freq[s.charCodeAt(j) - a]++\n ans += Math.max(...freq) - min(freq)\n }\n }\n return ans \n};" ]
1,782
count-pairs-of-nodes
[ "We want to count pairs (x,y) such that degree[x] + degree[y] - occurrences(x,y) > k", "Think about iterating on x, and counting the number of valid y to pair with x.", "You can consider at first that the (- occurrences(x,y)) isn't there, or it is 0 at first for all y. Count the valid y this way.", "Then you can iterate on the neighbors of x, let that neighbor be y, and update occurrences(x,y).", "When you update occurrences(x,y), the left-hand side decreases. Once it reaches k, then y is not valid for x anymore, so you should decrease the answer by 1." ]
/** * @param {number} n * @param {number[][]} edges * @param {number[]} queries * @return {number[]} */ var countPairs = function(n, edges, queries) { };
You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries. Let incident(a, b) be defined as the number of edges that are connected to either node a or b. The answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the following conditions: a < b incident(a, b) > queries[j] Return an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query. Note that there can be multiple edges between the same two nodes.   Example 1: Input: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3] Output: [6,5] Explanation: The calculations for incident(a, b) are shown in the table above. The answers for each of the queries are as follows: - answers[0] = 6. All the pairs have an incident(a, b) value greater than 2. - answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3. Example 2: Input: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5] Output: [10,10,9,8,6]   Constraints: 2 <= n <= 2 * 104 1 <= edges.length <= 105 1 <= ui, vi <= n ui != vi 1 <= queries.length <= 20 0 <= queries[j] < edges.length
Hard
[ "array", "two-pointers", "binary-search", "graph", "sorting" ]
null
[]
1,784
check-if-binary-string-has-at-most-one-segment-of-ones
[ "It's guaranteed to have at least one segment", "The string size is small so you can count all segments of ones with no that have no adjacent ones." ]
/** * @param {string} s * @return {boolean} */ var checkOnesSegment = function(s) { };
Given a binary string s ​​​​​without leading zeros, return true​​​ if s contains at most one contiguous segment of ones. Otherwise, return false.   Example 1: Input: s = "1001" Output: false Explanation: The ones do not form a contiguous segment. Example 2: Input: s = "110" Output: true   Constraints: 1 <= s.length <= 100 s[i]​​​​ is either '0' or '1'. s[0] is '1'.
Easy
[ "string" ]
[ "const checkOnesSegment = function(s) {\n let res = 1\n for(let i = 1, len = s.length; i < len; i++) {\n if(s[i] === '1' && s[i - 1] === '0') res++\n if(s[i] === '1' && s[i - 1] === '1') continue\n }\n return res <= 1\n};" ]
1,785
minimum-elements-to-add-to-form-a-given-sum
[ "Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit.", "You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit).", "You can \"normalize\" goal by offsetting it by the sum of the array. For example, if the goal is 5 and the sum is -3, then it's exactly the same as if the goal is 8 and the array is empty.", "The answer is ceil(abs(goal-sum)/limit) = (abs(goal-sum)+limit-1) / limit." ]
/** * @param {number[]} nums * @param {number} limit * @param {number} goal * @return {number} */ var minElements = function(nums, limit, goal) { };
You are given an integer array nums and two integers limit and goal. The array nums has an interesting property that abs(nums[i]) <= limit. Return the minimum number of elements you need to add to make the sum of the array equal to goal. The array must maintain its property that abs(nums[i]) <= limit. Note that abs(x) equals x if x >= 0, and -x otherwise.   Example 1: Input: nums = [1,-1,1], limit = 3, goal = -4 Output: 2 Explanation: You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4. Example 2: Input: nums = [1,-10,9,1], limit = 100, goal = 0 Output: 1   Constraints: 1 <= nums.length <= 105 1 <= limit <= 106 -limit <= nums[i] <= limit -109 <= goal <= 109
Medium
[ "array", "greedy" ]
[ "const minElements = function(nums, limit, goal) {\n const sum = nums.reduce((ac, e) => ac + e, 0)\n let delta = goal - sum\n if(delta === 0) return 0\n const op = delta > 0 ? '+' : '-'\n let res = 0\n delta = Math.abs(delta)\n return Math.floor(delta / limit) + (delta % limit > 0 ? 1 : 0)\n};" ]
1,786
number-of-restricted-paths-from-first-to-last-node
[ "Run a Dijkstra from node numbered n to compute distance from the last node.", "Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge.", "Now this problem reduces to computing the number of paths from 1 to n in a DAG, a standard DP problem." ]
/** * @param {number} n * @param {number[][]} edges * @return {number} */ var countRestrictedPaths = function(n, edges) { };
There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti. A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1. The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1. Return the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 109 + 7.   Example 1: Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]] Output: 3 Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are: 1) 1 --> 2 --> 5 2) 1 --> 2 --> 3 --> 5 3) 1 --> 3 --> 5 Example 2: Input: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]] Output: 1 Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7.   Constraints: 1 <= n <= 2 * 104 n - 1 <= edges.length <= 4 * 104 edges[i].length == 3 1 <= ui, vi <= n ui != vi 1 <= weighti <= 105 There is at most one edge between any two nodes. There is at least one path between any two nodes.
Medium
[ "dynamic-programming", "graph", "topological-sort", "heap-priority-queue", "shortest-path" ]
[ "const countRestrictedPaths = function(n, edges) {\n const adj = {}\n const MOD = 10 ** 9 + 7\n for(let edge of edges) {\n const [u,v,d] = edge\n if(adj[u] == null) adj[u] = []\n if(adj[v] == null) adj[v] = []\n adj[u].push([v, d])\n adj[v].push([u, d])\n }\n const dist = Array(n + 1).fill(Infinity)\n dist[n] = 0\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n pq.push([0, n])\n while(!pq.isEmpty()) {\n const [d, u] = pq.peek()\n pq.pop()\n if(d > dist[u]) continue\n for(let [v, c] of adj[u]) {\n if(d + c < dist[v]) {\n dist[v] = d + c\n pq.push([dist[v], v])\n }\n }\n }\n \n const order = Array(n).fill(0)\n for(let i = 0; i < n; i++) {\n order[i] = i + 1\n }\n \n order.sort((u, v) => dist[u] - dist[v])\n const ans = Array(n + 1).fill(0)\n ans[n] = 1\n for(let u of order) {\n for(let [v, c] of adj[u]) {\n if(dist[v] > dist[u]) {\n ans[v] = (ans[v] + ans[u]) % MOD\n }\n }\n }\n \n return ans[1]\n};\n\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}", "const countRestrictedPaths = function(n, edges) {\n if (n === 1) return 0\n const graph = {}\n for(const [u, v, t] of edges) {\n if(graph[u] == null) graph[u] = {}\n if(graph[v] == null) graph[v] = {}\n graph[u][v] = t\n graph[v][u] = t\n }\n const dist = dijkstra(n, graph)\n const memo = Array(n + 1).fill(null)\n const res = dfs(1)\n return res\n\n function dijkstra(n, graph) {\n const dist = Array(n + 1).fill(Infinity)\n dist[n] = 0\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n pq.push([0, n])\n while(!pq.isEmpty()) {\n const [d, cur] = pq.pop()\n if(d !== dist[cur]) continue\n for(const next of Object.keys(graph[cur] || {})) {\n const delta = graph[cur][next]\n if(dist[next] > d + delta) {\n dist[next] = d + delta\n pq.push([d + delta, next])\n } \n }\n }\n return dist\n }\n\n function dfs(src) {\n if(memo[src] != null) return memo[src]\n if(src === n) return 1\n let res = 0\n for(let next of Object.keys(graph[src] || {})) {\n next = +next\n if(dist[src] > dist[next]) {\n res = ((res + dfs(next)) % (1e9 + 7))\n }\n }\n return memo[src] = res\n }\n}" ]
1,787
make-the-xor-of-all-segments-equal-to-zero
[ "Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k]", "Basically, we need to make the first K elements have XOR = 0 and then modify them." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var minChanges = function(nums, k) { };
You are given an array nums​​​ and an integer k​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right]. Return the minimum number of elements to change in the array such that the XOR of all segments of size k​​​​​​ is equal to zero.   Example 1: Input: nums = [1,2,0,3,0], k = 1 Output: 3 Explanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0]. Example 2: Input: nums = [3,4,5,2,1,7,3,4,7], k = 3 Output: 3 Explanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7]. Example 3: Input: nums = [1,2,4,1,2,5,1,2,6], k = 3 Output: 3 Explanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].   Constraints: 1 <= k <= nums.length <= 2000 ​​​​​​0 <= nums[i] < 210
Hard
[ "array", "dynamic-programming", "bit-manipulation" ]
[ "const L = 2 ** 10;\nconst MAX = Number.MAX_SAFE_INTEGER;\nconst mi = Math.min;\nconst minChanges = (a, k) => {\n let n = a.length;\n let dp = Array(L).fill(MAX);\n dp[0] = 0;\n for (let i = 0; i < k; i++) {\n let tmp = Array(L).fill(0);\n let tot = 0;\n for (let j = i; j < n; j += k) {\n tmp[a[j]]++; // frequency count of starting points from each kth continuous subarray\n tot++; // total count of starting points from each kth continuous subarray\n }\n let ndp = Array(L).fill(0);\n let min = MAX;\n for (let j = 0; j < L; j++) {\n min = mi(min, dp[j]);\n }\n min += tot;\n ndp = ndp.map(x => x = min); // updated nested dp array with min value\n for (let j = 0; j < L; j++) {\n if (tmp[j] != 0) {\n for (let m = 0; m < L; m++) {\n ndp[m ^ j] = mi(ndp[m ^ j], dp[m] + tot - tmp[j]);\n }\n }\n }\n dp = ndp; // reset dp\n }\n return dp[0];\n};" ]
1,790
check-if-one-string-swap-can-make-strings-equal
[ "The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2.", "Check that these positions have the same set of characters." ]
/** * @param {string} s1 * @param {string} s2 * @return {boolean} */ var areAlmostEqual = function(s1, s2) { };
You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.   Example 1: Input: s1 = "bank", s2 = "kanb" Output: true Explanation: For example, swap the first character with the last character of s2 to make "bank". Example 2: Input: s1 = "attack", s2 = "defend" Output: false Explanation: It is impossible to make them equal with one string swap. Example 3: Input: s1 = "kelb", s2 = "kelb" Output: true Explanation: The two strings are already equal, so no string swap operation is required.   Constraints: 1 <= s1.length, s2.length <= 100 s1.length == s2.length s1 and s2 consist of only lowercase English letters.
Easy
[ "hash-table", "string", "counting" ]
[ "const areAlmostEqual = function(s1, s2) {\n if (s1 === s2) return true\n let arr = []\n for(let i = 0, len = s1.length; i < len; i++) {\n if(s1[i] !== s2[i]) arr.push(i)\n \n if(arr.length > 2) return false\n }\n \n if(arr.length === 1) return false\n const [i1, i2] = arr\n if(s1[i2] === s2[i1] && s1[i1] === s2[i2]) return true\n return false\n};" ]
1,791
find-center-of-star-graph
[ "The center is the only node that has more than one edge.", "The center is also connected to all other nodes.", "Any two edges must have a common node, which is the center." ]
/** * @param {number[][]} edges * @return {number} */ var findCenter = function(edges) { };
There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.   Example 1: Input: edges = [[1,2],[2,3],[4,2]] Output: 2 Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center. Example 2: Input: edges = [[1,2],[5,1],[1,3],[1,4]] Output: 1   Constraints: 3 <= n <= 105 edges.length == n - 1 edges[i].length == 2 1 <= ui, vi <= n ui != vi The given edges represent a valid star graph.
Easy
[ "graph" ]
[ "const findCenter = function(edges) {\n return edges[0][0] === edges[1][0] || edges[0][0] === edges[1][1] ? edges[0][0] : edges[0][1]\n};", "const findCenter = function(edges) {\n const map = {}\n for(let e of edges) {\n const [u, v] = e\n if(map[u] == null) map[u] = []\n if(map[v] == null) map[v] = []\n map[u].push(v)\n map[v].push(u)\n }\n \n const keys = Object.keys(map)\n let res, max = -Infinity\n keys.forEach(e => {\n if(map[e].length > max) {\n res = e\n max = map[e].length\n }\n })\n \n return res\n \n};" ]
1,792
maximum-average-pass-ratio
[ "Pay attention to how much the pass ratio changes when you add a student to the class. If you keep adding students, what happens to the change in pass ratio? The more students you add to a class, the smaller the change in pass ratio becomes.", "Since the change in the pass ratio is always decreasing with the more students you add, then the very first student you add to each class is the one that makes the biggest change in the pass ratio.", "Because each class's pass ratio is weighted equally, it's always optimal to put the student in the class that makes the biggest change among all the other classes.", "Keep a max heap of the current class sizes and order them by the change in pass ratio. For each extra student, take the top of the heap, update the class size, and put it back in the heap." ]
/** * @param {number[][]} classes * @param {number} extraStudents * @return {number} */ var maxAverageRatio = function(classes, extraStudents) { };
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam. You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes. The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes. Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2 Output: 0.78333 Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. Example 2: Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4 Output: 0.53485   Constraints: 1 <= classes.length <= 105 classes[i].length == 2 1 <= passi <= totali <= 105 1 <= extraStudents <= 105
Medium
[ "array", "greedy", "heap-priority-queue" ]
[ "const maxAverageRatio = function (classes, extraStudents) {\n const pq = new PriorityQueue((a, b) => a.delta > b.delta)\n const n = classes.length\n for (let e of classes) {\n pq.push({\n pass: e[0],\n total: e[1],\n ratio: e[0] / e[1],\n delta: (e[0] + 1) / (e[1] + 1) - e[0] / e[1],\n })\n }\n\n while (extraStudents) {\n const tmp = pq.pop()\n tmp.pass++\n tmp.total++\n tmp.ratio = tmp.pass / tmp.total\n tmp.delta = (tmp.pass + 1) / (tmp.total + 1) - tmp.ratio\n pq.push(tmp)\n extraStudents--\n }\n\n let res = 0\n while (!pq.isEmpty()) {\n const tmp = pq.pop()\n res += tmp.ratio\n }\n\n return res / 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 maxAverageRatio = function(classes, extraStudents) {\n const pq = new PriorityQueue((a, b) => a.up > b.up);\n for (let x of classes) pq.push(new Node(x[0], x[1]));\n while (extraStudents--) {\n let temp = pq.peek();\n pq.pop();\n temp.pass++, temp.total++;\n temp.calUp();\n pq.push(temp);\n }\n let total = 0.0;\n let n = classes.length;\n while (!pq.isEmpty()) {\n let temp = pq.peek();\n pq.pop();\n total += temp.pass / temp.total;\n }\n return total / n;\n};\n\nclass Node {\n constructor(pass, total) {\n this.pass = pass\n this.total = total\n this.calUp()\n }\n calUp() {\n this.up = (this.pass + 1) / (this.total + 1) - this.pass / this.total\n }\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}" ]
1,793
maximum-score-of-a-good-subarray
[ "Try thinking about the prefix before index k and the suffix after index k as two separate arrays.", "Using two pointers or binary search, we can find the maximum prefix of each array where the numbers are less than or equal to a certain value" ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var maximumScore = function(nums, k) { };
You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j. Return the maximum possible score of a good subarray.   Example 1: Input: nums = [1,4,3,7,4,5], k = 3 Output: 15 Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. Example 2: Input: nums = [5,5,4,5,4,1,1,1], k = 0 Output: 20 Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 2 * 104 0 <= k < nums.length
Hard
[ "array", "two-pointers", "binary-search", "stack", "monotonic-stack" ]
[ "const maximumScore = function(nums, k) {\n const n = nums.length, {min, max} = Math\n let mini = nums[k];\n let ans = mini;\n let i = k;\n let j = k;\n\n while (i > 0 || j < n - 1) {\n if (i === 0 || (j + 1 < n && nums[i - 1] <= nums[j + 1])) {\n j++;\n mini = min(mini, nums[j]);\n } else {\n i--;\n mini = min(mini, nums[i]);\n }\n ans = max(ans, mini * (j - i + 1));\n }\n\n return ans;\n};", "const maximumScore = function(nums, k) {\n const n = nums.length, { max, min } = Math\n let l = k, r = k, mi = nums[k]\n let res = nums[k]\n while(l > 0 || r < n - 1) {\n if(l === 0) r++\n else if(r === n - 1) l--\n else if(nums[l - 1] < nums[r + 1]) r++\n else l--\n mi = min(mi, nums[l], nums[r])\n res = max(res, mi * (r - l + 1))\n }\n \n return res\n};" ]
1,796
second-largest-digit-in-a-string
[ "First of all, get the distinct characters since we are only interested in those", "Let's note that there might not be any digits." ]
/** * @param {string} s * @return {number} */ var secondHighest = function(s) { };
Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist. An alphanumeric string is a string consisting of lowercase English letters and digits.   Example 1: Input: s = "dfa12321afd" Output: 2 Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2. Example 2: Input: s = "abc1111" Output: -1 Explanation: The digits that appear in s are [1]. There is no second largest digit.   Constraints: 1 <= s.length <= 500 s consists of only lowercase English letters and/or digits.
Easy
[ "hash-table", "string" ]
null
[]
1,797
design-authentication-manager
[ "Using a map, track the expiry times of the tokens.", "When generating a new token, add it to the map with its expiry time.", "When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time.", "To count unexpired tokens, iterate on the map and check for each token if it's not expired yet." ]
/** * @param {number} timeToLive */ var AuthenticationManager = function(timeToLive) { }; /** * @param {string} tokenId * @param {number} currentTime * @return {void} */ AuthenticationManager.prototype.generate = function(tokenId, currentTime) { }; /** * @param {string} tokenId * @param {number} currentTime * @return {void} */ AuthenticationManager.prototype.renew = function(tokenId, currentTime) { }; /** * @param {number} currentTime * @return {number} */ AuthenticationManager.prototype.countUnexpiredTokens = function(currentTime) { }; /** * Your AuthenticationManager object will be instantiated and called as such: * var obj = new AuthenticationManager(timeToLive) * obj.generate(tokenId,currentTime) * obj.renew(tokenId,currentTime) * var param_3 = obj.countUnexpiredTokens(currentTime) */
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime. If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime. Implement the AuthenticationManager class: AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive. generate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds. renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId, the request is ignored, and nothing happens. countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime. Note that if a token expires at time t, and another action happens on time t (renew or countUnexpiredTokens), the expiration takes place before the other actions.   Example 1: Input ["AuthenticationManager", "renew", "generate", "countUnexpiredTokens", "generate", "renew", "renew", "countUnexpiredTokens"] [[5], ["aaa", 1], ["aaa", 2], [6], ["bbb", 7], ["aaa", 8], ["bbb", 10], [15]] Output [null, null, null, 1, null, null, null, 0] Explanation AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with timeToLive = 5 seconds. authenticationManager.renew("aaa", 1); // No token exists with tokenId "aaa" at time 1, so nothing happens. authenticationManager.generate("aaa", 2); // Generates a new token with tokenId "aaa" at time 2. authenticationManager.countUnexpiredTokens(6); // The token with tokenId "aaa" is the only unexpired one at time 6, so return 1. authenticationManager.generate("bbb", 7); // Generates a new token with tokenId "bbb" at time 7. authenticationManager.renew("aaa", 8); // The token with tokenId "aaa" expired at time 7, and 8 >= 7, so at time 8 the renew request is ignored, and nothing happens. authenticationManager.renew("bbb", 10); // The token with tokenId "bbb" is unexpired at time 10, so the renew request is fulfilled and now the token will expire at time 15. authenticationManager.countUnexpiredTokens(15); // The token with tokenId "bbb" expires at time 15, and the token with tokenId "aaa" expired at time 7, so currently no token is unexpired, so return 0.   Constraints: 1 <= timeToLive <= 108 1 <= currentTime <= 108 1 <= tokenId.length <= 5 tokenId consists only of lowercase letters. All calls to generate will contain unique values of tokenId. The values of currentTime across all the function calls will be strictly increasing. At most 2000 calls will be made to all functions combined.
Medium
[ "hash-table", "design" ]
null
[]
1,798
maximum-number-of-consecutive-values-you-can-make
[ "If you can make the first x values and you have a value v, then you can make all the values <var>≤ v + x</var>", "Sort the array of coins. You can always make the value 0 so you can start with x = 0.", "Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x." ]
/** * @param {number[]} coins * @return {number} */ var getMaximumConsecutive = function(coins) { };
You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x. Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0. Note that you may have multiple coins of the same value.   Example 1: Input: coins = [1,3] Output: 2 Explanation: You can make the following values: - 0: take [] - 1: take [1] You can make 2 consecutive integer values starting from 0. Example 2: Input: coins = [1,1,1,4] Output: 8 Explanation: You can make the following values: - 0: take [] - 1: take [1] - 2: take [1,1] - 3: take [1,1,1] - 4: take [4] - 5: take [4,1] - 6: take [4,1,1] - 7: take [4,1,1,1] You can make 8 consecutive integer values starting from 0. Example 3: Input: nums = [1,4,10,3,1] Output: 20   Constraints: coins.length == n 1 <= n <= 4 * 104 1 <= coins[i] <= 4 * 104
Medium
[ "array", "greedy" ]
[ "const getMaximumConsecutive = function(coins) {\n coins.sort((a, b) => a - b);\n let res = 1;\n for (let a of coins) {\n if (a > res) break;\n res += a;\n }\n return res; \n};" ]
1,799
maximize-score-after-n-operations
[ "Find every way to split the array until n groups of 2. Brute force recursion is acceptable.", "Calculate the gcd of every pair and greedily multiply the largest gcds." ]
/** * @param {number[]} nums * @return {number} */ var maxScore = function(nums) { };
You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array. In the ith operation (1-indexed), you will: Choose two elements, x and y. Receive a score of i * gcd(x, y). Remove x and y from nums. Return the maximum score you can receive after performing n operations. The function gcd(x, y) is the greatest common divisor of x and y.   Example 1: Input: nums = [1,2] Output: 1 Explanation: The optimal choice of operations is: (1 * gcd(1, 2)) = 1 Example 2: Input: nums = [3,4,6,8] Output: 11 Explanation: The optimal choice of operations is: (1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11 Example 3: Input: nums = [1,2,3,4,5,6] Output: 14 Explanation: The optimal choice of operations is: (1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14   Constraints: 1 <= n <= 7 nums.length == 2 * n 1 <= nums[i] <= 106
Hard
[ "array", "math", "dynamic-programming", "backtracking", "bit-manipulation", "number-theory", "bitmask" ]
[ "const maxScore = function (nums) {\n const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b))\n const n = nums.length / 2\n const memo = {}\n const traverse = (op, mask) => {\n if (op > n) {\n return 0\n }\n const idx = op * 100000 + mask\n if (memo[idx] === undefined) {\n let res = 0\n for (let i = 0; i < 2 * n - 1; i++) {\n if (mask & (1 << i)) continue\n for (let j = i + 1; j < 2 * n; j++) {\n if (mask & (1 << j)) continue\n const newMask = mask | (1 << i) | (1 << j)\n res = Math.max(\n res,\n traverse(op + 1, newMask) + op * gcd(nums[i], nums[j])\n )\n }\n }\n memo[idx] = res\n }\n return memo[idx]\n }\n const res = traverse(1, 0)\n return res\n}" ]
1,800
maximum-ascending-subarray-sum
[ "It is fast enough to check all possible subarrays", "The end of each ascending subarray will be the start of the next" ]
/** * @param {number[]} nums * @return {number} */ var maxAscendingSum = function(nums) { };
Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums. A subarray is defined as a contiguous sequence of numbers in an array. A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending.   Example 1: Input: nums = [10,20,30,5,10,50] Output: 65 Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65. Example 2: Input: nums = [10,20,30,40,50] Output: 150 Explanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150. Example 3: Input: nums = [12,17,15,13,10,11,12] Output: 33 Explanation: [10,11,12] is the ascending subarray with the maximum sum of 33.   Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100
Easy
[ "array" ]
[ "const maxAscendingSum = function(nums) {\n let res = -Infinity\n \n const n = nums.length\n let cur = 0\n for(let i = 0; i < n; i++) {\n if(i === 0) cur = nums[i]\n if(i > 0) {\n if(nums[i] > nums[i - 1]) {\n cur += nums[i]\n res = Math.max(res, cur)\n } else {\n res = Math.max(res, cur)\n cur = nums[i]\n } \n }\n }\n res = Math.max(res, cur) \n return res\n};" ]
1,801
number-of-orders-in-the-backlog
[ "Store the backlog buy and sell orders in two heaps, the buy orders in a max heap by price and the sell orders in a min heap by price.", "Store the orders in batches and update the fields according to new incoming orders. Each batch should only take 1 \"slot\" in the heap." ]
/** * @param {number[][]} orders * @return {number} */ var getNumberOfBacklogOrders = function(orders) { };
You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is: 0 if it is a batch of buy orders, or 1 if it is a batch of sell orders. Note that orders[i] represents a batch of amounti independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i. There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens: If the order is a buy order, you look at the sell order with the smallest price in the backlog. If that sell order's price is smaller than or equal to the current buy order's price, they will match and be executed, and that sell order will be removed from the backlog. Else, the buy order is added to the backlog. Vice versa, if the order is a sell order, you look at the buy order with the largest price in the backlog. If that buy order's price is larger than or equal to the current sell order's price, they will match and be executed, and that buy order will be removed from the backlog. Else, the sell order is added to the backlog. Return the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7.   Example 1: Input: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]] Output: 6 Explanation: Here is what happens with the orders: - 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog. - 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog. - 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog. - 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog. Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6. Example 2: Input: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]] Output: 999999984 Explanation: Here is what happens with the orders: - 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog. - 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog. - 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog. - 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog. Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7).   Constraints: 1 <= orders.length <= 105 orders[i].length == 3 1 <= pricei, amounti <= 109 orderTypei is either 0 or 1.
Medium
[ "array", "heap-priority-queue", "simulation" ]
[ "const getNumberOfBacklogOrders = function(orders) {\n const buyPQ = new PQ((a, b) => a[0] > b[0])\n const sellPQ = new PQ((a, b) => a[0] < b[0])\n const mod = 1e9 + 7\n \n for(const e of orders) {\n const [p, a, o] = e\n if(o === 0) {\n // buy order\n if(sellPQ.isEmpty() || sellPQ.peek()[0] > p) {\n buyPQ.push(e)\n continue\n }\n while(!sellPQ.isEmpty() && sellPQ.peek()[0] <= p && e[1]) {\n const tmp = sellPQ.peek()\n if(e[1] <= tmp[1]) {\n tmp[1] -= e[1]\n e[1] = 0\n if(tmp[1] === 0) {\n sellPQ.pop()\n }\n } else {\n // e[1] > tmp[1]\n sellPQ.pop()\n e[1] -= tmp[1]\n }\n }\n if(e[1]) {\n buyPQ.push(e)\n }\n } else if(o === 1) {\n // sell order\n if(buyPQ.isEmpty() || buyPQ.peek()[0] < p) {\n sellPQ.push(e)\n continue\n }\n while(!buyPQ.isEmpty() && buyPQ.peek()[0] >= p && e[1]) {\n const tmp = buyPQ.peek()\n if(e[1] <= tmp[1]) {\n tmp[1] -= e[1]\n e[1] = 0\n if(tmp[1] === 0) {\n buyPQ.pop()\n }\n } else {\n // e[1] > tmp[1]\n buyPQ.pop()\n e[1] -= tmp[1]\n }\n }\n if(e[1]) {\n sellPQ.push(e)\n }\n }\n }\n \n let res = 0\n \n while(!buyPQ.isEmpty()) {\n res = (res + buyPQ.pop()[1]) % mod\n }\n while(!sellPQ.isEmpty()) {\n res = (res + sellPQ.pop()[1]) % mod\n }\n \n return res % mod\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}" ]
1,802
maximum-value-at-a-given-index-in-a-bounded-array
[ "What if the problem was instead determining if you could generate a valid array with nums[index] == target?", "To generate the array, set nums[index] to target, nums[index-i] to target-i, and nums[index+i] to target-i. Then, this will give the minimum possible sum, so check if the sum is less than or equal to maxSum.", "n is too large to actually generate the array, so you can use the formula 1 + 2 + ... + n = n * (n+1) / 2 to quickly find the sum of nums[0...index] and nums[index...n-1].", "Binary search for the target. If it is possible, then move the lower bound up. Otherwise, move the upper bound down." ]
/** * @param {number} n * @param {number} index * @param {number} maxSum * @return {number} */ var maxValue = function(n, index, maxSum) { };
You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions: nums.length == n nums[i] is a positive integer where 0 <= i < n. abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1. The sum of all the elements of nums does not exceed maxSum. nums[index] is maximized. Return nums[index] of the constructed array. Note that abs(x) equals x if x >= 0, and -x otherwise.   Example 1: Input: n = 4, index = 2, maxSum = 6 Output: 2 Explanation: nums = [1,2,2,1] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2]. Example 2: Input: n = 6, index = 1, maxSum = 10 Output: 3   Constraints: 1 <= n <= maxSum <= 109 0 <= index < n
Medium
[ "binary-search", "greedy" ]
[ "const maxValue = function (n, index, maxSum) {\n maxSum -= n;\n let left = 0, right = maxSum, mid;\n while (left < right) {\n const mid = right - Math.floor((right - left) / 2);\n if (valid(mid))left = mid;\n else right = mid - 1;\n }\n return left + 1;\n \n function valid(mid) {\n let b = Math.max(mid - index, 0);\n let res = (mid + b) * (mid - b + 1) / 2;\n b = Math.max(mid - ((n - 1) - index), 0);\n res += (mid + b) * (mid - b + 1) / 2;\n return res - mid <= maxSum;\n }\n}", "const maxValue = function(n, index, maxSum) {\n let res = 1, l = index, r = index\n maxSum -= n\n\n while(l > 0 || r < n - 1) {\n const len = r - l + 1\n if(maxSum >= len) {\n maxSum -= len \n res++\n } else break\n if(l > 0) l--\n if(r < n - 1) r++\n }\n res += ~~(maxSum / n)\n\n return res\n}", "const maxValue = function(n, index, maxSum) {\n maxSum -= n;\n let level = 1;\n let left = index;\n let right = index;\n\n while (maxSum - (right - left + 1) >= 0) {\n if (left === 0 && right === n - 1) break\n maxSum -= right - left + 1;\n if (left - 1 >= 0) left--\n if (right + 1 <= n - 1) right++;\n level++;\n }\n\n if (maxSum) level += ~~(maxSum / n)\n\n return level;\n}", "const maxValue = function(n, index, maxSum) {\n const { floor, sqrt } = Math\n maxSum -= n\n if(index < Math.floor(n / 2)) index = n - 1 - index\n let left = index // number of element to the left of the index\n let right = n - 1 - index // number of element to the right of the index\n // the triangle area for the left side if not hitting the boundary\n let leftSum = floor((left * (left + 1)) / 2)\n // the triangle area for the right side if not hitting the boundary\n let rightSum = floor((right * (right + 1)) / 2)\n // case: perfect pyramid\n if (maxSum <= (rightSum * 2 + right + 1)) return floor(sqrt(maxSum) + 1)\n // case: right side hits the boundary\n if (maxSum <= (leftSum + rightSum + (left - right) * right + left + 1)) {\n const b = 3 + 2 * right\n return floor((-b + sqrt(b * b - 8 * (rightSum + 1 - right * right - maxSum))) / 2) + 1 + 1\n }\n // case: both sides hit boundaries\n maxSum -= (leftSum + rightSum + (left - right) * right + left + 1)\n return left + 1 + 1 + floor(maxSum / n)\n};", "const maxValue = function (n, index, maxSum) {\n let ret = 0\n const { max } = Math\n for (let i = 30; i >= 0; i--) {\n const tmp = ret + (1 << i)\n const L = max(0, tmp - index)\n let sum = ((L + tmp) * (tmp - L + 1)) / 2\n const R = max(0, tmp - (n - 1 - index))\n sum += ((R + tmp) * (tmp - R + 1)) / 2 - tmp\n\n if (sum <= maxSum - n) ret += 1 << i\n }\n return ret + 1\n}" ]
1,803
count-pairs-with-xor-in-a-range
[ "Let's note that we can count all pairs with XOR ≤ K, so the answer would be to subtract the number of pairs withs XOR < low from the number of pairs with XOR ≤ high.", "For each value, find out the number of values when you XOR it with the result is ≤ K using a trie." ]
/** * @param {number[]} nums * @param {number} low * @param {number} high * @return {number} */ var countPairs = function(nums, low, high) { };
Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs. A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high.   Example 1: Input: nums = [1,4,2,7], low = 2, high = 6 Output: 6 Explanation: All nice pairs (i, j) are as follows: - (0, 1): nums[0] XOR nums[1] = 5 - (0, 2): nums[0] XOR nums[2] = 3 - (0, 3): nums[0] XOR nums[3] = 6 - (1, 2): nums[1] XOR nums[2] = 6 - (1, 3): nums[1] XOR nums[3] = 3 - (2, 3): nums[2] XOR nums[3] = 5 Example 2: Input: nums = [9,8,4,2,1], low = 5, high = 14 Output: 8 Explanation: All nice pairs (i, j) are as follows: ​​​​​ - (0, 2): nums[0] XOR nums[2] = 13   - (0, 3): nums[0] XOR nums[3] = 11   - (0, 4): nums[0] XOR nums[4] = 8   - (1, 2): nums[1] XOR nums[2] = 12   - (1, 3): nums[1] XOR nums[3] = 10   - (1, 4): nums[1] XOR nums[4] = 9   - (2, 3): nums[2] XOR nums[3] = 6   - (2, 4): nums[2] XOR nums[4] = 5   Constraints: 1 <= nums.length <= 2 * 104 1 <= nums[i] <= 2 * 104 1 <= low <= high <= 2 * 104
Hard
[ "array", "bit-manipulation", "trie" ]
[ "const countPairs = function (nums, low, high) {\n const trie = new Trie()\n\n let ans = 0\n for (let x of nums) {\n ans += trie.count(x, high + 1) - trie.count(x, low)\n trie.insert(x)\n }\n return ans\n}\n\nclass Trie {\n constructor() {\n this.root = {}\n }\n insert(val) {\n let node = this.root\n for (let i = 14; i >= 0; i--) {\n let bit = (val >> i) & 1\n if (!(bit in node)) node[bit] = { cnt: 1 }\n else node[bit]['cnt'] += 1\n node = node[bit]\n }\n }\n count(val, high) {\n let ans = 0\n let node = this.root\n for (let i = 14; i >= 0; i--) {\n if (!node) break\n const bit = (val >> i) & 1\n const cmp = (high >> i) & 1\n if (cmp) {\n if (node[bit]) ans += node[bit]['cnt']\n node = node[1 ^ bit]\n } else node = node[bit]\n }\n\n return ans\n }\n}" ]
1,805
number-of-different-integers-in-a-string
[ "Try to split the string so that each integer is in a different string.", "Try to remove each integer's leading zeroes and compare the strings to find how many of them are unique." ]
/** * @param {string} word * @return {number} */ var numDifferentIntegers = function(word) { };
You are given a string word that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123  34 8  34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "34". Return the number of different integers after performing the replacement operations on word. Two integers are considered different if their decimal representations without any leading zeros are different.   Example 1: Input: word = "a123bc34d8ef34" Output: 3 Explanation: The three different integers are "123", "34", and "8". Notice that "34" is only counted once. Example 2: Input: word = "leet1234code234" Output: 2 Example 3: Input: word = "a1b01c001" Output: 1 Explanation: The three integers "1", "01", and "001" all represent the same integer because the leading zeros are ignored when comparing their decimal values.   Constraints: 1 <= word.length <= 1000 word consists of digits and lowercase English letters.
Easy
[ "hash-table", "string" ]
[ "const numDifferentIntegers = function(word) {\n let cur = ''\n const n = word.length\n const set = new Set()\n for(let i = 0; i < n; i++ ) {\n if(word[i] >= '0' && word[i] <= '9') cur += word[i]\n else {\n if(cur) set.add(+cur)\n cur = ''\n }\n if(i === n - 1 && cur) set.add(+cur)\n }\n\n return set.size\n};" ]
1,806
minimum-number-of-operations-to-reinitialize-a-permutation
[ "It is safe to assume the number of operations isn't more than n", "The number is small enough to apply a brute force solution." ]
/** * @param {number} n * @return {number} */ var reinitializePermutation = function(n) { };
You are given an even integer n​​​​​​. You initially have a permutation perm of size n​​ where perm[i] == i​ (0-indexed)​​​​. In one operation, you will create a new array arr, and for each i: If i % 2 == 0, then arr[i] = perm[i / 2]. If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2]. You will then assign arr​​​​ to perm. Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.   Example 1: Input: n = 2 Output: 1 Explanation: perm = [0,1] initially. After the 1st operation, perm = [0,1] So it takes only 1 operation. Example 2: Input: n = 4 Output: 2 Explanation: perm = [0,1,2,3] initially. After the 1st operation, perm = [0,2,1,3] After the 2nd operation, perm = [0,1,2,3] So it takes only 2 operations. Example 3: Input: n = 6 Output: 4   Constraints: 2 <= n <= 1000 n​​​​​​ is even.
Medium
[ "array", "math", "simulation" ]
[ "const reinitializePermutation = function(n) {\n let perm = []\n for(let i = 0; i < n; i++) {\n perm[i] = i\n }\n let clone = perm.slice()\n let res = 0\n \n while(true) {\n res++\n let arr = clone.slice()\n for(let i = 0; i < clone.length; i++) {\n if(i % 2 === 0) arr[i] = clone[i / 2]\n else arr[i] = clone[n / 2 + (i - 1) / 2]\n }\n \n if(chk(perm, arr)) break\n clone = arr\n }\n \n \n return res\n \n function chk(a1, a2) {\n for(let i = 0, len = a1.length; i < len; i++) {\n if(a1[i] !== a2[i]) return false\n }\n return true\n }\n};", "const reinitializePermutation = function(n) {\n let res = 0, i = 1;\n while (res === 0 || i > 1) {\n i = i * 2 % (n - 1);\n res++;\n }\n return res;\n};", "const reinitializePermutation = function(n) {\n\tif (n === 2) return 1\n\tconst mod = n - 1\n\tlet curr_power = 2\n\tlet cnt = 1\n\t// Find multiplicative order modulo n-1\n\twhile (curr_power !== 1) {\n\t\tcurr_power = (2 * curr_power) % mod\n\t\tcnt++\n }\n\treturn cnt\n};" ]
1,807
evaluate-the-bracket-pairs-of-a-string
[ "Process pairs from right to left to handle repeats", "Keep track of the current enclosed string using another string" ]
/** * @param {string} s * @param {string[][]} knowledge * @return {string} */ var evaluate = function(s, knowledge) { };
You are given a string s that contains some bracket pairs, with each pair containing a non-empty key. For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain the keys "name" and "age". You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei. You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will: Replace keyi and the bracket pair with the key's corresponding valuei. If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark "?" (without the quotation marks). Each key will appear at most once in your knowledge. There will not be any nested brackets in s. Return the resulting string after evaluating all of the bracket pairs.   Example 1: Input: s = "(name)is(age)yearsold", knowledge = [["name","bob"],["age","two"]] Output: "bobistwoyearsold" Explanation: The key "name" has a value of "bob", so replace "(name)" with "bob". The key "age" has a value of "two", so replace "(age)" with "two". Example 2: Input: s = "hi(name)", knowledge = [["a","b"]] Output: "hi?" Explanation: As you do not know the value of the key "name", replace "(name)" with "?". Example 3: Input: s = "(a)(a)(a)aaa", knowledge = [["a","yes"]] Output: "yesyesyesaaa" Explanation: The same key can appear multiple times. The key "a" has a value of "yes", so replace all occurrences of "(a)" with "yes". Notice that the "a"s not in a bracket pair are not evaluated.   Constraints: 1 <= s.length <= 105 0 <= knowledge.length <= 105 knowledge[i].length == 2 1 <= keyi.length, valuei.length <= 10 s consists of lowercase English letters and round brackets '(' and ')'. Every open bracket '(' in s will have a corresponding close bracket ')'. The key in each bracket pair of s will be non-empty. There will not be any nested bracket pairs in s. keyi and valuei consist of lowercase English letters. Each keyi in knowledge is unique.
Medium
[ "array", "hash-table", "string" ]
[ "const evaluate = function(s, knowledge) {\n const map = {}\n for(let e of knowledge) {\n const [k, v] = e\n map[k] = v\n }\n const n = s.length\n let start = -1, end = 0\n let cur = ''\n const arr = []\n for(let i = 0; i < n; i++) {\n if(s[i] === '(') {\n start = i\n if(cur) {\n arr.push(cur)\n cur = ''\n }\n continue\n }\n else if(start !== -1 && s[i] !== ')') {\n cur += s[i]\n }\n else if(s[i] === ')') {\n if(cur in map) arr.push(map[cur])\n else arr.push('?')\n start = -1\n cur = ''\n } else {\n cur += s[i]\n }\n if(i === n - 1 && cur) arr.push(cur)\n }\n \n return arr.join('')\n \n};" ]
1,808
maximize-number-of-nice-divisors
[ "The number of nice divisors is equal to the product of the count of each prime factor. Then the problem is reduced to: given n, find a sequence of numbers whose sum equals n and whose product is maximized.", "This sequence can have no numbers that are larger than 4. Proof: if it contains a number x that is larger than 4, then you can replace x with floor(x/2) and ceil(x/2), and floor(x/2) * ceil(x/2) > x. You can also replace 4s with two 2s. Hence, there will always be optimal solutions with only 2s and 3s.", "If there are three 2s, you can replace them with two 3s to get a better product. Hence, you'll never have more than two 2s.", "Keep adding 3s as long as n ≥ 5." ]
/** * @param {number} primeFactors * @return {number} */ var maxNiceDivisors = function(primeFactors) { };
You are given a positive integer primeFactors. You are asked to construct a positive integer n that satisfies the following conditions: The number of prime factors of n (not necessarily distinct) is at most primeFactors. The number of nice divisors of n is maximized. Note that a divisor of n is nice if it is divisible by every prime factor of n. For example, if n = 12, then its prime factors are [2,2,3], then 6 and 12 are nice divisors, while 3 and 4 are not. Return the number of nice divisors of n. Since that number can be too large, return it modulo 109 + 7. Note that a prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The prime factors of a number n is a list of prime numbers such that their product equals n.   Example 1: Input: primeFactors = 5 Output: 6 Explanation: 200 is a valid value of n. It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200]. There is not other value of n that has at most 5 prime factors and more nice divisors. Example 2: Input: primeFactors = 8 Output: 18   Constraints: 1 <= primeFactors <= 109
Hard
[ "math", "recursion" ]
[ "const MOD = BigInt(1e9 + 7)\nconst maxNiceDivisors = (pf) => {\n if (pf == 1) return 1\n let bpf = BigInt(pf)\n let res\n if (pf % 3 == 0) {\n res = powmod(3n, bpf / 3n, MOD)\n } else if (pf % 3 == 1) {\n res = (powmod(3n, bpf / 3n - 1n, MOD) * 4n) % MOD\n } else {\n res = (powmod(3n, bpf / 3n, MOD) * 2n) % MOD\n }\n return Number(res)\n}\n\nconst powmod = (a, b, mod) => {\n let r = 1n\n while (b > 0n) {\n if (b % 2n == 1) r = (r * a) % mod\n b >>= 1n\n a = (a * a) % mod\n }\n return r\n}" ]
1,812
determine-color-of-a-chessboard-square
[ "Convert the coordinates to (x, y) - that is, \"a1\" is (1, 1), \"d7\" is (4, 7).", "Try add the numbers together and look for a pattern." ]
/** * @param {string} coordinates * @return {boolean} */ var squareIsWhite = function(coordinates) { };
You are given coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return true if the square is white, and false if the square is black. The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.   Example 1: Input: coordinates = "a1" Output: false Explanation: From the chessboard above, the square with coordinates "a1" is black, so return false. Example 2: Input: coordinates = "h3" Output: true Explanation: From the chessboard above, the square with coordinates "h3" is white, so return true. Example 3: Input: coordinates = "c7" Output: false   Constraints: coordinates.length == 2 'a' <= coordinates[0] <= 'h' '1' <= coordinates[1] <= '8'
Easy
[ "math", "string" ]
null
[]
1,813
sentence-similarity-iii
[ "One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence.", "Get the longest common prefix between them and the longest common suffix." ]
/** * @param {string} sentence1 * @param {string} sentence2 * @return {boolean} */ var areSentencesSimilar = function(sentence1, sentence2) { };
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, "Hello World", "HELLO", "hello world hello world" are all sentences. Words consist of only uppercase and lowercase English letters. Two sentences sentence1 and sentence2 are similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. For example, sentence1 = "Hello my name is Jane" and sentence2 = "Hello Jane" can be made equal by inserting "my name is" between "Hello" and "Jane" in sentence2. Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false.   Example 1: Input: sentence1 = "My name is Haley", sentence2 = "My Haley" Output: true Explanation: sentence2 can be turned to sentence1 by inserting "name is" between "My" and "Haley". Example 2: Input: sentence1 = "of", sentence2 = "A lot of words" Output: false Explanation: No single sentence can be inserted inside one of the sentences to make it equal to the other. Example 3: Input: sentence1 = "Eating right now", sentence2 = "Eating" Output: true Explanation: sentence2 can be turned to sentence1 by inserting "right now" at the end of the sentence.   Constraints: 1 <= sentence1.length, sentence2.length <= 100 sentence1 and sentence2 consist of lowercase and uppercase English letters and spaces. The words in sentence1 and sentence2 are separated by a single space.
Medium
[ "array", "two-pointers", "string" ]
null
[]
1,814
count-nice-pairs-in-an-array
[ "The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])).", "Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values.", "Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map. If it is, then add that count to the overall count. Then, increment the frequency of nums[i]." ]
/** * @param {number[]} nums * @return {number} */ var countNicePairs = function(nums) { };
You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions: 0 <= i < j < nums.length nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.   Example 1: Input: nums = [42,11,1,97] Output: 2 Explanation: The two pairs are: - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. Example 2: Input: nums = [13,10,35,24,76] Output: 4   Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109
Medium
[ "array", "hash-table", "math", "counting" ]
null
[]
1,815
maximum-number-of-groups-getting-fresh-donuts
[ "The maximum number of happy groups is the maximum number of partitions you can split the groups into such that the sum of group sizes in each partition is 0 mod batchSize. At most one partition is allowed to have a different remainder (the first group will get fresh donuts anyway).", "Suppose you have an array freq of length k where freq[i] = number of groups of size i mod batchSize. How can you utilize this in a dp solution?", "Make a DP state dp[freq][r] that represents \"the maximum number of partitions you can form given the current freq and current remainder r\". You can hash the freq array to store it more easily in the dp table.", "For each i from 0 to batchSize-1, the next DP state is dp[freq`][(r+i)%batchSize] where freq` is freq but with freq[i] decremented by 1. Take the largest of all of the next states and store it in ans. If r == 0, then return ans+1 (because you can form a new partition), otherwise return ans (continuing the current partition)." ]
/** * @param {number} batchSize * @param {number[]} groups * @return {number} */ var maxHappyGroups = function(batchSize, groups) { };
There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut. When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group. You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.   Example 1: Input: batchSize = 3, groups = [1,2,3,4,5,6] Output: 4 Explanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy. Example 2: Input: batchSize = 4, groups = [1,3,2,5,2,2,1,6] Output: 4   Constraints: 1 <= batchSize <= 9 1 <= groups.length <= 30 1 <= groups[i] <= 109
Hard
[ "array", "dynamic-programming", "bit-manipulation", "memoization", "bitmask" ]
[ "const maxHappyGroups = function (batchSize, groups) {\n const arr = new Array(batchSize + 1).fill(0)\n let result = 0\n // reduce group to groups of size group%n\n for (let gSize of groups) {\n arr[gSize % batchSize]++\n }\n\n // Only need 1 step\n result += arr[0]\n arr[0] = 0\n\n // Only need 2 step\n for (let i = 1; i < batchSize / 2; i++) {\n let min = Math.min(arr[i], arr[batchSize - i])\n arr[i] -= min\n arr[batchSize - i] -= min\n result += min\n }\n result += dfs(arr, 0, new Map())\n return result\n}\n\nfunction dfs(arr, remain, cache) {\n let n = arr.length - 1\n const key = arr.join(',')\n if (cache.has(key)) return cache.get(key)\n let result = 0\n // greedy and short cut when we can finish the current round\n if (remain > 0 && arr[n - remain] > 0) {\n arr[n - remain]--\n result = dfs(arr, 0, cache)\n arr[n - remain]++\n } else {\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] > 0) {\n arr[i]--\n result = Math.max(\n result,\n dfs(arr, (remain + i) % n, cache) + (remain == 0 ? 1 : 0)\n )\n arr[i]++\n }\n }\n }\n cache.set(key, result)\n return result\n}" ]
1,816
truncate-sentence
[ "It's easier to solve this problem on an array of strings so parse the string to an array of words", "After return the first k words as a sentence" ]
/** * @param {string} s * @param {number} k * @return {string} */ var truncateSentence = function(s, k) { };
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation). For example, "Hello World", "HELLO", and "hello world hello world" are all sentences. You are given a sentence s​​​​​​ and an integer k​​​​​​. You want to truncate s​​​​​​ such that it contains only the first k​​​​​​ words. Return s​​​​​​ after truncating it.   Example 1: Input: s = "Hello how are you Contestant", k = 4 Output: "Hello how are you" Explanation: The words in s are ["Hello", "how" "are", "you", "Contestant"]. The first 4 words are ["Hello", "how", "are", "you"]. Hence, you should return "Hello how are you". Example 2: Input: s = "What is the solution to this problem", k = 4 Output: "What is the solution" Explanation: The words in s are ["What", "is" "the", "solution", "to", "this", "problem"]. The first 4 words are ["What", "is", "the", "solution"]. Hence, you should return "What is the solution". Example 3: Input: s = "chopper is not a tanuki", k = 5 Output: "chopper is not a tanuki"   Constraints: 1 <= s.length <= 500 k is in the range [1, the number of words in s]. s consist of only lowercase and uppercase English letters and spaces. The words in s are separated by a single space. There are no leading or trailing spaces.
Easy
[ "array", "string" ]
[ "const truncateSentence = function(s, k) {\n const arr = s.split(' ')\n const sli = arr.slice(0, k)\n return sli.join(' ')\n};" ]
1,817
finding-the-users-active-minutes
[ "Try to find the number of different minutes when action happened for each user.", "For each user increase the value of the answer array index which matches the UAM for this user." ]
/** * @param {number[][]} logs * @param {number} k * @return {number[]} */ var findingUsersActiveMinutes = function(logs, k) { };
You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei. Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute. The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] is the number of users whose UAM equals j. Return the array answer as described above.   Example 1: Input: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5 Output: [0,2,0,0,0] Explanation: The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0. Example 2: Input: logs = [[1,1],[2,2],[2,3]], k = 4 Output: [1,1,0,0] Explanation: The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.   Constraints: 1 <= logs.length <= 104 0 <= IDi <= 109 1 <= timei <= 105 k is in the range [The maximum UAM for a user, 105].
Medium
[ "array", "hash-table" ]
[ "const findingUsersActiveMinutes = function(logs, k) {\n const hash = {}, map = {}\n logs.forEach(l => {\n const [id, mi] = l\n if(hash[mi] == null) hash[mi] = new Set()\n if(map[id] == null) map[id] = new Set()\n hash[mi].add(id)\n map[id].add(mi)\n })\n\n const res = Array(k).fill(0)\n Object.keys(map).forEach(k => {\n const num = map[k].size\n res[num - 1]++\n })\n \n return res\n \n};" ]
1,818
minimum-absolute-sum-difference
[ "Go through each element and test the optimal replacements.", "There are only 2 possible replacements for each element (higher and lower) that are optimal." ]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var minAbsoluteSumDiff = function(nums1, nums2) { };
You are given two positive integer arrays nums1 and nums2, both of length n. The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference. Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7. |x| is defined as: x if x >= 0, or -x if x < 0.   Example 1: Input: nums1 = [1,7,5], nums2 = [2,3,5] Output: 3 Explanation: There are two possible optimal solutions: - Replace the second element with the first: [1,7,5] => [1,1,5], or - Replace the second element with the third: [1,7,5] => [1,5,5]. Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3. Example 2: Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10] Output: 0 Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an absolute sum difference of 0. Example 3: Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4] Output: 20 Explanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7]. This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20   Constraints: n == nums1.length n == nums2.length 1 <= n <= 105 1 <= nums1[i], nums2[i] <= 105
Medium
[ "array", "binary-search", "sorting", "ordered-set" ]
[ "const minAbsoluteSumDiff = function (A, B) {\n const mod = 10 ** 9 + 7\n const sA = [...A].sort((a, b) => a - b)\n let res = 0\n let gain = 0\n\n for (let i = 0; i < A.length; i++) {\n const delta = Math.abs(A[i] - B[i])\n res += delta\n // if delta <= gain, delta - newDelta is not possbile to be better than gain\n if (delta <= gain) continue\n // Find closest to B[i] in A\n const idx = binaryS(sA, B[i])\n // Double check l, l + 1, l - 1\n const newDelta = Math.min(\n Math.abs(sA[idx] - B[i]),\n idx >= 1 ? Math.abs(sA[idx - 1] - B[i]) : Infinity,\n idx + 1 < A.length ? Math.abs(sA[idx + 1] - B[i]) : Infinity\n )\n gain = Math.max(gain, delta - newDelta)\n }\n return (res - gain) % mod\n}\nfunction binaryS(A, b) {\n let [l, r] = [0, A.length - 1]\n while (l < r) {\n const mid = l + ((r - l) >> 1)\n const midV = A[mid]\n if (midV === b) return mid\n if (midV < b) l = mid + 1\n else r = mid - 1\n }\n return l\n}" ]
1,819
number-of-different-subsequences-gcds
[ "Think of how to check if a number x is a gcd of a subsequence.", "If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1.", "Adding a number to a subsequence cannot increase its gcd. So, if there is a valid subsequence for x , then the subsequence that contains all multiples of x is a valid one too.", "Iterate on all possiblex from 1 to 10^5, and check if there is a valid subsequence for x." ]
/** * @param {number[]} nums * @return {number} */ var countDifferentSubsequenceGCDs = function(nums) { };
You are given an array nums that consists of positive integers. The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly. For example, the GCD of the sequence [4,6,16] is 2. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10]. Return the number of different GCDs among all non-empty subsequences of nums.   Example 1: Input: nums = [6,10,3] Output: 5 Explanation: The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. Example 2: Input: nums = [5,15,40,5,6] Output: 7   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 2 * 105
Hard
[ "array", "math", "counting", "number-theory" ]
[ "const countDifferentSubsequenceGCDs = function(nums) {\n const MAX = 2e5 + 1;\n const cnt = Array(MAX).fill(0)\n for (let x of nums) cnt[x] = true;\n let ret = 0;\n for (let x=1; x<MAX; x++) {\n let g = 0;\n for (let y=x; y<MAX; y+=x) {\n if (cnt[y]) g = gcd(g, y);\n }\n if (g == x) ret++;\n }\n return ret;\n};\n\nfunction gcd(x,y){\n if(y === 0) return x\n return gcd(y, x % y)\n}" ]
1,822
sign-of-the-product-of-an-array
[ "If there is a 0 in the array the answer is 0", "To avoid overflow make all the negative numbers -1 and all positive numbers 1 and calculate the prod" ]
/** * @param {number[]} nums * @return {number} */ var arraySign = function(nums) { };
There is a function signFunc(x) that returns: 1 if x is positive. -1 if x is negative. 0 if x is equal to 0. You are given an integer array nums. Let product be the product of all values in the array nums. Return signFunc(product).   Example 1: Input: nums = [-1,-2,-3,-4,3,2,1] Output: 1 Explanation: The product of all values in the array is 144, and signFunc(144) = 1 Example 2: Input: nums = [1,5,0,2,-3] Output: 0 Explanation: The product of all values in the array is 0, and signFunc(0) = 0 Example 3: Input: nums = [-1,1,-1,1,-1] Output: -1 Explanation: The product of all values in the array is -1, and signFunc(-1) = -1   Constraints: 1 <= nums.length <= 1000 -100 <= nums[i] <= 100
Easy
[ "array", "math" ]
[ "const arraySign = function(nums) {\n let pos = 0, neg = 0, zero = 0\n for(let e of nums) {\n if(e > 0) pos++\n else if(e < 0) neg++\n else zero++\n }\n if(zero > 0) return 0\n if(neg % 2 === 1) return -1\n else return 1\n};" ]
1,823
find-the-winner-of-the-circular-game
[ "Simulate the process.", "Maintain in a circular list the people who are still in the circle and the current person you are standing at.", "In each turn, count k people and remove the last person from the list." ]
/** * @param {number} n * @param {number} k * @return {number} */ var findTheWinner = function(n, k) { };
There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. The rules of the game are as follows: Start at the 1st friend. Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once. The last friend you counted leaves the circle and loses the game. If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat. Else, the last friend in the circle wins the game. Given the number of friends, n, and an integer k, return the winner of the game.   Example 1: Input: n = 5, k = 2 Output: 3 Explanation: Here are the steps of the game: 1) Start at friend 1. 2) Count 2 friends clockwise, which are friends 1 and 2. 3) Friend 2 leaves the circle. Next start is friend 3. 4) Count 2 friends clockwise, which are friends 3 and 4. 5) Friend 4 leaves the circle. Next start is friend 5. 6) Count 2 friends clockwise, which are friends 5 and 1. 7) Friend 1 leaves the circle. Next start is friend 3. 8) Count 2 friends clockwise, which are friends 3 and 5. 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. Example 2: Input: n = 6, k = 5 Output: 1 Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.   Constraints: 1 <= k <= n <= 500   Follow up: Could you solve this problem in linear time with constant space?
Medium
[ "array", "math", "recursion", "queue", "simulation" ]
[ "const findTheWinner = function(n, k) {\n const arr = Array(n).fill(0)\n for(let i = 0; i < n; i++) arr[i] = i + 1\n let idx = 0\n while(arr.length > 1) {\n idx = (idx + k - 1) % arr.length\n arr.splice(idx, 1)\n }\n return arr.length ? arr[0] : -1\n};" ]
1,824
minimum-sideway-jumps
[ "At a given point, there are only 3 possible states for where the frog can be.", "Check all the ways to move from one point to the next and update the minimum side jumps for each lane." ]
/** * @param {number[]} obstacles * @return {number} */ var minSideJumps = function(obstacles) { };
There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way. You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no obstacles at point i. There will be at most one obstacle in the 3 lanes at each point. For example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2. The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane. For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0. Note: There will be no obstacles on points 0 and n.   Example 1: Input: obstacles = [0,1,2,3,0] Output: 2 Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). Example 2: Input: obstacles = [0,1,1,3,3,0] Output: 0 Explanation: There are no obstacles on lane 2. No side jumps are required. Example 3: Input: obstacles = [0,2,1,0,3,0] Output: 2 Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps.   Constraints: obstacles.length == n + 1 1 <= n <= 5 * 105 0 <= obstacles[i] <= 3 obstacles[0] == obstacles[n] == 0
Medium
[ "array", "dynamic-programming", "greedy" ]
[ "const minSideJumps = function(obstacles) {\n const n = obstacles.length\n const { max, min } = Math\n const dp = [10000000, 1, 0, 1];\n for (let i of obstacles) {\n dp[i] = dp[0];\n for (let j = 1; j <= 3; ++j)\n if (i !== j)\n dp[j] = min(dp[1] + (j != 1 ? 1 : 0), dp[2] + (j != 2 ? 1 : 0), dp[3] + (j != 3 ? 1 : 0));\n }\n return min(dp[1], dp[2], dp[3]);\n};" ]
1,825
finding-mk-average
[ "At each query, try to save and update the sum of the elements needed to calculate MKAverage.", "You can use BSTs for fast insertion and deletion of the elements." ]
/** * @param {number} m * @param {number} k */ var MKAverage = function(m, k) { }; /** * @param {number} num * @return {void} */ MKAverage.prototype.addElement = function(num) { }; /** * @return {number} */ MKAverage.prototype.calculateMKAverage = function() { }; /** * Your MKAverage object will be instantiated and called as such: * var obj = new MKAverage(m, k) * obj.addElement(num) * var param_2 = obj.calculateMKAverage() */
You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream. The MKAverage can be calculated using these steps: If the number of the elements in the stream is less than m you should consider the MKAverage to be -1. Otherwise, copy the last m elements of the stream to a separate container. Remove the smallest k elements and the largest k elements from the container. Calculate the average value for the rest of the elements rounded down to the nearest integer. Implement the MKAverage class: MKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two integers m and k. void addElement(int num) Inserts a new element num into the stream. int calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.   Example 1: Input ["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"] [[3, 1], [3], [1], [], [10], [], [5], [5], [5], []] Output [null, null, null, -1, null, 3, null, null, null, 5] Explanation MKAverage obj = new MKAverage(3, 1); obj.addElement(3); // current elements are [3] obj.addElement(1); // current elements are [3,1] obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist. obj.addElement(10); // current elements are [3,1,10] obj.calculateMKAverage(); // The last 3 elements are [3,1,10]. // After removing smallest and largest 1 element the container will be [3]. // The average of [3] equals 3/1 = 3, return 3 obj.addElement(5); // current elements are [3,1,10,5] obj.addElement(5); // current elements are [3,1,10,5,5] obj.addElement(5); // current elements are [3,1,10,5,5,5] obj.calculateMKAverage(); // The last 3 elements are [5,5,5]. // After removing smallest and largest 1 element the container will be [5]. // The average of [5] equals 5/1 = 5, return 5   Constraints: 3 <= m <= 105 1 <= k*2 < m 1 <= num <= 105 At most 105 calls will be made to addElement and calculateMKAverage.
Hard
[ "design", "queue", "heap-priority-queue", "data-stream", "ordered-set" ]
[ "const MKAverage = function (m, k) {\n this.sum = 0\n this.dataBuff = []\n this.dataM = []\n this.m = m\n this.k = k\n this.count = m - k - k\n}\n\nMKAverage.prototype.addElement = function (num) {\n const total = this.dataBuff.length\n this.dataBuff.push(num)\n if (total >= this.m) {\n let index = binarySearch(\n this.dataBuff,\n this.dataM,\n this.dataBuff[total - this.m]\n )\n this.dataM[index] = this.dataBuff.length - 1\n if (index === 0 || num > this.dataBuff[this.dataM[index - 1]]) {\n move2End(this.dataBuff, this.dataM, index)\n } else if (\n index === this.m - 1 ||\n num < this.dataBuff[this.dataM[index - 1]]\n ) {\n move2Start(this.dataBuff, this.dataM, index)\n }\n\n this.sum = 0\n } else {\n this.dataM.push(this.dataBuff.length - 1)\n move2Start(this.dataBuff, this.dataM, this.dataBuff.length - 1)\n }\n}\n\n\nMKAverage.prototype.calculateMKAverage = function () {\n if (this.dataM.length < this.m) {\n return -1\n } else {\n if (!this.sum) {\n this.sum = calcSum(this.dataBuff, this.dataM, this.k, this.count)\n }\n return Math.floor(this.sum / this.count)\n }\n}\n\n\nfunction binarySearch(numArr, indexArr, tar) {\n let left = 0\n let right = indexArr.length - 1\n\n while (left <= right) {\n let mid = (left + right) >>> 1\n\n if (numArr[indexArr[mid]] > tar) {\n right = mid - 1\n } else if (numArr[indexArr[mid]] < tar) {\n left = mid + 1\n } else {\n return mid\n }\n }\n}\nfunction move2Start(numArr, indexArr, index) {\n let tmp\n\n while (index > 0 && numArr[indexArr[index]] < numArr[indexArr[index - 1]]) {\n tmp = indexArr[index]\n indexArr[index] = indexArr[index - 1]\n indexArr[index - 1] = tmp\n index--\n }\n}\nfunction move2End(numArr, indexArr, index) {\n let tmp\n\n while (\n index < indexArr.length - 1 &&\n numArr[indexArr[index]] > numArr[indexArr[index + 1]]\n ) {\n tmp = indexArr[index]\n indexArr[index] = indexArr[index + 1]\n indexArr[index + 1] = tmp\n index++\n }\n}\n\nfunction calcSum(numArr, indexArr, start, count) {\n let sum = 0\n for (let i = 0; i < count; i++) {\n sum += numArr[indexArr[i + start]]\n }\n return sum\n}" ]
1,827
minimum-operations-to-make-the-array-increasing
[ "nums[i+1] must be at least equal to nums[i] + 1.", "Think greedily. You don't have to increase nums[i+1] beyond nums[i]+1.", "Iterate on i and set nums[i] = max(nums[i-1]+1, nums[i]) ." ]
/** * @param {number[]} nums * @return {number} */ var minOperations = function(nums) { };
You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1. For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3]. Return the minimum number of operations needed to make nums strictly increasing. An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing.   Example 1: Input: nums = [1,1,1] Output: 3 Explanation: You can do the following operations: 1) Increment nums[2], so nums becomes [1,1,2]. 2) Increment nums[1], so nums becomes [1,2,2]. 3) Increment nums[2], so nums becomes [1,2,3]. Example 2: Input: nums = [1,5,2,4,1] Output: 14 Example 3: Input: nums = [8] Output: 0   Constraints: 1 <= nums.length <= 5000 1 <= nums[i] <= 104
Easy
[ "array", "greedy" ]
[ "const minOperations = function(nums) {\n let res = 0\n let pre = nums[0]\n for(let i = 1, n = nums.length; i < n; i++) {\n const e = nums[i]\n if(e <= pre) {\n res += pre - e + 1\n pre++\n } else {\n pre = e\n }\n }\n return res\n};" ]
1,828
queries-on-number-of-points-inside-a-circle
[ "For a point to be inside a circle, the euclidean distance between it and the circle's center needs to be less than or equal to the radius.", "Brute force for each circle and iterate overall points and find those inside it." ]
/** * @param {number[][]} points * @param {number[][]} queries * @return {number[]} */ var countPoints = function(points, queries) { };
You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates. You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj. For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside. Return an array answer, where answer[j] is the answer to the jth query.   Example 1: Input: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]] Output: [3,2,2] Explanation: The points and circles are shown above. queries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle. Example 2: Input: points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]] Output: [2,3,2,4] Explanation: The points and circles are shown above. queries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.   Constraints: 1 <= points.length <= 500 points[i].length == 2 0 <= x​​​​​​i, y​​​​​​i <= 500 1 <= queries.length <= 500 queries[j].length == 3 0 <= xj, yj <= 500 1 <= rj <= 500 All coordinates are integers.   Follow up: Could you find the answer for each query in better complexity than O(n)?
Medium
[ "array", "math", "geometry" ]
[ "var countPoints = function(points, queries) {\n const res = []\n \n for(const [x, y, r] of queries) {\n const square = r ** 2\n const center = [x, y]\n let cnt = 0\n for(const d of points) {\n if(disSquare(d, center) <= square) {\n cnt++\n } \n }\n res.push(cnt)\n }\n \n return res\n \n function disSquare(a, b) {\n return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2\n }\n};" ]