Datasets:

QID
int64
1
2.85k
titleSlug
stringlengths
3
77
Hints
sequence
Code
stringlengths
80
1.34k
Body
stringlengths
190
4.55k
Difficulty
stringclasses
3 values
Topics
sequence
Definitions
stringclasses
14 values
Solutions
sequence
2,470
number-of-subarrays-with-lcm-equal-to-k
[ "The constraints on nums.length are small. It is possible to check every subarray.", "To calculate LCM, you can use a built-in function or the formula lcm(a, b) = a * b / gcd(a, b).", "As you calculate the LCM of more numbers, it can only become greater. Once it becomes greater than k, you know that any larger subarrays containing all the current elements will not work." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var subarrayLCM = function(nums, k) { };
Given an integer array nums and an integer k, return the number of subarrays of nums where the least common multiple of the subarray's elements is k. A subarray is a contiguous non-empty sequence of elements within an array. The least common multiple of an array is the smallest positive integer that is divisible by all the array elements.   Example 1: Input: nums = [3,6,2,7,1], k = 6 Output: 4 Explanation: The subarrays of nums where 6 is the least common multiple of all the subarray's elements are: - [3,6,2,7,1] - [3,6,2,7,1] - [3,6,2,7,1] - [3,6,2,7,1] Example 2: Input: nums = [3], k = 2 Output: 0 Explanation: There are no subarrays of nums where 2 is the least common multiple of all the subarray's elements.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i], k <= 1000
Medium
[ "array", "math", "number-theory" ]
[ "var subarrayLCM = function(nums, k) {\n let res = 0\n const n = nums.length\n \n for(let i = 0; i < n; i++) {\n let tmp = nums[i]\n for(let j = i; j < n; j++) {\n if(k % nums[j] !== 0) break\n if(lcm(tmp, nums[j]) === k) res++\n tmp = Math.max(tmp, nums[j])\n }\n }\n \n return res\n};\n\n\nfunction lcm(a, b) {\n return a * b / gcd(a, b);\n}\n\nfunction gcd(a, b) {\n return b ? gcd(b, a % b) : a\n}" ]
2,471
minimum-number-of-operations-to-sort-a-binary-tree-by-level
[ "We can group the values level by level and solve each group independently.", "Do BFS to group the value level by level.", "Find the minimum number of swaps to sort the array of each level.", "While iterating over the array, check the current element, and if not in the correct index, replace that element with the index of the element which should have come." ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var minimumOperations = function(root) { };
You are given the root of a binary tree with unique values. In one operation, you can choose any two nodes at the same level and swap their values. Return the minimum number of operations needed to make the values at each level sorted in a strictly increasing order. The level of a node is the number of edges along the path between it and the root node.   Example 1: Input: root = [1,4,3,7,6,8,5,null,null,null,null,9,null,10] Output: 3 Explanation: - Swap 4 and 3. The 2nd level becomes [3,4]. - Swap 7 and 5. The 3rd level becomes [5,6,8,7]. - Swap 8 and 7. The 3rd level becomes [5,6,7,8]. We used 3 operations so return 3. It can be proven that 3 is the minimum number of operations needed. Example 2: Input: root = [1,3,2,7,6,5,4] Output: 3 Explanation: - Swap 3 and 2. The 2nd level becomes [2,3]. - Swap 7 and 4. The 3rd level becomes [4,6,5,7]. - Swap 6 and 5. The 3rd level becomes [4,5,6,7]. We used 3 operations so return 3. It can be proven that 3 is the minimum number of operations needed. Example 3: Input: root = [1,2,3,4,5,6] Output: 0 Explanation: Each level is already sorted in increasing order so return 0.   Constraints: The number of nodes in the tree is in the range [1, 105]. 1 <= Node.val <= 105 All the values of the tree are unique.
Medium
[ "tree", "breadth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "var minimumOperations = function (root) {\n let res = 0\n let q = []\n q.push(root)\n\n while (q.length) {\n const nxt = []\n res += minSwaps(\n q.map((e) => e.val),\n q.length\n )\n const len = q.length\n\n for (let i = 0; i < len; i++) {\n const cur = q[i]\n if (cur.left) nxt.push(cur.left)\n if (cur.right) nxt.push(cur.right)\n }\n\n q = nxt\n }\n\n return res\n}\n\nfunction swap(arr, i, j) {\n const temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp\n}\n\n// Return the minimum number\n// of swaps required to sort\n// the array\nfunction minSwaps(arr, len) {\n let ans = 0\n const temp = arr.slice()\n\n // Hashmap which stores the\n // indexes of the input array\n const h = new Map()\n\n temp.sort((a, b) => a - b)\n for (let i = 0; i < len; i++) {\n h.set(arr[i], i)\n }\n for (let i = 0; i < len; i++) {\n // This is checking whether\n // the current element is\n // at the right place or not\n if (arr[i] !== temp[i]) {\n ans++\n const init = arr[i]\n\n // If not, swap this element\n // with the index of the\n // element which should come here\n swap(arr, i, h.get(temp[i]))\n\n // Update the indexes in\n // the hashmap accordingly\n h.set(init, h.get(temp[i]))\n h.set(temp[i], i)\n }\n }\n return ans\n}" ]
2,472
maximum-number-of-non-overlapping-palindrome-substrings
[ "Try to use dynamic programming to solve the problem.", "let dp[i] be the answer for the prefix s[0…i].", "The final answer to the problem will be dp[n-1]. How do you compute this dp?" ]
/** * @param {string} s * @param {number} k * @return {number} */ var maxPalindromes = function(s, k) { };
You are given a string s and a positive integer k. Select a set of non-overlapping substrings from the string s that satisfy the following conditions: The length of each substring is at least k. Each substring is a palindrome. Return the maximum number of substrings in an optimal selection. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "abaccdbbd", k = 3 Output: 2 Explanation: We can select the substrings underlined in s = "abaccdbbd". Both "aba" and "dbbd" are palindromes and have a length of at least k = 3. It can be shown that we cannot find a selection with more than two valid substrings. Example 2: Input: s = "adbcda", k = 2 Output: 0 Explanation: There is no palindrome substring of length at least 2 in the string.   Constraints: 1 <= k <= s.length <= 2000 s consists of lowercase English letters.
Hard
[ "string", "dynamic-programming" ]
[ "const maxPalindromes = function(s, k) {\n const len = s.length;\n // dp[i] 表示s[0 .. i - 1] 中的不重叠回文子字符串的最大数目\n const dp = new Array(len + 1).fill(0);\n // 如果s[i]不在回文字符串内,dp[i+1]=dp[i];\n // 如果s[l..r]是回文字符串且长度不小于k,那么dp[r+1]=max(dp[r+1],dp[l]+1)\n\n // 中心扩展法\n // 回文中心:len个单字符和len-1个双字符\n for (let center = 0; center < 2 * len - 1; center++) {\n let l = center >> 1,\n r = l + (center % 2);\n dp[l + 1] = Math.max(dp[l + 1], dp[l]);\n while (l >= 0 && r < len && s[l] === s[r]) {\n if (r - l + 1 >= k) {\n dp[r + 1] = Math.max(dp[r + 1], dp[l] + 1);\n }\n // expand from center\n l--, r++;\n }\n }\n\n return dp[len];\n};" ]
2,475
number-of-unequal-triplets-in-array
[ "The constraints are very small. Can we try every triplet?", "Yes, we can. Use three loops to iterate through all the possible triplets, ensuring the condition i < j < k holds." ]
/** * @param {number[]} nums * @return {number} */ var unequalTriplets = function(nums) { };
You are given a 0-indexed array of positive integers nums. Find the number of triplets (i, j, k) that meet the following conditions: 0 <= i < j < k < nums.length nums[i], nums[j], and nums[k] are pairwise distinct. In other words, nums[i] != nums[j], nums[i] != nums[k], and nums[j] != nums[k]. Return the number of triplets that meet the conditions.   Example 1: Input: nums = [4,4,2,4,3] Output: 3 Explanation: The following triplets meet the conditions: - (0, 2, 4) because 4 != 2 != 3 - (1, 2, 4) because 4 != 2 != 3 - (2, 3, 4) because 2 != 4 != 3 Since there are 3 triplets, we return 3. Note that (2, 0, 4) is not a valid triplet because 2 > 0. Example 2: Input: nums = [1,1,1,1,1] Output: 0 Explanation: No triplets meet the conditions so we return 0.   Constraints: 3 <= nums.length <= 100 1 <= nums[i] <= 1000
Easy
[ "array", "hash-table" ]
[ "const unequalTriplets = function(nums) {\n let res = 0\n const n = nums.length\n \n for(let i = 0; i < n; i++) {\n for(let j = i + 1; j < n; j++) {\n for(let k = j + 1; k < n; k++) {\n if(nums[i] !== nums[j] && nums[j] !== nums[k] && nums[i] !== nums[k]) res++\n }\n }\n }\n \n return res\n};" ]
2,476
closest-nodes-queries-in-a-binary-search-tree
[ "Try to first convert the tree into a sorted array.", "How do you solve each query in O(log(n)) time using the array of the tree?" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number[]} queries * @return {number[][]} */ var closestNodes = function(root, queries) { };
You are given the root of a binary search tree and an array queries of size n consisting of positive integers. Find a 2D array answer of size n where answer[i] = [mini, maxi]: mini is the largest value in the tree that is smaller than or equal to queries[i]. If a such value does not exist, add -1 instead. maxi is the smallest value in the tree that is greater than or equal to queries[i]. If a such value does not exist, add -1 instead. Return the array answer.   Example 1: Input: root = [6,2,13,1,4,9,15,null,null,null,null,null,null,14], queries = [2,5,16] Output: [[2,2],[4,6],[15,-1]] Explanation: We answer the queries in the following way: - The largest number that is smaller or equal than 2 in the tree is 2, and the smallest number that is greater or equal than 2 is still 2. So the answer for the first query is [2,2]. - The largest number that is smaller or equal than 5 in the tree is 4, and the smallest number that is greater or equal than 5 is 6. So the answer for the second query is [4,6]. - The largest number that is smaller or equal than 16 in the tree is 15, and the smallest number that is greater or equal than 16 does not exist. So the answer for the third query is [15,-1]. Example 2: Input: root = [4,null,9], queries = [3] Output: [[-1,4]] Explanation: The largest number that is smaller or equal to 3 in the tree does not exist, and the smallest number that is greater or equal to 3 is 4. So the answer for the query is [-1,4].   Constraints: The number of nodes in the tree is in the range [2, 105]. 1 <= Node.val <= 106 n == queries.length 1 <= n <= 105 1 <= queries[i] <= 106
Medium
[ "array", "binary-search", "tree", "depth-first-search", "binary-tree" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "var closestNodes = function(root, queries) {\n const arr = []\n function dfs(node) {\n if(node == null) return\n dfs(node.left)\n arr.push(node.val)\n dfs(node.right)\n }\n dfs(root)\n const res = []\n // console.log(arr)\n for(const q of queries) {\n const tmp = []\n tmp[0] = ceil(arr, q)\n tmp[1] = floor(arr, q)\n res.push(tmp)\n }\n \n return res\n // maxIdx that <= target \n function ceil(arr, q) {\n const n = arr.length\n let l = 0, r = n - 1\n while(l < r) {\n const mid = r - (~~((r - l) / 2))\n if(arr[mid] <= q) {\n l = mid\n } else {\n r = mid - 1\n }\n }\n \n return arr[l] <= q ? arr[l] : -1\n }\n // minIdx that >= target\n function floor(arr, q) {\n const n = arr.length\n let l = 0, r = n - 1\n while(l < r) {\n const mid = ~~((r + l) / 2)\n if(arr[mid] < q) {\n l = mid + 1\n } else {\n r = mid\n }\n }\n \n return arr[l] >= q ? arr[l] : -1\n }\n};" ]
2,477
minimum-fuel-cost-to-report-to-the-capital
[ "Can you record the size of each subtree?", "If n people meet on the same node, what is the minimum number of cars needed?" ]
/** * @param {number[][]} roads * @param {number} seats * @return {number} */ var minimumFuelCost = function(roads, seats) { };
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0. You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi. There is a meeting for the representatives of each city. The meeting is in the capital city. There is a car in each city. You are given an integer seats that indicates the number of seats in each car. A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel. Return the minimum number of liters of fuel to reach the capital city.   Example 1: Input: roads = [[0,1],[0,2],[0,3]], seats = 5 Output: 3 Explanation: - Representative1 goes directly to the capital with 1 liter of fuel. - Representative2 goes directly to the capital with 1 liter of fuel. - Representative3 goes directly to the capital with 1 liter of fuel. It costs 3 liters of fuel at minimum. It can be proven that 3 is the minimum number of liters of fuel needed. Example 2: Input: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2 Output: 7 Explanation: - Representative2 goes directly to city 3 with 1 liter of fuel. - Representative2 and representative3 go together to city 1 with 1 liter of fuel. - Representative2 and representative3 go together to the capital with 1 liter of fuel. - Representative1 goes directly to the capital with 1 liter of fuel. - Representative5 goes directly to the capital with 1 liter of fuel. - Representative6 goes directly to city 4 with 1 liter of fuel. - Representative4 and representative6 go together to the capital with 1 liter of fuel. It costs 7 liters of fuel at minimum. It can be proven that 7 is the minimum number of liters of fuel needed. Example 3: Input: roads = [], seats = 1 Output: 0 Explanation: No representatives need to travel to the capital city.   Constraints: 1 <= n <= 105 roads.length == n - 1 roads[i].length == 2 0 <= ai, bi < n ai != bi roads represents a valid tree. 1 <= seats <= 105
Medium
[ "tree", "depth-first-search", "breadth-first-search", "graph" ]
[ "const minimumFuelCost = function(roads, seats) {\n const n = roads.length + 1\n const graph = {}, inDegree = Array(n).fill(0)\n const nodes = Array(n).fill(null).map((e, i) => ([i, 1, 0]))\n for(const [u, v] of roads) {\n if(graph[u] == null) graph[u] = new Set()\n if(graph[v] == null) graph[v] = new Set()\n graph[u].add(nodes[v])\n graph[v].add(nodes[u])\n \n inDegree[u]++\n inDegree[v]++\n }\n const { ceil } = Math\n let q = []\n \n for(let i = 0; i < n; i++) {\n if(inDegree[i] === 1) q.push([i, 1, 0])\n }\n // console.log(q)\n let res = 0\n const visited = new Set()\n \n while(q.length) {\n const nxt = []\n const len = q.length\n for(let i = 0; i < len; i++) {\n const [c, num, sum] = q[i]\n if(c === 0) continue\n for(const node of (graph[c] || [])) {\n const [e] = node\n if(visited.has(e)) continue\n inDegree[e]-- \n // console.log(c, e, sum, num, res)\n if(e === 0) res += ceil(num/ seats) + sum\n else {\n node[1] += num\n node[2] += ceil(num / seats) + sum\n if(inDegree[e] === 1) nxt.push(node)\n }\n // console.log(res)\n }\n visited.add(c)\n }\n\n q = nxt\n // console.log(q, visited)\n }\n \n\n return res\n};" ]
2,478
number-of-beautiful-partitions
[ "Try using a greedy approach where you take as many digits as possible from the left of the string for each partition.", "You can also use a dynamic programming approach, let an array dp where dp[i] is the solution of the problem for the prefix of the string ending at index i, the answer of the problem will be dp[n-1]. What are the transitions of this dp?" ]
/** * @param {string} s * @param {number} k * @param {number} minLength * @return {number} */ var beautifulPartitions = function(s, k, minLength) { };
You are given a string s that consists of the digits '1' to '9' and two integers k and minLength. A partition of s is called beautiful if: s is partitioned into k non-intersecting substrings. Each substring has a length of at least minLength. Each substring starts with a prime digit and ends with a non-prime digit. Prime digits are '2', '3', '5', and '7', and the rest of the digits are non-prime. Return the number of beautiful partitions of s. Since the answer may be very large, return it modulo 109 + 7. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "23542185131", k = 3, minLength = 2 Output: 3 Explanation: There exists three ways to create a beautiful partition: "2354 | 218 | 5131" "2354 | 21851 | 31" "2354218 | 51 | 31" Example 2: Input: s = "23542185131", k = 3, minLength = 3 Output: 1 Explanation: There exists one way to create a beautiful partition: "2354 | 218 | 5131". Example 3: Input: s = "3312958", k = 3, minLength = 1 Output: 1 Explanation: There exists one way to create a beautiful partition: "331 | 29 | 58".   Constraints: 1 <= k, minLength <= s.length <= 1000 s consists of the digits '1' to '9'.
Hard
[ "string", "dynamic-programming" ]
[ "const beautifulPartitions = function (s, k, minLength) {\n const mod = 1e9 + 7\n const p = new Set(['2', '3', '5', '7'])\n\n function isPrime(x) {\n return p.has(x)\n }\n\n let n = s.length\n const dp = Array.from({ length: k + 1 }, () => Array(n).fill(0))\n\n for (let j = 0; j < n; ++j) {\n dp[1][j] = isPrime(s[0]) && !isPrime(s[j])\n }\n let previous_row = Array(n).fill(0)\n for (let i = 0; i + 1 < n; ++i) {\n if (isPrime(s[i + 1])) previous_row[i] = dp[1][i] // update IFF next_index is prime and capable of starting a substring\n if (i - 1 >= 0)\n previous_row[i] = (previous_row[i] + previous_row[i - 1]) % mod\n }\n for (let i = 2; i <= k; ++i) {\n let current_row = Array(n).fill(0)\n for (let end = i * minLength - 1; end < n; ++end) {\n if (isPrime(s[end])) continue\n\n // optimization usage\n let prefixsum = previous_row[end - minLength]\n let start = (i - 1) * minLength - 1\n if (start - 1 >= 0)\n prefixsum = (prefixsum - previous_row[start - 1] + mod) % mod\n dp[i][end] = (dp[i][end] + prefixsum) % mod\n\n // update current_row's column only if the next_index is a prime and capable of starting a substring\n if (end + 1 < n && isPrime(s[end + 1]))\n current_row[end] = (current_row[end] + dp[i][end]) % mod\n }\n // re-calclate prefix sum of current row dp values for each column\n for (let c = 1; c <= n - 1; ++c) {\n current_row[c] = (current_row[c] + current_row[c - 1]) % mod\n }\n\n // swap previous_row dp values and current_row dp values. why ?\n // Because current row will become previous row for next row\n // swap(previous_row, current_row);\n let tmp = current_row\n current_row = previous_row\n previous_row = tmp\n }\n return dp[k][n - 1]\n}" ]
2,481
minimum-cuts-to-divide-a-circle
[ "Think about odd and even values separately.", "When will we not have to cut the circle at all?" ]
/** * @param {number} n * @return {number} */ var numberOfCuts = function(n) { };
A valid cut in a circle can be: A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or A cut that is represented by a straight line that touches one point on the edge of the circle and its center. Some valid and invalid cuts are shown in the figures below. Given the integer n, return the minimum number of cuts needed to divide a circle into n equal slices.   Example 1: Input: n = 4 Output: 2 Explanation: The above figure shows how cutting the circle twice through the middle divides it into 4 equal slices. Example 2: Input: n = 3 Output: 3 Explanation: At least 3 cuts are needed to divide the circle into 3 equal slices. It can be shown that less than 3 cuts cannot result in 3 slices of equal size and shape. Also note that the first cut will not divide the circle into distinct parts.   Constraints: 1 <= n <= 100
Easy
[ "math", "geometry" ]
null
[]
2,482
difference-between-ones-and-zeros-in-row-and-column
[ "You need to reuse information about a row or a column many times. Try storing it to avoid computing it multiple times.", "Use an array to store the number of 1’s in each row and another array to store the number of 1’s in each column. Once you know the number of 1’s in each row or column, you can also easily calculate the number of 0’s." ]
/** * @param {number[][]} grid * @return {number[][]} */ var onesMinusZeros = function(grid) { };
You are given a 0-indexed m x n binary matrix grid. A 0-indexed m x n difference matrix diff is created with the following procedure: Let the number of ones in the ith row be onesRowi. Let the number of ones in the jth column be onesColj. Let the number of zeros in the ith row be zerosRowi. Let the number of zeros in the jth column be zerosColj. diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj Return the difference matrix diff.   Example 1: Input: grid = [[0,1,1],[1,0,1],[0,0,1]] Output: [[0,0,4],[0,0,4],[-2,-2,2]] Explanation: - diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 2 + 1 - 1 - 2 = 0 - diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 2 + 1 - 1 - 2 = 0 - diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 2 + 3 - 1 - 0 = 4 - diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 2 + 1 - 1 - 2 = 0 - diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 2 + 1 - 1 - 2 = 0 - diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 2 + 3 - 1 - 0 = 4 - diff[2][0] = onesRow2 + onesCol0 - zerosRow2 - zerosCol0 = 1 + 1 - 2 - 2 = -2 - diff[2][1] = onesRow2 + onesCol1 - zerosRow2 - zerosCol1 = 1 + 1 - 2 - 2 = -2 - diff[2][2] = onesRow2 + onesCol2 - zerosRow2 - zerosCol2 = 1 + 3 - 2 - 0 = 2 Example 2: Input: grid = [[1,1,1],[1,1,1]] Output: [[5,5,5],[5,5,5]] Explanation: - diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 3 + 2 - 0 - 0 = 5 - diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 3 + 2 - 0 - 0 = 5 - diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 3 + 2 - 0 - 0 = 5 - diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 3 + 2 - 0 - 0 = 5 - diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 3 + 2 - 0 - 0 = 5 - diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 3 + 2 - 0 - 0 = 5   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 105 1 <= m * n <= 105 grid[i][j] is either 0 or 1.
Medium
[ "array", "matrix", "simulation" ]
null
[]
2,483
minimum-penalty-for-a-shop
[ "At any index, the penalty is the sum of prefix count of ‘N’ and suffix count of ‘Y’.", "Enumerate all indices and find the minimum such value." ]
/** * @param {string} customers * @return {number} */ var bestClosingTime = function(customers) { };
You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y': if the ith character is 'Y', it means that customers come at the ith hour whereas 'N' indicates that no customers come at the ith hour. If the shop closes at the jth hour (0 <= j <= n), the penalty is calculated as follows: For every hour when the shop is open and no customers come, the penalty increases by 1. For every hour when the shop is closed and customers come, the penalty increases by 1. Return the earliest hour at which the shop must be closed to incur a minimum penalty. Note that if a shop closes at the jth hour, it means the shop is closed at the hour j.   Example 1: Input: customers = "YYNY" Output: 2 Explanation: - Closing the shop at the 0th hour incurs in 1+1+0+1 = 3 penalty. - Closing the shop at the 1st hour incurs in 0+1+0+1 = 2 penalty. - Closing the shop at the 2nd hour incurs in 0+0+0+1 = 1 penalty. - Closing the shop at the 3rd hour incurs in 0+0+1+1 = 2 penalty. - Closing the shop at the 4th hour incurs in 0+0+1+0 = 1 penalty. Closing the shop at 2nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2. Example 2: Input: customers = "NNNNN" Output: 0 Explanation: It is best to close the shop at the 0th hour as no customers arrive. Example 3: Input: customers = "YYYY" Output: 4 Explanation: It is best to close the shop at the 4th hour as customers arrive at each hour.   Constraints: 1 <= customers.length <= 105 customers consists only of characters 'Y' and 'N'.
Medium
[ "string", "prefix-sum" ]
null
[]
2,484
count-palindromic-subsequences
[ "There are 100 possibilities for the first two characters of the palindrome.", "Iterate over all characters, letting the current character be the center of the palindrome." ]
/** * @param {string} s * @return {number} */ var countPalindromes = function(s) { };
Given a string of digits s, return the number of palindromic subsequences of s having length 5. Since the answer may be very large, return it modulo 109 + 7. Note: A string is palindromic if it reads the same forward and backward. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.   Example 1: Input: s = "103301" Output: 2 Explanation: There are 6 possible subsequences of length 5: "10330","10331","10301","10301","13301","03301". Two of them (both equal to "10301") are palindromic. Example 2: Input: s = "0000000" Output: 21 Explanation: All 21 subsequences are "00000", which is palindromic. Example 3: Input: s = "9999900000" Output: 2 Explanation: The only two palindromic subsequences are "99999" and "00000".   Constraints: 1 <= s.length <= 104 s consists of digits.
Hard
[ "string", "dynamic-programming" ]
[ "const initialize2DArray = (n, m) => {\n let d = []\n for (let i = 0; i < n; i++) {\n let t = Array(m).fill(0)\n d.push(t)\n }\n return d\n}\n\nconst mod = 1e9 + 7\n\nconst countPalindromes = (s) => {\n let res = 0,\n n = s.length,\n cnt = Array(10).fill(0)\n for (let i = 0; i < n; i++) {\n let tot = 0\n for (let j = n - 1; j > i; j--) {\n if (s[i] == s[j]) {\n res += tot * (j - i - 1)\n res %= mod\n }\n tot += cnt[s[j] - \"0\"]\n }\n cnt[s[i] - \"0\"]++\n }\n return res\n}" ]
2,485
find-the-pivot-integer
[ "Can you use brute force to check every number from 1 to n if any of them is the pivot integer?", "If you know the sum of [1: pivot], how can you efficiently calculate the sum of the other parts?" ]
/** * @param {number} n * @return {number} */ var pivotInteger = function(n) { };
Given a positive integer n, find the pivot integer x such that: The sum of all elements between 1 and x inclusively equals the sum of all elements between x and n inclusively. Return the pivot integer x. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input.   Example 1: Input: n = 8 Output: 6 Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21. Example 2: Input: n = 1 Output: 1 Explanation: 1 is the pivot integer since: 1 = 1. Example 3: Input: n = 4 Output: -1 Explanation: It can be proved that no such integer exist.   Constraints: 1 <= n <= 1000
Easy
[ "math", "prefix-sum" ]
[ "var pivotInteger = function(n) {\n const sum = (1 + n) * n / 2\n let tmp = 0\n for(let i = 1; i <= n; i++) {\n tmp += i\n if(tmp === sum - tmp + i) return i\n }\n \n return -1\n};" ]
2,486
append-characters-to-string-to-make-subsequence
[ "Find the longest prefix of t that is a subsequence of s.", "Use two variables to keep track of your location in s and t. If the characters match, increment both variables. Otherwise, only increment the variable for s.", "The remaining characters in t must be appended to the end of s." ]
/** * @param {string} s * @param {string} t * @return {number} */ var appendCharacters = function(s, t) { };
You are given two strings s and t consisting of only lowercase English letters. Return the minimum number of characters that need to be appended to the end of s so that t becomes a subsequence of s. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.   Example 1: Input: s = "coaching", t = "coding" Output: 4 Explanation: Append the characters "ding" to the end of s so that s = "coachingding". Now, t is a subsequence of s ("coachingding"). It can be shown that appending any 3 characters to the end of s will never make t a subsequence. Example 2: Input: s = "abcde", t = "a" Output: 0 Explanation: t is already a subsequence of s ("abcde"). Example 3: Input: s = "z", t = "abcde" Output: 5 Explanation: Append the characters "abcde" to the end of s so that s = "zabcde". Now, t is a subsequence of s ("zabcde"). It can be shown that appending any 4 characters to the end of s will never make t a subsequence.   Constraints: 1 <= s.length, t.length <= 105 s and t consist only of lowercase English letters.
Medium
[ "two-pointers", "string", "greedy" ]
[ "var appendCharacters = function(s, t) {\n let i = 0, j = 0\n const m = s.length, n = t.length\n while(i < m && j < n) {\n if(s[i] === t[j]) {\n i++\n j++\n } else {\n i++\n }\n }\n \n return n - 1 - (j - 1)\n};" ]
2,487
remove-nodes-from-linked-list
[ "Iterate on nodes in reversed order.", "When iterating in reversed order, save the maximum value that was passed before." ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {ListNode} */ var removeNodes = function(head) { };
You are given the head of a linked list. Remove every node which has a node with a strictly greater value anywhere to the right side of it. Return the head of the modified linked list.   Example 1: Input: head = [5,2,13,3,8] Output: [13,8] Explanation: The nodes that should be removed are 5, 2 and 3. - Node 13 is to the right of node 5. - Node 13 is to the right of node 2. - Node 8 is to the right of node 3. Example 2: Input: head = [1,1,1,1] Output: [1,1,1,1] Explanation: Every node has value 1, so no nodes are removed.   Constraints: The number of the nodes in the given list is in the range [1, 105]. 1 <= Node.val <= 105
Medium
[ "linked-list", "stack", "recursion", "monotonic-stack" ]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
[ "const removeNodes = function(head) {\n const arr = []\n let cur = head\n while(cur) {\n arr.push(cur)\n cur = cur.next\n }\n \n const stk = []\n for(const e of arr) {\n while(stk.length && e.val > stk[stk.length - 1].val) {\n stk.pop()\n }\n stk.push(e)\n }\n \n for(let i = 0; i < stk.length - 1; i++) {\n const cur = stk[i]\n cur.next = stk[i + 1]\n }\n \n return stk[0]\n};" ]
2,488
count-subarrays-with-median-k
[ "Consider changing the numbers that are strictly greater than k in the array to 1, the numbers that are strictly smaller than k to -1, and k to 0.", "After the change, what property does a subarray with median k have in the new array?", "An array with median k should have a sum equal to either 0 or 1 in the new array and should contain the element k. How do you count such subarrays?" ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var countSubarrays = function(nums, k) { };
You are given an array nums of size n consisting of distinct integers from 1 to n and a positive integer k. Return the number of non-empty subarrays in nums that have a median equal to k. Note: The median of an array is the middle element after sorting the array in ascending order. If the array is of even length, the median is the left middle element. For example, the median of [2,3,1,4] is 2, and the median of [8,4,3,5,1] is 4. A subarray is a contiguous part of an array.   Example 1: Input: nums = [3,2,1,4,5], k = 4 Output: 3 Explanation: The subarrays that have a median equal to 4 are: [4], [4,5] and [1,4,5]. Example 2: Input: nums = [2,3,1], k = 3 Output: 1 Explanation: [3] is the only subarray that has a median equal to 3.   Constraints: n == nums.length 1 <= n <= 105 1 <= nums[i], k <= n The integers in nums are distinct.
Hard
[ "array", "hash-table", "prefix-sum" ]
[ "const countSubarrays = (a, k) => permutationArrayWithMedianK(a, k);\n\nconst permutationArrayWithMedianK = (a, k) => {\n const m = new Map([[0, 1]])\n let find = false, balance = 0, res = 0;\n for (const x of a) {\n if (x < k) {\n balance--;\n } else if (x > k) {\n balance++;\n } else {\n find = true;\n }\n if (find) {\n // balance - 1, subarray length is even, has one more right\n res += (m.get(balance) || 0) + (m.get(balance - 1) || 0);\n } else {\n m.set(balance, (m.get(balance) || 0) + 1);\n }\n }\n return res;\n};" ]
2,490
circular-sentence
[ "Check the character before the empty space and the character after the empty space.", "Check the first character and the last character of the sentence." ]
/** * @param {string} sentence * @return {boolean} */ var isCircularSentence = function(sentence) { };
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. Uppercase and lowercase English letters are considered different. A sentence is circular if: The last character of a word is equal to the first character of the next word. The last character of the last word is equal to the first character of the first word. For example, "leetcode exercises sound delightful", "eetcode", "leetcode eats soul" are all circular sentences. However, "Leetcode is cool", "happy Leetcode", "Leetcode" and "I like Leetcode" are not circular sentences. Given a string sentence, return true if it is circular. Otherwise, return false.   Example 1: Input: sentence = "leetcode exercises sound delightful" Output: true Explanation: The words in sentence are ["leetcode", "exercises", "sound", "delightful"]. - leetcode's last character is equal to exercises's first character. - exercises's last character is equal to sound's first character. - sound's last character is equal to delightful's first character. - delightful's last character is equal to leetcode's first character. The sentence is circular. Example 2: Input: sentence = "eetcode" Output: true Explanation: The words in sentence are ["eetcode"]. - eetcode's last character is equal to eetcode's first character. The sentence is circular. Example 3: Input: sentence = "Leetcode is cool" Output: false Explanation: The words in sentence are ["Leetcode", "is", "cool"]. - Leetcode's last character is not equal to is's first character. The sentence is not circular.   Constraints: 1 <= sentence.length <= 500 sentence consist of only lowercase and uppercase English letters and spaces. The words in sentence are separated by a single space. There are no leading or trailing spaces.
Easy
[ "string" ]
[ "var isCircularSentence = function(sentence) {\n const arr = sentence.split(' ')\n const n = arr.length\n for(let i = 0; i < n; i++) {\n if(i === n - 1) {\n if(arr[i][arr[i].length - 1] !== arr[0][0]) return false\n } else {\n if(arr[i][arr[i].length - 1] !== arr[i + 1][0]) return false\n }\n }\n return true\n};" ]
2,491
divide-players-into-teams-of-equal-skill
[ "Try sorting the skill array.", "It is always optimal to pair the weakest available player with the strongest available player." ]
/** * @param {number[]} skill * @return {number} */ var dividePlayers = function(skill) { };
You are given a positive integer array skill of even length n where skill[i] denotes the skill of the ith player. Divide the players into n / 2 teams of size 2 such that the total skill of each team is equal. The chemistry of a team is equal to the product of the skills of the players on that team. Return the sum of the chemistry of all the teams, or return -1 if there is no way to divide the players into teams such that the total skill of each team is equal.   Example 1: Input: skill = [3,2,5,1,3,4] Output: 22 Explanation: Divide the players into the following teams: (1, 5), (2, 4), (3, 3), where each team has a total skill of 6. The sum of the chemistry of all the teams is: 1 * 5 + 2 * 4 + 3 * 3 = 5 + 8 + 9 = 22. Example 2: Input: skill = [3,4] Output: 12 Explanation: The two players form a team with a total skill of 7. The chemistry of the team is 3 * 4 = 12. Example 3: Input: skill = [1,1,2,3] Output: -1 Explanation: There is no way to divide the players into teams such that the total skill of each team is equal.   Constraints: 2 <= skill.length <= 105 skill.length is even. 1 <= skill[i] <= 1000
Medium
[ "array", "hash-table", "two-pointers", "sorting" ]
[ "const dividePlayers = function(skill) {\n skill.sort((a, b) => a - b)\n const n = skill.length\n const sum = skill[0] + skill[skill.length - 1]\n for(let i = 1; i < n / 2; i++) {\n const j = n - 1 - i\n if(skill[i] + skill[j] !== sum) return -1\n }\n let res = skill[0] * skill[skill.length - 1]\n for(let i = 1; i < n / 2; i++) {\n const j = n - 1 - i\n res += skill[i] * skill[j]\n }\n \n return res\n};" ]
2,492
minimum-score-of-a-path-between-two-cities
[ "Can you solve the problem if the whole graph is connected?", "Notice that if the graph is connected, you can always use any edge of the graph in your path.", "How to solve the general problem in a similar way? Remove all the nodes that are not connected to 1 and n, then apply the previous solution in the new graph." ]
/** * @param {number} n * @param {number[][]} roads * @return {number} */ var minScore = function(n, roads) { };
You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [ai, bi, distancei] indicates that there is a bidirectional road between cities ai and bi with a distance equal to distancei. The cities graph is not necessarily connected. The score of a path between two cities is defined as the minimum distance of a road in this path. Return the minimum possible score of a path between cities 1 and n. Note: A path is a sequence of roads between two cities. It is allowed for a path to contain the same road multiple times, and you can visit cities 1 and n multiple times along the path. The test cases are generated such that there is at least one path between 1 and n.   Example 1: Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]] Output: 5 Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5. It can be shown that no other path has less score. Example 2: Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]] Output: 2 Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2.   Constraints: 2 <= n <= 105 1 <= roads.length <= 105 roads[i].length == 3 1 <= ai, bi <= n ai != bi 1 <= distancei <= 104 There are no repeated edges. There is at least one path between 1 and n.
Medium
[ "depth-first-search", "breadth-first-search", "union-find", "graph" ]
[ "const minScore = function(n, roads) {\n const g = {}, visited = Array(n + 1).fill(0)\n let res = Infinity\n for(const [u, v, d] of roads) {\n if(g[u] == null) g[u] = []\n if(g[v] == null) g[v] = []\n \n g[u].push([v, d])\n g[v].push([u, d])\n }\n \n dfs(1)\n \n return res\n \n function dfs(node) {\n visited[node] = 1\n for(const [nxt, dis] of (g[node] || [])) {\n res = Math.min(res, dis)\n if(visited[nxt] === 0) {\n dfs(nxt)\n }\n }\n }\n};", "class UnionFind {\n constructor() {\n this.sizes = new Map()\n this.parents = new Map()\n }\n\n find(x){\n if (x !== (this.parents.get(x) ?? x)) {\n this.parents.set(x, this.find(this.parents.get(x) ?? x));\n }\n return this.parents.get(x) ?? x;\n }\n size(x) {\n return (this.sizes.get(this.find(x)) ?? 1);\n }\n connected(p, q) {\n return this.find(p) == this.find(q);\n }\n union(a, b) {\n const fa = this.find(a);\n const fb = this.find(b);\n if (fa == fb) {\n return;\n }\n const sa = this.sizes.get(fa) ?? 1;\n const sb = this.sizes.get(fb) ?? 1;\n\n if (sa < sb) {\n this.parents.set(fa, fb);\n this.sizes.set(fb, sb + sa);\n } else {\n this.parents.set(fb, fa);\n this.sizes.set(fa, sb + sa);\n }\n }\n}\n\nvar minScore = function(n, roads) {\n const uf = new UnionFind();\n\n for (const [a, b] of roads) {\n uf.union(a, b);\n }\n let ans = Infinity;\n\n for (const [i, j, d] of roads) {\n if (uf.connected(1, i) && uf.connected(1, j)) {\n ans = Math.min(ans, d);\n }\n }\n return ans;\n};" ]
2,493
divide-nodes-into-the-maximum-number-of-groups
[ "If the graph is not bipartite, it is not possible to group the nodes.", "Notice that we can solve the problem for each connected component independently, and the final answer will be just the sum of the maximum number of groups in each component.", "Finally, to solve the problem for each connected component, we can notice that if for some node v we fix its position to be in the leftmost group, then we can also evaluate the position of every other node. That position is the depth of the node in a bfs tree after rooting at node v." ]
/** * @param {number} n * @param {number[][]} edges * @return {number} */ var magnificentSets = function(n, edges) { };
You are given a positive integer n representing the number of nodes in an undirected graph. The nodes are labeled from 1 to n. You are also given a 2D integer array edges, where edges[i] = [ai, bi] indicates that there is a bidirectional edge between nodes ai and bi. Notice that the given graph may be disconnected. Divide the nodes of the graph into m groups (1-indexed) such that: Each node in the graph belongs to exactly one group. For every pair of nodes in the graph that are connected by an edge [ai, bi], if ai belongs to the group with index x, and bi belongs to the group with index y, then |y - x| = 1. Return the maximum number of groups (i.e., maximum m) into which you can divide the nodes. Return -1 if it is impossible to group the nodes with the given conditions.   Example 1: Input: n = 6, edges = [[1,2],[1,4],[1,5],[2,6],[2,3],[4,6]] Output: 4 Explanation: As shown in the image we: - Add node 5 to the first group. - Add node 1 to the second group. - Add nodes 2 and 4 to the third group. - Add nodes 3 and 6 to the fourth group. We can see that every edge is satisfied. It can be shown that that if we create a fifth group and move any node from the third or fourth group to it, at least on of the edges will not be satisfied. Example 2: Input: n = 3, edges = [[1,2],[2,3],[3,1]] Output: -1 Explanation: If we add node 1 to the first group, node 2 to the second group, and node 3 to the third group to satisfy the first two edges, we can see that the third edge will not be satisfied. It can be shown that no grouping is possible.   Constraints: 1 <= n <= 500 1 <= edges.length <= 104 edges[i].length == 2 1 <= ai, bi <= n ai != bi There is at most one edge between any pair of vertices.
Hard
[ "breadth-first-search", "union-find", "graph" ]
[ "const magnificentSets = function (n, edges) {\n function getComponents(n) {\n let visited = Array(n + 1).fill(false);\n let ans = [];\n for (let i = 1; i <= n; i++) {\n if (!visited[i]) {\n ans.push(visit(i, [], visited));\n }\n }\n return ans;\n }\n\n function visit(cur, nodes, visited) {\n visited[cur] = true;\n nodes.push(cur);\n for (let next of map.get(cur)) {\n // skip if you have already visited this node\n if (visited[next]) continue;\n visit(next, nodes, visited);\n }\n return nodes;\n }\n\n function find(node, n) {\n let group = Array(n + 1).fill(-1);\n\n let queue = [];\n queue.push(node);\n let groups = 0;\n while (queue.length > 0) {\n let k = queue.length;\n // store nodes in set to avoid duplicates\n let set = new Set();\n while (k-- > 0) {\n let cur = queue.shift();\n // this case occurs when 2 nodes in the same level are connected\n // so, return -1\n if (group[cur] != -1) return -1;\n group[cur] = groups;\n for (let next of map.get(cur)) {\n if (group[next] == -1) {\n set.add(next);\n }\n }\n }\n for (let val of set) queue.push(val);\n groups++;\n }\n return groups;\n }\n\n let map = new Map(); // Integer -> List<Integer>\n for (let i = 1; i <= n; i++) {\n map.set(i, []);\n }\n // adjacency list\n for (let edge of edges) {\n let u = edge[0],\n v = edge[1];\n map.get(u).push(v);\n map.get(v).push(u);\n }\n\n // get all components as Graph can be disconnected\n let components = getComponents(n);\n\n let ans = 0;\n \n for (let component of components) {\n let groups = -1;\n for (let node of component) {\n groups = Math.max(groups, find(node, n));\n }\n if (groups == -1) return -1;\n ans += groups;\n }\n\n return ans;\n};", "/////////////////////// Template ////////////////////////////////////////\nconst initializeGraph = (n) => { let g = []; for (let i = 0; i < n; i++) { g.push([]); } return g; };\nconst packUG = (g, edges) => { for (const [u, v] of edges) { g[u].push(v); g[v].push(u); } };\nconst initialize2DArray = (n, m) => { let d = []; for (let i = 0; i < n; i++) { let t = Array(m).fill(Number.MAX_SAFE_INTEGER); d.push(t); } return d; };\n\nfunction DJSet(n) {\n // parent[i] < 0, -parent[i] is the group size which root is i. example: (i -> parent[i] -> parent[parent[i]] -> parent[parent[parent[i]]] ...)\n // parent[i] >= 0, i is not the root and parent[i] is i's parent. example: (... parent[parent[parent[i]]] -> parent[parent[i]] -> parent[i] -> i)\n let parent = Array(n).fill(-1);\n return { find, union, count, equiv, par }\n function find(x) {\n return parent[x] < 0 ? x : parent[x] = find(parent[x]);\n }\n function union(x, y) {\n x = find(x);\n y = find(y);\n if (x != y) {\n if (parent[x] < parent[y]) [x, y] = [y, x];\n parent[x] += parent[y];\n parent[y] = x;\n }\n return x == y;\n }\n function count() { // total groups\n return parent.filter(v => v < 0).length;\n }\n function equiv(x, y) { // isConnected\n return find(x) == find(y);\n }\n function par() {\n return parent;\n }\n}\n\nconst isBipartite = (g) => {\n let n = g.length, start = 1, visit = Array(n).fill(false), q = [], color = Array(n).fill(0); // 0: no color, 1: red -1: blue\n for (let i = start; i < n; i++) {\n if (color[i] != 0) continue;\n q.push(i);\n color[i] = 1;\n if (visit[i]) continue;\n while (q.length) {\n let cur = q.shift();\n if (visit[cur]) continue;\n for (const child of g[cur]) {\n if (color[child] == color[cur]) return false;\n if (color[child]) continue;\n color[child] = -color[cur];\n q.push(child);\n }\n }\n }\n return true;\n};\n////////////////////////////////////////////////////////////////////\n\nconst magnificentSets = (n, edges) => {\n let g = initializeGraph(n + 1), ds = new DJSet(n + 1);\n packUG(g, edges);\n if (!isBipartite(g)) return -1;\n let d = initialize2DArray(n + 1, n + 1), res = Array(n + 1).fill(0);\n for (let i = 1; i <= n; i++) d[i][i] = 0;\n for (const [u, v] of edges) {\n d[u][v] = 1;\n d[v][u] = 1;\n ds.union(u, v);\n }\n wf(d);\n for (let i = 1; i <= n; i++) {\n let max = 0;\n for (let j = 1; j <= n; j++) {\n if (d[i][j] >= Number.MAX_SAFE_INTEGER) continue;\n max = Math.max(max, d[i][j]);\n }\n let par = ds.find(i);\n res[par] = Math.max(res[par], max + 1);\n }\n let ans = 0;\n for (let i = 1; i <= n; i++) ans += res[i];\n return ans;\n};\n\nconst wf = (g) => {\n let n = g.length;\n for (let k = 0; k < n; k++) {\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n if (g[i][j] > g[i][k] + g[k][j]) {\n g[i][j] = g[i][k] + g[k][j];\n }\n }\n }\n }\n};" ]
2,496
maximum-value-of-a-string-in-an-array
[ "For strings comprising only of digits, convert them into integers.", "For all other strings, calculate their length." ]
/** * @param {string[]} strs * @return {number} */ var maximumValue = function(strs) { };
The value of an alphanumeric string can be defined as: The numeric representation of the string in base 10, if it comprises of digits only. The length of the string, otherwise. Given an array strs of alphanumeric strings, return the maximum value of any string in strs.   Example 1: Input: strs = ["alic3","bob","3","4","00000"] Output: 5 Explanation: - "alic3" consists of both letters and digits, so its value is its length, i.e. 5. - "bob" consists only of letters, so its value is also its length, i.e. 3. - "3" consists only of digits, so its value is its numeric equivalent, i.e. 3. - "4" also consists only of digits, so its value is 4. - "00000" consists only of digits, so its value is 0. Hence, the maximum value is 5, of "alic3". Example 2: Input: strs = ["1","01","001","0001"] Output: 1 Explanation: Each string in the array has value 1. Hence, we return 1.   Constraints: 1 <= strs.length <= 100 1 <= strs[i].length <= 9 strs[i] consists of only lowercase English letters and digits.
Easy
[ "array", "string" ]
null
[]
2,497
maximum-star-sum-of-a-graph
[ "A star graph doesn’t necessarily include all of its neighbors.", "For each node, sort its neighbors in descending order and take k max valued neighbors." ]
/** * @param {number[]} vals * @param {number[][]} edges * @param {number} k * @return {number} */ var maxStarSum = function(vals, edges, k) { };
There is an undirected graph consisting of n nodes numbered from 0 to n - 1. You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. A star graph is a subgraph of the given graph having a center node containing 0 or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges. The image below shows star graphs with 3 and 4 neighbors respectively, centered at the blue node. The star sum is the sum of the values of all the nodes present in the star graph. Given an integer k, return the maximum star sum of a star graph containing at most k edges.   Example 1: Input: vals = [1,2,3,4,10,-10,-20], edges = [[0,1],[1,2],[1,3],[3,4],[3,5],[3,6]], k = 2 Output: 16 Explanation: The above diagram represents the input graph. The star graph with the maximum star sum is denoted by blue. It is centered at 3 and includes its neighbors 1 and 4. It can be shown it is not possible to get a star graph with a sum greater than 16. Example 2: Input: vals = [-5], edges = [], k = 0 Output: -5 Explanation: There is only one possible star graph, which is node 0 itself. Hence, we return -5.   Constraints: n == vals.length 1 <= n <= 105 -104 <= vals[i] <= 104 0 <= edges.length <= min(n * (n - 1) / 2, 105) edges[i].length == 2 0 <= ai, bi <= n - 1 ai != bi 0 <= k <= n - 1
Medium
[ "array", "greedy", "graph", "sorting", "heap-priority-queue" ]
null
[]
2,498
frog-jump-ii
[ "One of the optimal strategies will be to jump to every stone.", "Skipping just one stone in every forward jump and jumping to those skipped stones in backward jump can minimize the maximum jump." ]
/** * @param {number[]} stones * @return {number} */ var maxJump = function(stones) { };
You are given a 0-indexed integer array stones sorted in strictly increasing order representing the positions of stones in a river. A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone at most once. The length of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps. More formally, if the frog is at stones[i] and is jumping to stones[j], the length of the jump is |stones[i] - stones[j]|. The cost of a path is the maximum length of a jump among all jumps in the path. Return the minimum cost of a path for the frog.   Example 1: Input: stones = [0,2,5,6,7] Output: 5 Explanation: The above figure represents one of the optimal paths the frog can take. The cost of this path is 5, which is the maximum length of a jump. Since it is not possible to achieve a cost of less than 5, we return it. Example 2: Input: stones = [0,3,9] Output: 9 Explanation: The frog can jump directly to the last stone and come back to the first stone. In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9. It can be shown that this is the minimum achievable cost.   Constraints: 2 <= stones.length <= 105 0 <= stones[i] <= 109 stones[0] == 0 stones is sorted in a strictly increasing order.
Medium
[ "array", "binary-search", "greedy" ]
null
[]
2,499
minimum-total-cost-to-make-arrays-unequal
[ "How can we check which indices of <code>nums1</code> will be considered for swapping? How to minimize the number of such operations?", "It can be seen that greedily swapping values of indices where <code>nums1[i] == nums2[i]</code> is the most optimal choice. How many values cannot be swapped this way?", "Find which indices we will swap these remaining values with, and if there are enough such indices." ]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var minimumTotalCost = function(nums1, nums2) { };
You are given two 0-indexed integer arrays nums1 and nums2, of equal length n. In one operation, you can swap the values of any two indices of nums1. The cost of this operation is the sum of the indices. Find the minimum total cost of performing the given operation any number of times such that nums1[i] != nums2[i] for all 0 <= i <= n - 1 after performing all the operations. Return the minimum total cost such that nums1 and nums2 satisfy the above condition. In case it is not possible, return -1.   Example 1: Input: nums1 = [1,2,3,4,5], nums2 = [1,2,3,4,5] Output: 10 Explanation: One of the ways we can perform the operations is: - Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = [4,2,3,1,5] - Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = [4,3,2,1,5]. - Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =[5,3,2,1,4]. We can see that for each index i, nums1[i] != nums2[i]. The cost required here is 10. Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10. Example 2: Input: nums1 = [2,2,2,1,3], nums2 = [1,2,2,3,3] Output: 10 Explanation: One of the ways we can perform the operations is: - Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = [2,2,1,2,3]. - Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = [2,3,1,2,2]. The total cost needed here is 10, which is the minimum possible. Example 3: Input: nums1 = [1,2,2], nums2 = [1,2,2] Output: -1 Explanation: It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform. Hence, we return -1.   Constraints: n == nums1.length == nums2.length 1 <= n <= 105 1 <= nums1[i], nums2[i] <= n
Hard
[ "array", "hash-table", "greedy", "counting" ]
null
[]
2,500
delete-greatest-value-in-each-row
[ "Iterate from the first to the last row and if there exist some unmarked cells, take a maximum from them and mark that cell as visited.", "Add a maximum of newly marked cells to answer and repeat that operation until the whole matrix becomes marked." ]
/** * @param {number[][]} grid * @return {number} */ var deleteGreatestValue = function(grid) { };
You are given an m x n matrix grid consisting of positive integers. Perform the following operation until grid becomes empty: Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them. Add the maximum of deleted elements to the answer. Note that the number of columns decreases by one after each operation. Return the answer after performing the operations described above.   Example 1: Input: grid = [[1,2,4],[3,3,1]] Output: 8 Explanation: The diagram above shows the removed values in each step. - In the first operation, we remove 4 from the first row and 3 from the second row (notice that, there are two cells with value 3 and we can remove any of them). We add 4 to the answer. - In the second operation, we remove 2 from the first row and 3 from the second row. We add 3 to the answer. - In the third operation, we remove 1 from the first row and 1 from the second row. We add 1 to the answer. The final answer = 4 + 3 + 1 = 8. Example 2: Input: grid = [[10]] Output: 10 Explanation: The diagram above shows the removed values in each step. - In the first operation, we remove 10 from the first row. We add 10 to the answer. The final answer = 10.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 50 1 <= grid[i][j] <= 100
Easy
[ "array", "sorting", "heap-priority-queue", "matrix", "simulation" ]
null
[]
2,501
longest-square-streak-in-an-array
[ "With the constraints, the length of the longest square streak possible is 5.", "Store the elements of nums in a set to quickly check if it exists.", "Store the elements of nums in a set to quickly check if it exists." ]
/** * @param {number[]} nums * @return {number} */ var longestSquareStreak = function(nums) { };
You are given an integer array nums. A subsequence of nums is called a square streak if: The length of the subsequence is at least 2, and after sorting the subsequence, each element (except the first element) is the square of the previous number. Return the length of the longest square streak in nums, or return -1 if there is no square streak. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.   Example 1: Input: nums = [4,3,6,16,8,2] Output: 3 Explanation: Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16]. - 4 = 2 * 2. - 16 = 4 * 4. Therefore, [4,16,2] is a square streak. It can be shown that every subsequence of length 4 is not a square streak. Example 2: Input: nums = [2,3,5,6,7] Output: -1 Explanation: There is no square streak in nums so return -1.   Constraints: 2 <= nums.length <= 105 2 <= nums[i] <= 105
Medium
[ "array", "hash-table", "binary-search", "dynamic-programming", "sorting" ]
null
[]
2,502
design-memory-allocator
[ "Can you simulate the process?", "Use brute force to find the leftmost free block and free each occupied memory unit" ]
/** * @param {number} n */ var Allocator = function(n) { }; /** * @param {number} size * @param {number} mID * @return {number} */ Allocator.prototype.allocate = function(size, mID) { }; /** * @param {number} mID * @return {number} */ Allocator.prototype.free = function(mID) { }; /** * Your Allocator object will be instantiated and called as such: * var obj = new Allocator(n) * var param_1 = obj.allocate(size,mID) * var param_2 = obj.free(mID) */
You are given an integer n representing the size of a 0-indexed memory array. All memory units are initially free. You have a memory allocator with the following functionalities: Allocate a block of size consecutive free memory units and assign it the id mID. Free all memory units with the given id mID. Note that: Multiple blocks can be allocated to the same mID. You should free all the memory units with mID, even if they were allocated in different blocks. Implement the Allocator class: Allocator(int n) Initializes an Allocator object with a memory array of size n. int allocate(int size, int mID) Find the leftmost block of size consecutive free memory units and allocate it with the id mID. Return the block's first index. If such a block does not exist, return -1. int free(int mID) Free all memory units with the id mID. Return the number of memory units you have freed.   Example 1: Input ["Allocator", "allocate", "allocate", "allocate", "free", "allocate", "allocate", "allocate", "free", "allocate", "free"] [[10], [1, 1], [1, 2], [1, 3], [2], [3, 4], [1, 1], [1, 1], [1], [10, 2], [7]] Output [null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0] Explanation Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free. loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes [1,_,_,_,_,_,_,_,_,_]. We return 0. loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes [1,2,_,_,_,_,_,_,_,_]. We return 1. loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes [1,2,3,_,_,_,_,_,_,_]. We return 2. loc.free(2); // Free all memory units with mID 2. The memory array becomes [1,_, 3,_,_,_,_,_,_,_]. We return 1 since there is only 1 unit with mID 2. loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes [1,_,3,4,4,4,_,_,_,_]. We return 3. loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes [1,1,3,4,4,4,_,_,_,_]. We return 1. loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes [1,1,3,4,4,4,1,_,_,_]. We return 6. loc.free(1); // Free all memory units with mID 1. The memory array becomes [_,_,3,4,4,4,_,_,_,_]. We return 3 since there are 3 units with mID 1. loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1. loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.   Constraints: 1 <= n, size, mID <= 1000 At most 1000 calls will be made to allocate and free.
Medium
[ "array", "hash-table", "design", "simulation" ]
null
[]
2,503
maximum-number-of-points-from-grid-queries
[ "The queries are all given to you beforehand so you can answer them in any order you want.", "Sort the queries knowing their original order to be able to build the answer array.", "Run a BFS on the graph and answer the queries in increasing order." ]
/** * @param {number[][]} grid * @param {number[]} queries * @return {number[]} */ var maxPoints = function(grid, queries) { };
You are given an m x n integer matrix grid and an array queries of size k. Find an array answer of size k such that for each integer queries[i] you start in the top left cell of the matrix and repeat the following process: If queries[i] is strictly greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any adjacent cell in all 4 directions: up, down, left, and right. Otherwise, you do not get any points, and you end this process. After the process, answer[i] is the maximum number of points you can get. Note that for each query you are allowed to visit the same cell multiple times. Return the resulting array answer.   Example 1: Input: grid = [[1,2,3],[2,5,7],[3,5,1]], queries = [5,6,2] Output: [5,8,1] Explanation: The diagrams above show which cells we visit to get points for each query. Example 2: Input: grid = [[5,2,1],[1,1,2]], queries = [3] Output: [0] Explanation: We can not get any points because the value of the top left cell is already greater than or equal to 3.   Constraints: m == grid.length n == grid[i].length 2 <= m, n <= 1000 4 <= m * n <= 105 k == queries.length 1 <= k <= 104 1 <= grid[i][j], queries[i] <= 106
Hard
[ "array", "breadth-first-search", "union-find", "sorting", "heap-priority-queue" ]
[ "const maxPoints = function (grid, queries) {\n const heap = new MinPriorityQueue({\n compare: ({ value: valueA }, { value: valueB }) => valueA - valueB,\n })\n\n const enqueue = (r, c) => {\n if (\n 0 <= r &&\n r < grid.length &&\n 0 <= c &&\n c < grid[0].length &&\n grid[r][c] !== null\n ) {\n heap.enqueue({ row: r, col: c, value: grid[r][c] })\n grid[r][c] = null\n }\n }\n enqueue(0, 0)\n let count = 0\n const map = {}\n const sortedQueries = [...queries].sort((x, y) => x - y)\n\n for (const query of sortedQueries) {\n while (!heap.isEmpty()) {\n const { row, col, value } = heap.front()\n if (query <= value) break\n heap.dequeue()\n enqueue(row + 1, col)\n enqueue(row - 1, col)\n enqueue(row, col + 1)\n enqueue(row, col - 1)\n ++count\n }\n\n map[query] = count\n }\n\n return queries.map((query) => map[query])\n}" ]
2,506
count-pairs-of-similar-strings
[ "How can you check if two strings are similar?", "Use a hashSet to store the character of each string." ]
/** * @param {string[]} words * @return {number} */ var similarPairs = function(words) { };
You are given a 0-indexed string array words. Two strings are similar if they consist of the same characters. For example, "abca" and "cba" are similar since both consist of characters 'a', 'b', and 'c'. However, "abacba" and "bcfd" are not similar since they do not consist of the same characters. Return the number of pairs (i, j) such that 0 <= i < j <= word.length - 1 and the two strings words[i] and words[j] are similar.   Example 1: Input: words = ["aba","aabb","abcd","bac","aabc"] Output: 2 Explanation: There are 2 pairs that satisfy the conditions: - i = 0 and j = 1 : both words[0] and words[1] only consist of characters 'a' and 'b'. - i = 3 and j = 4 : both words[3] and words[4] only consist of characters 'a', 'b', and 'c'. Example 2: Input: words = ["aabb","ab","ba"] Output: 3 Explanation: There are 3 pairs that satisfy the conditions: - i = 0 and j = 1 : both words[0] and words[1] only consist of characters 'a' and 'b'. - i = 0 and j = 2 : both words[0] and words[2] only consist of characters 'a' and 'b'. - i = 1 and j = 2 : both words[1] and words[2] only consist of characters 'a' and 'b'. Example 3: Input: words = ["nba","cba","dba"] Output: 0 Explanation: Since there does not exist any pair that satisfies the conditions, we return 0.   Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 100 words[i] consist of only lowercase English letters.
Easy
[ "array", "hash-table", "string" ]
null
[]
2,507
smallest-value-after-replacing-with-sum-of-prime-factors
[ "Every time you replace n, it will become smaller until it is a prime number, where it will keep the same value each time you replace it.", "n decreases logarithmically, allowing you to simulate the process.", "To find the prime factors, iterate through all numbers less than n from least to greatest and find the maximum number of times each number divides n." ]
/** * @param {number} n * @return {number} */ var smallestValue = function(n) { };
You are given a positive integer n. Continuously replace n with the sum of its prime factors. Note that if a prime factor divides n multiple times, it should be included in the sum as many times as it divides n. Return the smallest value n will take on.   Example 1: Input: n = 15 Output: 5 Explanation: Initially, n = 15. 15 = 3 * 5, so replace n with 3 + 5 = 8. 8 = 2 * 2 * 2, so replace n with 2 + 2 + 2 = 6. 6 = 2 * 3, so replace n with 2 + 3 = 5. 5 is the smallest value n will take on. Example 2: Input: n = 3 Output: 3 Explanation: Initially, n = 3. 3 is the smallest value n will take on.   Constraints: 2 <= n <= 105
Medium
[ "math", "number-theory" ]
null
[]
2,508
add-edges-to-make-degrees-of-all-nodes-even
[ "Notice that each edge that we add changes the degree of exactly 2 nodes.", "The number of nodes with an odd degree in the original graph should be either 0, 2, or 4. Try to work on each of these cases." ]
/** * @param {number} n * @param {number[][]} edges * @return {boolean} */ var isPossible = function(n, edges) { };
There is an undirected graph consisting of n nodes numbered from 1 to n. You are given the integer n and a 2D array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi. The graph can be disconnected. You can add at most two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops. Return true if it is possible to make the degree of each node in the graph even, otherwise return false. The degree of a node is the number of edges connected to it.   Example 1: Input: n = 5, edges = [[1,2],[2,3],[3,4],[4,2],[1,4],[2,5]] Output: true Explanation: The above diagram shows a valid way of adding an edge. Every node in the resulting graph is connected to an even number of edges. Example 2: Input: n = 4, edges = [[1,2],[3,4]] Output: true Explanation: The above diagram shows a valid way of adding two edges. Example 3: Input: n = 4, edges = [[1,2],[1,3],[1,4]] Output: false Explanation: It is not possible to obtain a valid graph with adding at most 2 edges.   Constraints: 3 <= n <= 105 2 <= edges.length <= 105 edges[i].length == 2 1 <= ai, bi <= n ai != bi There are no repeated edges.
Hard
[ "hash-table", "graph" ]
[ "const isPossible = (n, edges) => {\n const g = initializeGraphSet(n)\n packUG_Set(g, edges)\n return canAddAtMost2EdgesMakeALLNodesDegreeEven(g)\n}\n\nfunction initializeGraphSet(n) {\n const g = []\n for (let i = 0; i < n; i++) {\n g.push(new Set())\n }\n return g\n}\nfunction packUG_Set(g, edges) {\n for (const [u, v] of edges) {\n g[u - 1].add(v - 1)\n g[v - 1].add(u - 1)\n }\n}\n\nfunction canAddAtMost2EdgesMakeALLNodesDegreeEven(g) {\n const oddNodes = []\n for (let i = 0; i < g.length; i++) {\n let deg = g[i].size\n if (deg % 2 == 1) {\n oddNodes.push(i)\n }\n }\n if (oddNodes.length == 0) {\n // add no edge\n return true\n } else if (oddNodes.length == 2) {\n // add one edge\n let [a, b] = oddNodes\n for (let k = 0; k < g.length; k++) {\n // a <-> k b <-> k (k as transition node)\n if (!g[a].has(k) && !g[b].has(k)) return true\n }\n return false\n } else if (oddNodes.length == 4) {\n // add two edges\n let [a, b, c, d] = oddNodes // find two matched pairs valid\n if (!g[a].has(b) && !g[c].has(d)) return true\n if (!g[a].has(c) && !g[b].has(d)) return true\n if (!g[a].has(d) && !g[c].has(b)) return true\n return false\n } else {\n return false\n }\n}" ]
2,509
cycle-length-queries-in-a-tree
[ "Find the distance between nodes “a” and “b”.", "distance(a, b) = depth(a) + depth(b) - 2 * LCA(a, b). Where depth(a) denotes depth from root to node “a” and LCA(a, b) denotes the lowest common ancestor of nodes “a” and “b”.", "To find LCA(a, b), iterate over all ancestors of node “a” and check if it is the ancestor of node “b” too. If so, take the one with maximum depth." ]
/** * @param {number} n * @param {number[][]} queries * @return {number[]} */ var cycleLengthQueries = function(n, queries) { };
You are given an integer n. There is a complete binary tree with 2n - 1 nodes. The root of that tree is the node with the value 1, and every node with a value val in the range [1, 2n - 1 - 1] has two children where: The left node has the value 2 * val, and The right node has the value 2 * val + 1. You are also given a 2D integer array queries of length m, where queries[i] = [ai, bi]. For each query, solve the following problem: Add an edge between the nodes with values ai and bi. Find the length of the cycle in the graph. Remove the added edge between nodes with values ai and bi. Note that: A cycle is a path that starts and ends at the same node, and each edge in the path is visited only once. The length of a cycle is the number of edges visited in the cycle. There could be multiple edges between two nodes in the tree after adding the edge of the query. Return an array answer of length m where answer[i] is the answer to the ith query.   Example 1: Input: n = 3, queries = [[5,3],[4,7],[2,3]] Output: [4,5,3] Explanation: The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge. - After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes [5,2,1,3]. Thus answer to the first query is 4. We delete the added edge and process the next query. - After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes [4,2,1,3,7]. Thus answer to the second query is 5. We delete the added edge and process the next query. - After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes [2,1,3]. Thus answer to the third query is 3. We delete the added edge. Example 2: Input: n = 2, queries = [[1,2]] Output: [2] Explanation: The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge. - After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes [2,1]. Thus answer for the first query is 2. We delete the added edge.   Constraints: 2 <= n <= 30 m == queries.length 1 <= m <= 105 queries[i].length == 2 1 <= ai, bi <= 2n - 1 ai != bi
Hard
[ "tree", "binary-tree" ]
null
[]
2,511
maximum-enemy-forts-that-can-be-captured
[ "For each fort under your command, check if you can move the army from here.", "If yes, find the closest empty positions satisfying all criteria.", "How can two-pointers be used to solve this problem optimally?" ]
/** * @param {number[]} forts * @return {number} */ var captureForts = function(forts) { };
You are given a 0-indexed integer array forts of length n representing the positions of several forts. forts[i] can be -1, 0, or 1 where: -1 represents there is no fort at the ith position. 0 indicates there is an enemy fort at the ith position. 1 indicates the fort at the ith the position is under your command. Now you have decided to move your army from one of your forts at position i to an empty position j such that: 0 <= i, j <= n - 1 The army travels over enemy forts only. Formally, for all k where min(i,j) < k < max(i,j), forts[k] == 0. While moving the army, all the enemy forts that come in the way are captured. Return the maximum number of enemy forts that can be captured. In case it is impossible to move your army, or you do not have any fort under your command, return 0.   Example 1: Input: forts = [1,0,0,-1,0,0,0,0,1] Output: 4 Explanation: - Moving the army from position 0 to position 3 captures 2 enemy forts, at 1 and 2. - Moving the army from position 8 to position 3 captures 4 enemy forts. Since 4 is the maximum number of enemy forts that can be captured, we return 4. Example 2: Input: forts = [0,0,1,-1] Output: 0 Explanation: Since no enemy fort can be captured, 0 is returned.   Constraints: 1 <= forts.length <= 1000 -1 <= forts[i] <= 1
Easy
[ "array", "two-pointers" ]
null
[]
2,512
reward-top-k-students
[ "Hash the positive and negative feedback words separately.", "Calculate the points for each student’s feedback.", "Sort the students accordingly to find the top <em>k</em> among them." ]
/** * @param {string[]} positive_feedback * @param {string[]} negative_feedback * @param {string[]} report * @param {number[]} student_id * @param {number} k * @return {number[]} */ var topStudents = function(positive_feedback, negative_feedback, report, student_id, k) { };
You are given two string arrays positive_feedback and negative_feedback, containing the words denoting positive and negative feedback, respectively. Note that no word is both positive and negative. Initially every student has 0 points. Each positive word in a feedback report increases the points of a student by 3, whereas each negative word decreases the points by 1. You are given n feedback reports, represented by a 0-indexed string array report and a 0-indexed integer array student_id, where student_id[i] represents the ID of the student who has received the feedback report report[i]. The ID of each student is unique. Given an integer k, return the top k students after ranking them in non-increasing order by their points. In case more than one student has the same points, the one with the lower ID ranks higher.   Example 1: Input: positive_feedback = ["smart","brilliant","studious"], negative_feedback = ["not"], report = ["this student is studious","the student is smart"], student_id = [1,2], k = 2 Output: [1,2] Explanation: Both the students have 1 positive feedback and 3 points but since student 1 has a lower ID he ranks higher. Example 2: Input: positive_feedback = ["smart","brilliant","studious"], negative_feedback = ["not"], report = ["this student is not studious","the student is smart"], student_id = [1,2], k = 2 Output: [2,1] Explanation: - The student with ID 1 has 1 positive feedback and 1 negative feedback, so he has 3-1=2 points. - The student with ID 2 has 1 positive feedback, so he has 3 points. Since student 2 has more points, [2,1] is returned.   Constraints: 1 <= positive_feedback.length, negative_feedback.length <= 104 1 <= positive_feedback[i].length, negative_feedback[j].length <= 100 Both positive_feedback[i] and negative_feedback[j] consists of lowercase English letters. No word is present in both positive_feedback and negative_feedback. n == report.length == student_id.length 1 <= n <= 104 report[i] consists of lowercase English letters and spaces ' '. There is a single space between consecutive words of report[i]. 1 <= report[i].length <= 100 1 <= student_id[i] <= 109 All the values of student_id[i] are unique. 1 <= k <= n
Medium
[ "array", "hash-table", "string", "sorting", "heap-priority-queue" ]
null
[]
2,513
minimize-the-maximum-of-two-arrays
[ "Use binary search to find smallest maximum element.", "Add numbers divisible by x in nums2 and vice versa." ]
/** * @param {number} divisor1 * @param {number} divisor2 * @param {number} uniqueCnt1 * @param {number} uniqueCnt2 * @return {number} */ var minimizeSet = function(divisor1, divisor2, uniqueCnt1, uniqueCnt2) { };
We have two arrays arr1 and arr2 which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions: arr1 contains uniqueCnt1 distinct positive integers, each of which is not divisible by divisor1. arr2 contains uniqueCnt2 distinct positive integers, each of which is not divisible by divisor2. No integer is present in both arr1 and arr2. Given divisor1, divisor2, uniqueCnt1, and uniqueCnt2, return the minimum possible maximum integer that can be present in either array.   Example 1: Input: divisor1 = 2, divisor2 = 7, uniqueCnt1 = 1, uniqueCnt2 = 3 Output: 4 Explanation: We can distribute the first 4 natural numbers into arr1 and arr2. arr1 = [1] and arr2 = [2,3,4]. We can see that both arrays satisfy all the conditions. Since the maximum value is 4, we return it. Example 2: Input: divisor1 = 3, divisor2 = 5, uniqueCnt1 = 2, uniqueCnt2 = 1 Output: 3 Explanation: Here arr1 = [1,2], and arr2 = [3] satisfy all conditions. Since the maximum value is 3, we return it. Example 3: Input: divisor1 = 2, divisor2 = 4, uniqueCnt1 = 8, uniqueCnt2 = 2 Output: 15 Explanation: Here, the final possible arrays can be arr1 = [1,3,5,7,9,11,13,15], and arr2 = [2,6]. It can be shown that it is not possible to obtain a lower maximum satisfying all conditions.   Constraints: 2 <= divisor1, divisor2 <= 105 1 <= uniqueCnt1, uniqueCnt2 < 109 2 <= uniqueCnt1 + uniqueCnt2 <= 109
Medium
[ "math", "binary-search", "number-theory" ]
null
[]
2,514
count-anagrams
[ "For each word, can you count the number of permutations possible if all characters are distinct?", "How to reduce overcounting when letters are repeated?", "The product of the counts of distinct permutations of all words will give the final answer." ]
/** * @param {string} s * @return {number} */ var countAnagrams = function(s) { };
You are given a string s containing one or more words. Every consecutive pair of words is separated by a single space ' '. A string t is an anagram of string s if the ith word of t is a permutation of the ith word of s. For example, "acb dfe" is an anagram of "abc def", but "def cab" and "adc bef" are not. Return the number of distinct anagrams of s. Since the answer may be very large, return it modulo 109 + 7.   Example 1: Input: s = "too hot" Output: 18 Explanation: Some of the anagrams of the given string are "too hot", "oot hot", "oto toh", "too toh", and "too oht". Example 2: Input: s = "aa" Output: 1 Explanation: There is only one anagram possible for the given string.   Constraints: 1 <= s.length <= 105 s consists of lowercase English letters and spaces ' '. There is single space between consecutive words.
Hard
[ "hash-table", "math", "string", "combinatorics", "counting" ]
null
[]
2,515
shortest-distance-to-target-string-in-a-circular-array
[ "You have two options, either move straight to the left or move straight to the right.", "Find the first target word and record the distance.", "Choose the one with the minimum distance." ]
/** * @param {string[]} words * @param {string} target * @param {number} startIndex * @return {number} */ var closetTarget = function(words, target, startIndex) { };
You are given a 0-indexed circular string array words and a string target. A circular array means that the array's end connects to the array's beginning. Formally, the next element of words[i] is words[(i + 1) % n] and the previous element of words[i] is words[(i - 1 + n) % n], where n is the length of words. Starting from startIndex, you can move to either the next word or the previous word with 1 step at a time. Return the shortest distance needed to reach the string target. If the string target does not exist in words, return -1.   Example 1: Input: words = ["hello","i","am","leetcode","hello"], target = "hello", startIndex = 1 Output: 1 Explanation: We start from index 1 and can reach "hello" by - moving 3 units to the right to reach index 4. - moving 2 units to the left to reach index 4. - moving 4 units to the right to reach index 0. - moving 1 unit to the left to reach index 0. The shortest distance to reach "hello" is 1. Example 2: Input: words = ["a","b","leetcode"], target = "leetcode", startIndex = 0 Output: 1 Explanation: We start from index 0 and can reach "leetcode" by - moving 2 units to the right to reach index 3. - moving 1 unit to the left to reach index 3. The shortest distance to reach "leetcode" is 1. Example 3: Input: words = ["i","eat","leetcode"], target = "ate", startIndex = 0 Output: -1 Explanation: Since "ate" does not exist in words, we return -1.   Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 100 words[i] and target consist of only lowercase English letters. 0 <= startIndex < words.length
Easy
[ "array", "string" ]
null
[]
2,516
take-k-of-each-character-from-left-and-right
[ "Start by counting the frequency of each character and checking if it is possible.", "If you take x characters from the left side, what is the minimum number of characters you need to take from the right side? Find this for all values of x in the range 0 ≤ x ≤ s.length.", "Use a two-pointers approach to avoid computing the same information multiple times." ]
/** * @param {string} s * @param {number} k * @return {number} */ var takeCharacters = function(s, k) { };
You are given a string s consisting of the characters 'a', 'b', and 'c' and a non-negative integer k. Each minute, you may take either the leftmost character of s, or the rightmost character of s. Return the minimum number of minutes needed for you to take at least k of each character, or return -1 if it is not possible to take k of each character.   Example 1: Input: s = "aabaaaacaabc", k = 2 Output: 8 Explanation: Take three characters from the left of s. You now have two 'a' characters, and one 'b' character. Take five characters from the right of s. You now have four 'a' characters, two 'b' characters, and two 'c' characters. A total of 3 + 5 = 8 minutes is needed. It can be proven that 8 is the minimum number of minutes needed. Example 2: Input: s = "a", k = 1 Output: -1 Explanation: It is not possible to take one 'b' or 'c' so return -1.   Constraints: 1 <= s.length <= 105 s consists of only the letters 'a', 'b', and 'c'. 0 <= k <= s.length
Medium
[ "hash-table", "string", "sliding-window" ]
[ "const takeCharacters = function(s, k) {\n const cnt = {a: 0, b: 0, c: 0}\n const n = s.length\n for(const ch of s) {\n cnt[ch]++\n }\n if(cnt.a < k || cnt.b < k || cnt.c < k) return -1\n const limits = { a: cnt.a - k, b: cnt.b - k, c: cnt.c - k }\n let l = 0, r = 0, res = 0\n const hash = {a: 0, b: 0, c: 0}\n for(; r < n; r++) {\n const cur = s[r]\n hash[cur]++\n while(hash[cur] > limits[cur]) {\n hash[s[l]]--\n l++\n }\n \n res = Math.max(res, r - l + 1)\n }\n \n return n - res\n};" ]
2,517
maximum-tastiness-of-candy-basket
[ "The answer is binary searchable.", "For some x, we can use a greedy strategy to check if it is possible to pick k distinct candies with tastiness being at least x.", "Sort prices and iterate from left to right. For some price[i] check if the price difference between the last taken candy and price[i] is at least x. If so, add the candy i to the basket.", "So, a candy basket with tastiness x can be achieved if the basket size is bigger than or equal to k." ]
/** * @param {number[]} price * @param {number} k * @return {number} */ var maximumTastiness = function(price, k) { };
You are given an array of positive integers price where price[i] denotes the price of the ith candy and a positive integer k. The store sells baskets of k distinct candies. The tastiness of a candy basket is the smallest absolute difference of the prices of any two candies in the basket. Return the maximum tastiness of a candy basket.   Example 1: Input: price = [13,5,1,8,21,2], k = 3 Output: 8 Explanation: Choose the candies with the prices [13,5,21]. The tastiness of the candy basket is: min(|13 - 5|, |13 - 21|, |5 - 21|) = min(8, 8, 16) = 8. It can be proven that 8 is the maximum tastiness that can be achieved. Example 2: Input: price = [1,3,1], k = 2 Output: 2 Explanation: Choose the candies with the prices [1,3]. The tastiness of the candy basket is: min(|1 - 3|) = min(2) = 2. It can be proven that 2 is the maximum tastiness that can be achieved. Example 3: Input: price = [7,7,7,7], k = 2 Output: 0 Explanation: Choosing any two distinct candies from the candies we have will result in a tastiness of 0.   Constraints: 2 <= k <= price.length <= 105 1 <= price[i] <= 109
Medium
[ "array", "binary-search", "sorting" ]
null
[]
2,518
number-of-great-partitions
[ "If the sum of the array is smaller than 2*k, then it is impossible to find a great partition.", "Solve the reverse problem, that is, find the number of partitions where the sum of elements of at least one of the two groups is smaller than k." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var countPartitions = function(nums, k) { };
You are given an array nums consisting of positive integers and an integer k. Partition the array into two ordered groups such that each element is in exactly one group. A partition is called great if the sum of elements of each group is greater than or equal to k. Return the number of distinct great partitions. Since the answer may be too large, return it modulo 109 + 7. Two partitions are considered distinct if some element nums[i] is in different groups in the two partitions.   Example 1: Input: nums = [1,2,3,4], k = 4 Output: 6 Explanation: The great partitions are: ([1,2,3], [4]), ([1,3], [2,4]), ([1,4], [2,3]), ([2,3], [1,4]), ([2,4], [1,3]) and ([4], [1,2,3]). Example 2: Input: nums = [3,3,3], k = 4 Output: 0 Explanation: There are no great partitions for this array. Example 3: Input: nums = [6,6], k = 2 Output: 2 Explanation: We can either put nums[0] in the first partition or in the second partition. The great partitions will be ([6], [6]) and ([6], [6]).   Constraints: 1 <= nums.length, k <= 1000 1 <= nums[i] <= 109
Hard
[ "array", "dynamic-programming" ]
[ "const ll = BigInt,\n mod = 1e9 + 7,\n bmod = ll(mod)\nconst sm = (a) => a.reduce((x, y) => x + y, 0)\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}\nconst minus_mod = (x, y, mod) => (((x - y) % mod) + mod) % mod\nconst knapsack_01 = (a, k) => {\n if (sm(a) < 2 * k) return 0\n let dp = Array(k).fill(0)\n dp[0] = 1\n for (const x of a) {\n for (let j = k - 1; j > x - 1; j--) {\n dp[j] += dp[j - x]\n dp[j] %= mod\n }\n }\n let bad = ll(sm(dp) * 2),\n tot = powmod(2n, ll(a.length), bmod),\n good = minus_mod(tot, bad, bmod)\n return good\n}\n\nconst countPartitions = function(nums, k) {\n return knapsack_01(nums, k)\n};" ]
2,520
count-the-digits-that-divide-a-number
[ "Use mod by 10 to retrieve the least significant digit of the number", "Divide the number by 10, then round it down so that the second least significant digit becomes the least significant digit of the number", "Use your language’s mod operator to see if a number is a divisor of another." ]
/** * @param {number} num * @return {number} */ var countDigits = function(num) { };
Given an integer num, return the number of digits in num that divide num. An integer val divides nums if nums % val == 0.   Example 1: Input: num = 7 Output: 1 Explanation: 7 divides itself, hence the answer is 1. Example 2: Input: num = 121 Output: 2 Explanation: 121 is divisible by 1, but not 2. Since 1 occurs twice as a digit, we return 2. Example 3: Input: num = 1248 Output: 4 Explanation: 1248 is divisible by all of its digits, hence the answer is 4.   Constraints: 1 <= num <= 109 num does not contain 0 as one of its digits.
Easy
[ "math" ]
null
[]
2,521
distinct-prime-factors-of-product-of-array
[ "Do not multiply all the numbers together, as the product is too big to store.", "Think about how each individual number's prime factors contribute to the prime factors of the product of the entire array.", "Find the prime factors of each element in nums, and store all of them in a set to avoid duplicates." ]
/** * @param {number[]} nums * @return {number} */ var distinctPrimeFactors = function(nums) { };
Given an array of positive integers nums, return the number of distinct prime factors in the product of the elements of nums. Note that: A number greater than 1 is called prime if it is divisible by only 1 and itself. An integer val1 is a factor of another integer val2 if val2 / val1 is an integer.   Example 1: Input: nums = [2,4,3,7,10,6] Output: 4 Explanation: The product of all the elements in nums is: 2 * 4 * 3 * 7 * 10 * 6 = 10080 = 25 * 32 * 5 * 7. There are 4 distinct prime factors so we return 4. Example 2: Input: nums = [2,4,8,16] Output: 1 Explanation: The product of all the elements in nums is: 2 * 4 * 8 * 16 = 1024 = 210. There is 1 distinct prime factor so we return 1.   Constraints: 1 <= nums.length <= 104 2 <= nums[i] <= 1000
Medium
[ "array", "hash-table", "math", "number-theory" ]
[ "var distinctPrimeFactors = function(nums) {\n const primes = getPrime(1000)\n const ans = new Set()\n nums.forEach(it => {\n let cur = it\n ans.add(primes[cur])\n while (primes[cur] != 1) {\n ans.add(primes[cur])\n cur /= primes[cur]\n }\n ans.add(cur)\n })\n ans.delete(1)\n\n return ans.size\n \n function getPrime(k) {\n const minPrime = new Array(k + 1).fill(1)\n let p = 2\n while (p <= k) {\n let i = p\n while (p <= k / i) {\n if (minPrime[i * p] == 1) {\n minPrime[i * p] = p\n }\n i++\n }\n p++\n while (p <= k) {\n if (minPrime[p] == 1) break\n p++\n }\n }\n return minPrime\n }\n};" ]
2,522
partition-string-into-substrings-with-values-at-most-k
[]
/** * @param {string} s * @param {number} k * @return {number} */ var minimumPartition = function(s, k) { };
You are given a string s consisting of digits from 1 to 9 and an integer k. A partition of a string s is called good if: Each digit of s is part of exactly one substring. The value of each substring is less than or equal to k. Return the minimum number of substrings in a good partition of s. If no good partition of s exists, return -1. Note that: The value of a string is its result when interpreted as an integer. For example, the value of "123" is 123 and the value of "1" is 1. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "165462", k = 60 Output: 4 Explanation: We can partition the string into substrings "16", "54", "6", and "2". Each substring has a value less than or equal to k = 60. It can be shown that we cannot partition the string into less than 4 substrings. Example 2: Input: s = "238182", k = 5 Output: -1 Explanation: There is no good partition for this string.   Constraints: 1 <= s.length <= 105 s[i] is a digit from '1' to '9'. 1 <= k <= 109  
Medium
[ "string", "dynamic-programming", "greedy" ]
null
[]
2,523
closest-prime-numbers-in-range
[ "Use Sieve of Eratosthenes to mark numbers that are primes.", "Iterate from right to left and find pair with the minimum distance between marked numbers." ]
/** * @param {number} left * @param {number} right * @return {number[]} */ var closestPrimes = function(left, right) { };
Given two positive integers left and right, find the two integers num1 and num2 such that: left <= nums1 < nums2 <= right . nums1 and nums2 are both prime numbers. nums2 - nums1 is the minimum amongst all other pairs satisfying the above conditions. Return the positive integer array ans = [nums1, nums2]. If there are multiple pairs satisfying these conditions, return the one with the minimum nums1 value or [-1, -1] if such numbers do not exist. A number greater than 1 is called prime if it is only divisible by 1 and itself.   Example 1: Input: left = 10, right = 19 Output: [11,13] Explanation: The prime numbers between 10 and 19 are 11, 13, 17, and 19. The closest gap between any pair is 2, which can be achieved by [11,13] or [17,19]. Since 11 is smaller than 17, we return the first pair. Example 2: Input: left = 4, right = 6 Output: [-1,-1] Explanation: There exists only one prime number in the given range, so the conditions cannot be satisfied.   Constraints: 1 <= left <= right <= 106  
Medium
[ "math", "number-theory" ]
[ "var closestPrimes = function(left, right) {\n let primeArr = [];\n let res = [-1, -1];\n let minDiff = Infinity;\n\n for(let i=left; i<=right; i++){\n if(isPrime(i)) primeArr.push(i)\n }\n\n for(let i=1; i<primeArr.length; i++){\n let diff = primeArr[i]-primeArr[i-1];\n if(diff<minDiff){\n res = [primeArr[i-1], primeArr[i]]\n minDiff = diff;\n }\n }\n return res\n\n};\n\nfunction isPrime(n) {\n if (n === 1) return false;\n if (n % 2 === 0) return n === 2;\n let max = Math.floor(Math.sqrt(n)) ;\n for(let i = 3; i <= max; i += 2) {\n if (n % i === 0) return false;\n }\n return true;\n}" ]
2,525
categorize-box-according-to-criteria
[ "Use conditional statements to find the right category of the box." ]
/** * @param {number} length * @param {number} width * @param {number} height * @param {number} mass * @return {string} */ var categorizeBox = function(length, width, height, mass) { };
Given four integers length, width, height, and mass, representing the dimensions and mass of a box, respectively, return a string representing the category of the box. The box is "Bulky" if: Any of the dimensions of the box is greater or equal to 104. Or, the volume of the box is greater or equal to 109. If the mass of the box is greater or equal to 100, it is "Heavy". If the box is both "Bulky" and "Heavy", then its category is "Both". If the box is neither "Bulky" nor "Heavy", then its category is "Neither". If the box is "Bulky" but not "Heavy", then its category is "Bulky". If the box is "Heavy" but not "Bulky", then its category is "Heavy". Note that the volume of the box is the product of its length, width and height.   Example 1: Input: length = 1000, width = 35, height = 700, mass = 300 Output: "Heavy" Explanation: None of the dimensions of the box is greater or equal to 104. Its volume = 24500000 <= 109. So it cannot be categorized as "Bulky". However mass >= 100, so the box is "Heavy". Since the box is not "Bulky" but "Heavy", we return "Heavy". Example 2: Input: length = 200, width = 50, height = 800, mass = 50 Output: "Neither" Explanation: None of the dimensions of the box is greater or equal to 104. Its volume = 8 * 106 <= 109. So it cannot be categorized as "Bulky". Its mass is also less than 100, so it cannot be categorized as "Heavy" either. Since its neither of the two above categories, we return "Neither".   Constraints: 1 <= length, width, height <= 105 1 <= mass <= 103
Easy
[ "math" ]
null
[]
2,526
find-consecutive-integers-from-a-data-stream
[ "Keep track of the last integer which is not equal to <code>value</code>.", "Use a queue-type data structure to store the last <code>k</code> integers." ]
/** * @param {number} value * @param {number} k */ var DataStream = function(value, k) { }; /** * @param {number} num * @return {boolean} */ DataStream.prototype.consec = function(num) { }; /** * Your DataStream object will be instantiated and called as such: * var obj = new DataStream(value, k) * var param_1 = obj.consec(num) */
For a stream of integers, implement a data structure that checks if the last k integers parsed in the stream are equal to value. Implement the DataStream class: DataStream(int value, int k) Initializes the object with an empty integer stream and the two integers value and k. boolean consec(int num) Adds num to the stream of integers. Returns true if the last k integers are equal to value, and false otherwise. If there are less than k integers, the condition does not hold true, so returns false.   Example 1: Input ["DataStream", "consec", "consec", "consec", "consec"] [[4, 3], [4], [4], [4], [3]] Output [null, false, false, true, false] Explanation DataStream dataStream = new DataStream(4, 3); //value = 4, k = 3 dataStream.consec(4); // Only 1 integer is parsed, so returns False. dataStream.consec(4); // Only 2 integers are parsed. // Since 2 is less than k, returns False. dataStream.consec(4); // The 3 integers parsed are all equal to value, so returns True. dataStream.consec(3); // The last k integers parsed in the stream are [4,4,3]. // Since 3 is not equal to value, it returns False.   Constraints: 1 <= value, num <= 109 1 <= k <= 105 At most 105 calls will be made to consec.
Medium
[ "hash-table", "design", "queue", "counting", "data-stream" ]
null
[]
2,527
find-xor-beauty-of-array
[ "Try to simplify the given expression.", "Try constructing the answer bit by bit." ]
/** * @param {number[]} nums * @return {number} */ var xorBeauty = function(nums) { };
You are given a 0-indexed integer array nums. The effective value of three indices i, j, and k is defined as ((nums[i] | nums[j]) & nums[k]). The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i, j, k) where 0 <= i, j, k < n. Return the xor-beauty of nums. Note that: val1 | val2 is bitwise OR of val1 and val2. val1 & val2 is bitwise AND of val1 and val2.   Example 1: Input: nums = [1,4] Output: 5 Explanation: The triplets and their corresponding effective values are listed below: - (0,0,0) with effective value ((1 | 1) & 1) = 1 - (0,0,1) with effective value ((1 | 1) & 4) = 0 - (0,1,0) with effective value ((1 | 4) & 1) = 1 - (0,1,1) with effective value ((1 | 4) & 4) = 4 - (1,0,0) with effective value ((4 | 1) & 1) = 1 - (1,0,1) with effective value ((4 | 1) & 4) = 4 - (1,1,0) with effective value ((4 | 4) & 1) = 0 - (1,1,1) with effective value ((4 | 4) & 4) = 4 Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5. Example 2: Input: nums = [15,45,20,2,34,35,5,44,32,30] Output: 34 Explanation: The xor-beauty of the given array is 34.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109
Medium
[ "array", "math", "bit-manipulation" ]
[ "const xorBeauty = function(nums) {\n let res = 0\n for(const e of nums) res ^= e\n return res\n};" ]
2,528
maximize-the-minimum-powered-city
[ "Pre calculate the number of stations on each city using Line Sweep.", "Use binary search to maximize the minimum." ]
/** * @param {number[]} stations * @param {number} r * @param {number} k * @return {number} */ var maxPower = function(stations, r, k) { };
You are given a 0-indexed integer array stations of length n, where stations[i] represents the number of power stations in the ith city. Each power station can provide power to every city in a fixed range. In other words, if the range is denoted by r, then a power station at city i can provide power to all cities j such that |i - j| <= r and 0 <= i, j <= n - 1. Note that |x| denotes absolute value. For example, |7 - 5| = 2 and |3 - 10| = 7. The power of a city is the total number of power stations it is being provided power from. The government has sanctioned building k more power stations, each of which can be built in any city, and have the same range as the pre-existing ones. Given the two integers r and k, return the maximum possible minimum power of a city, if the additional power stations are built optimally. Note that you can build the k power stations in multiple cities.   Example 1: Input: stations = [1,2,4,5,0], r = 1, k = 2 Output: 5 Explanation: One of the optimal ways is to install both the power stations at city 1. So stations will become [1,4,4,5,0]. - City 0 is provided by 1 + 4 = 5 power stations. - City 1 is provided by 1 + 4 + 4 = 9 power stations. - City 2 is provided by 4 + 4 + 5 = 13 power stations. - City 3 is provided by 5 + 4 = 9 power stations. - City 4 is provided by 5 + 0 = 5 power stations. So the minimum power of a city is 5. Since it is not possible to obtain a larger power, we return 5. Example 2: Input: stations = [4,4,4,4], r = 0, k = 3 Output: 4 Explanation: It can be proved that we cannot make the minimum power of a city greater than 4.   Constraints: n == stations.length 1 <= n <= 105 0 <= stations[i] <= 105 0 <= r <= n - 1 0 <= k <= 109
Hard
[ "array", "binary-search", "greedy", "queue", "sliding-window", "prefix-sum" ]
null
[]
2,529
maximum-count-of-positive-integer-and-negative-integer
[ "Count how many positive integers and negative integers are in the array.", "Since the array is sorted, can we use the binary search?" ]
/** * @param {number[]} nums * @return {number} */ var maximumCount = function(nums) { };
Given an array nums sorted in non-decreasing order, return the maximum between the number of positive integers and the number of negative integers. In other words, if the number of positive integers in nums is pos and the number of negative integers is neg, then return the maximum of pos and neg. Note that 0 is neither positive nor negative.   Example 1: Input: nums = [-2,-1,-1,1,2,3] Output: 3 Explanation: There are 3 positive integers and 3 negative integers. The maximum count among them is 3. Example 2: Input: nums = [-3,-2,-1,0,0,1,2] Output: 3 Explanation: There are 2 positive integers and 3 negative integers. The maximum count among them is 3. Example 3: Input: nums = [5,20,66,1314] Output: 4 Explanation: There are 4 positive integers and 0 negative integers. The maximum count among them is 4.   Constraints: 1 <= nums.length <= 2000 -2000 <= nums[i] <= 2000 nums is sorted in a non-decreasing order.   Follow up: Can you solve the problem in O(log(n)) time complexity?
Easy
[ "array", "binary-search", "counting" ]
[ "var maximumCount = function(nums) {\n let pos = 0, neg = 0\n \n for(const e of nums) {\n if(e > 0) pos++\n else if(e < 0) neg++\n }\n \n return Math.max(pos, neg)\n};" ]
2,530
maximal-score-after-applying-k-operations
[ "It is always optimal to select the greatest element in the array.", "Use a heap to query for the maximum in O(log n) time." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var maxKelements = function(nums, k) { };
You are given a 0-indexed integer array nums and an integer k. You have a starting score of 0. In one operation: choose an index i such that 0 <= i < nums.length, increase your score by nums[i], and replace nums[i] with ceil(nums[i] / 3). Return the maximum possible score you can attain after applying exactly k operations. The ceiling function ceil(val) is the least integer greater than or equal to val.   Example 1: Input: nums = [10,10,10,10,10], k = 5 Output: 50 Explanation: Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50. Example 2: Input: nums = [1,10,3,3,3], k = 3 Output: 17 Explanation: You can do the following operations: Operation 1: Select i = 1, so nums becomes [1,4,3,3,3]. Your score increases by 10. Operation 2: Select i = 1, so nums becomes [1,2,3,3,3]. Your score increases by 4. Operation 3: Select i = 2, so nums becomes [1,1,1,3,3]. Your score increases by 3. The final score is 10 + 4 + 3 = 17.   Constraints: 1 <= nums.length, k <= 105 1 <= nums[i] <= 109
Medium
[ "array", "greedy", "heap-priority-queue" ]
[ "var maxKelements = function(nums, k) {\n const pq = new PQ((a, b) => a > b)\n for(const e of nums) pq.push(e)\n let res = 0\n while(k) {\n const tmp = pq.pop()\n res += tmp\n pq.push(Math.ceil(tmp / 3))\n k--\n }\n \n return res\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}" ]
2,531
make-number-of-distinct-characters-equal
[ "Create a frequency array of the letters of each string.", "There are 26*26 possible pairs of letters to swap. Can we try them all?", "Iterate over all possible pairs of letters and check if swapping them will yield two strings that have the same number of distinct characters. Use the frequency array for the check." ]
/** * @param {string} word1 * @param {string} word2 * @return {boolean} */ var isItPossible = function(word1, word2) { };
You are given two 0-indexed strings word1 and word2. A move consists of choosing two indices i and j such that 0 <= i < word1.length and 0 <= j < word2.length and swapping word1[i] with word2[j]. Return true if it is possible to get the number of distinct characters in word1 and word2 to be equal with exactly one move. Return false otherwise.   Example 1: Input: word1 = "ac", word2 = "b" Output: false Explanation: Any pair of swaps would yield two distinct characters in the first string, and one in the second string. Example 2: Input: word1 = "abcc", word2 = "aab" Output: true Explanation: We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = "abac" and word2 = "cab", which both have 3 distinct characters. Example 3: Input: word1 = "abcde", word2 = "fghij" Output: true Explanation: Both resulting strings will have 5 distinct characters, regardless of which indices we swap.   Constraints: 1 <= word1.length, word2.length <= 105 word1 and word2 consist of only lowercase English letters.
Medium
[ "hash-table", "string", "counting" ]
[ "const isItPossible = function(word1, word2) {\n const map1 = new Array(26).fill(0);\n const map2 = new Array(26).fill(0);\n \n const a = 'a'.charCodeAt(0)\n\t\t// store frequency of characters\n for (const ch of word1) map1[ch.charCodeAt(0)-a]++;\n for (const ch of word2) map2[ch.charCodeAt(0)-a]++;\n\n for (let i = 0; i < 26; i++) {\n if (map1[i] === 0) continue;\n for (let j = 0; j < 26; j++) {\n if (map2[j] === 0) continue;\n\n // increase freq of char2 and decrease freq of char1 in map1\n map1[j]++;\n map1[i]--;\n\n // increase freq of char1 and decrease freq of char2 in map2\n map2[i]++;\n map2[j]--;\n\n // if equal number of unique characters, return true\n if (same(map1, map2)) return true;\n\n // revert back changes\n map1[j]--;\n map1[i]++;\n map2[i]--;\n map2[j]++;\n }\n }\n\n return false;\n \n \t// check if both maps contain equal number of unique characters\n function same( map1, map2) {\n let count1 = 0;\n let count2 = 0;\n for (let i = 0; i < 26; i++) {\n if (map1[i] > 0) count1++;\n if (map2[i] > 0) count2++;\n }\n\n return count1 === count2;\n }\n};" ]
2,532
time-to-cross-a-bridge
[ "Try simulating this process.", "We can use a priority queue to query over the least efficient worker." ]
/** * @param {number} n * @param {number} k * @param {number[][]} time * @return {number} */ var findCrossingTime = function(n, k, time) { };
There are k workers who want to move n boxes from an old warehouse to a new one. You are given the two integers n and k, and a 2D integer array time of size k x 4 where time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]. The warehouses are separated by a river and connected by a bridge. The old warehouse is on the right bank of the river, and the new warehouse is on the left bank of the river. Initially, all k workers are waiting on the left side of the bridge. To move the boxes, the ith worker (0-indexed) can : Cross the bridge from the left bank (new warehouse) to the right bank (old warehouse) in leftToRighti minutes. Pick a box from the old warehouse and return to the bridge in pickOldi minutes. Different workers can pick up their boxes simultaneously. Cross the bridge from the right bank (old warehouse) to the left bank (new warehouse) in rightToLefti minutes. Put the box in the new warehouse and return to the bridge in putNewi minutes. Different workers can put their boxes simultaneously. A worker i is less efficient than a worker j if either condition is met: leftToRighti + rightToLefti > leftToRightj + rightToLeftj leftToRighti + rightToLefti == leftToRightj + rightToLeftj and i > j The following rules regulate the movement of the workers through the bridge : If a worker x reaches the bridge while another worker y is crossing the bridge, x waits at their side of the bridge. If the bridge is free, the worker waiting on the right side of the bridge gets to cross the bridge. If more than one worker is waiting on the right side, the one with the lowest efficiency crosses first. If the bridge is free and no worker is waiting on the right side, and at least one box remains at the old warehouse, the worker on the left side of the river gets to cross the bridge. If more than one worker is waiting on the left side, the one with the lowest efficiency crosses first. Return the instance of time at which the last worker reaches the left bank of the river after all n boxes have been put in the new warehouse.   Example 1: Input: n = 1, k = 3, time = [[1,1,2,1],[1,1,3,1],[1,1,4,1]] Output: 6 Explanation: From 0 to 1: worker 2 crosses the bridge from the left bank to the right bank. From 1 to 2: worker 2 picks up a box from the old warehouse. From 2 to 6: worker 2 crosses the bridge from the right bank to the left bank. From 6 to 7: worker 2 puts a box at the new warehouse. The whole process ends after 7 minutes. We return 6 because the problem asks for the instance of time at which the last worker reaches the left bank. Example 2: Input: n = 3, k = 2, time = [[1,9,1,8],[10,10,10,10]] Output: 50 Explanation: From 0  to 10: worker 1 crosses the bridge from the left bank to the right bank. From 10 to 20: worker 1 picks up a box from the old warehouse. From 10 to 11: worker 0 crosses the bridge from the left bank to the right bank. From 11 to 20: worker 0 picks up a box from the old warehouse. From 20 to 30: worker 1 crosses the bridge from the right bank to the left bank. From 30 to 40: worker 1 puts a box at the new warehouse. From 30 to 31: worker 0 crosses the bridge from the right bank to the left bank. From 31 to 39: worker 0 puts a box at the new warehouse. From 39 to 40: worker 0 crosses the bridge from the left bank to the right bank. From 40 to 49: worker 0 picks up a box from the old warehouse. From 49 to 50: worker 0 crosses the bridge from the right bank to the left bank. From 50 to 58: worker 0 puts a box at the new warehouse. The whole process ends after 58 minutes. We return 50 because the problem asks for the instance of time at which the last worker reaches the left bank.   Constraints: 1 <= n, k <= 104 time.length == k time[i].length == 4 1 <= leftToRighti, pickOldi, rightToLefti, putNewi <= 1000
Hard
[ "array", "heap-priority-queue", "simulation" ]
null
[]
2,535
difference-between-element-sum-and-digit-sum-of-an-array
[ "Use a simple for loop to iterate each number.", "How you can get the digit for each number?" ]
/** * @param {number[]} nums * @return {number} */ var differenceOfSum = function(nums) { };
You are given a positive integer array nums. The element sum is the sum of all the elements in nums. The digit sum is the sum of all the digits (not necessarily distinct) that appear in nums. Return the absolute difference between the element sum and digit sum of nums. Note that the absolute difference between two integers x and y is defined as |x - y|.   Example 1: Input: nums = [1,15,6,3] Output: 9 Explanation: The element sum of nums is 1 + 15 + 6 + 3 = 25. The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16. The absolute difference between the element sum and digit sum is |25 - 16| = 9. Example 2: Input: nums = [1,2,3,4] Output: 0 Explanation: The element sum of nums is 1 + 2 + 3 + 4 = 10. The digit sum of nums is 1 + 2 + 3 + 4 = 10. The absolute difference between the element sum and digit sum is |10 - 10| = 0.   Constraints: 1 <= nums.length <= 2000 1 <= nums[i] <= 2000
Easy
[ "array", "math" ]
null
[]
2,536
increment-submatrices-by-one
[ "Imagine each row as a separate array. Instead of updating the whole submatrix together, we can use prefix sum to update each row separately.", "For each query, iterate over the rows i in the range [row1, row2] and add 1 to prefix sum S[i][col1], and subtract 1 from S[i][col2 + 1].", "After doing this operation for all the queries, update each row separately with S[i][j] = S[i][j] + S[i][j - 1]." ]
/** * @param {number} n * @param {number[][]} queries * @return {number[][]} */ var rangeAddQueries = function(n, queries) { };
You are given a positive integer n, indicating that we initially have an n x n 0-indexed integer matrix mat filled with zeroes. You are also given a 2D integer array query. For each query[i] = [row1i, col1i, row2i, col2i], you should do the following operation: Add 1 to every element in the submatrix with the top left corner (row1i, col1i) and the bottom right corner (row2i, col2i). That is, add 1 to mat[x][y] for all row1i <= x <= row2i and col1i <= y <= col2i. Return the matrix mat after performing every query.   Example 1: Input: n = 3, queries = [[1,1,2,2],[0,0,1,1]] Output: [[1,1,0],[1,2,1],[0,1,1]] Explanation: The diagram above shows the initial matrix, the matrix after the first query, and the matrix after the second query. - In the first query, we add 1 to every element in the submatrix with the top left corner (1, 1) and bottom right corner (2, 2). - In the second query, we add 1 to every element in the submatrix with the top left corner (0, 0) and bottom right corner (1, 1). Example 2: Input: n = 2, queries = [[0,0,1,1]] Output: [[1,1],[1,1]] Explanation: The diagram above shows the initial matrix and the matrix after the first query. - In the first query we add 1 to every element in the matrix.   Constraints: 1 <= n <= 500 1 <= queries.length <= 104 0 <= row1i <= row2i < n 0 <= col1i <= col2i < n
Medium
[ "array", "matrix", "prefix-sum" ]
null
[]
2,537
count-the-number-of-good-subarrays
[ "For a fixed index l, try to find the minimum value of index r, such that the subarray is not good", "When a number is added to a subarray, it increases the number of pairs by its previous appearances.", "When a number is removed from the subarray, it decreases the number of pairs by its remaining appearances.", "Maintain 2-pointers l and r such that we can keep in account the number of equal pairs." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var countGood = function(nums, k) { };
Given an integer array nums and an integer k, return the number of good subarrays of nums. A subarray arr is good if it there are at least k pairs of indices (i, j) such that i < j and arr[i] == arr[j]. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,1,1,1,1], k = 10 Output: 1 Explanation: The only good subarray is the array nums itself. Example 2: Input: nums = [3,1,4,3,2,2,4], k = 2 Output: 4 Explanation: There are 4 different good subarrays: - [3,1,4,3,2,2] that has 2 pairs. - [3,1,4,3,2,2,4] that has 3 pairs. - [1,4,3,2,2,4] that has 2 pairs. - [4,3,2,2,4] that has 2 pairs.   Constraints: 1 <= nums.length <= 105 1 <= nums[i], k <= 109
Medium
[ "array", "hash-table", "sliding-window" ]
null
[]
2,538
difference-between-maximum-and-minimum-price-sum
[ "The minimum price sum is always the price of a rooted node.", "Let’s root the tree at vertex 0 and find the answer from this perspective.", "In the optimal answer maximum price is the sum of the prices of nodes on the path from “u” to “v” where either “u” or “v” is the parent of the second one or neither is a parent of the second one.", "The first case is easy to find. For the second case, notice that in the optimal path, “u” and “v” are both leaves. Then we can use dynamic programming to find such a path.", "Let DP(v,1) denote “the maximum price sum from node v to leaf, where v is a parent of that leaf” and let DP(v,0) denote “the maximum price sum from node v to leaf, where v is a parent of that leaf - price[leaf]”. Then the answer is maximum of DP(u,0) + DP(v,1) + price[parent] where u, v are directly connected to vertex “parent”." ]
/** * @param {number} n * @param {number[][]} edges * @param {number[]} price * @return {number} */ var maxOutput = function(n, edges, price) { };
There exists an undirected and initially unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node. The price sum of a given path is the sum of the prices of all nodes lying on that path. The tree can be rooted at any node root of your choice. The incurred cost after choosing root is the difference between the maximum and minimum price sum amongst all paths starting at root. Return the maximum possible cost amongst all possible root choices.   Example 1: Input: n = 6, edges = [[0,1],[1,2],[1,3],[3,4],[3,5]], price = [9,8,7,6,10,5] Output: 24 Explanation: The diagram above denotes the tree after rooting it at node 2. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum. - The first path contains nodes [2,1,3,4]: the prices are [7,8,6,10], and the sum of the prices is 31. - The second path contains the node [2] with the price [7]. The difference between the maximum and minimum price sum is 24. It can be proved that 24 is the maximum cost. Example 2: Input: n = 3, edges = [[0,1],[1,2]], price = [1,1,1] Output: 2 Explanation: The diagram above denotes the tree after rooting it at node 0. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum. - The first path contains nodes [0,1,2]: the prices are [1,1,1], and the sum of the prices is 3. - The second path contains node [0] with a price [1]. The difference between the maximum and minimum price sum is 2. It can be proved that 2 is the maximum cost.   Constraints: 1 <= n <= 105 edges.length == n - 1 0 <= ai, bi <= n - 1 edges represents a valid tree. price.length == n 1 <= price[i] <= 105
Hard
[ "array", "dynamic-programming", "tree", "depth-first-search" ]
[ "const maxOutput = function(n, edges, price) {\n const tree = [];\n const memo = [];\n for (let i = 0; i < n; i++) tree[i] = [];\n for (const [a, b] of edges) {\n tree[a].push(b);\n tree[b].push(a);\n }\n\n let result = 0;\n dfs(0, -1);\n\n function dfs(node, parent) {\n const max = [price[node], 0];\n const nodes = tree[node] ?? [];\n for (const child of nodes) {\n if (child === parent) continue;\n const sub = dfs(child, node);\n result = Math.max(result, max[0] + sub[1]);\n result = Math.max(result, max[1] + sub[0]);\n max[0] = Math.max(max[0], sub[0] + price[node]);\n max[1] = Math.max(max[1], sub[1] + price[node]);\n }\n return max;\n }\n\n return result;\n};" ]
2,540
minimum-common-value
[ "Try to use a set.", "Otherwise, try to use a two-pointer approach." ]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var getCommon = function(nums1, nums2) { };
Given two integer arrays nums1 and nums2, sorted in non-decreasing order, return the minimum integer common to both arrays. If there is no common integer amongst nums1 and nums2, return -1. Note that an integer is said to be common to nums1 and nums2 if both arrays have at least one occurrence of that integer.   Example 1: Input: nums1 = [1,2,3], nums2 = [2,4] Output: 2 Explanation: The smallest element common to both arrays is 2, so we return 2. Example 2: Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5] Output: 2 Explanation: There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.   Constraints: 1 <= nums1.length, nums2.length <= 105 1 <= nums1[i], nums2[j] <= 109 Both nums1 and nums2 are sorted in non-decreasing order.
Easy
[ "array", "hash-table", "two-pointers", "binary-search" ]
null
[]
2,541
minimum-operations-to-make-array-equal-ii
[ "What are the cases for which we cannot make nums1 == nums2?", "For minimum moves, if nums1[i] < nums2[i], then we should never decrement nums1[i]. \r\nIf nums1[i] > nums2[i], then we should never increment nums1[i]." ]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @param {number} k * @return {number} */ var minOperations = function(nums1, nums2, k) { };
You are given two integer arrays nums1 and nums2 of equal length n and an integer k. You can perform the following operation on nums1: Choose two indexes i and j and increment nums1[i] by k and decrement nums1[j] by k. In other words, nums1[i] = nums1[i] + k and nums1[j] = nums1[j] - k. nums1 is said to be equal to nums2 if for all indices i such that 0 <= i < n, nums1[i] == nums2[i]. Return the minimum number of operations required to make nums1 equal to nums2. If it is impossible to make them equal, return -1.   Example 1: Input: nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3 Output: 2 Explanation: In 2 operations, we can transform nums1 to nums2. 1st operation: i = 2, j = 0. After applying the operation, nums1 = [1,3,4,4]. 2nd operation: i = 2, j = 3. After applying the operation, nums1 = [1,3,7,1]. One can prove that it is impossible to make arrays equal in fewer operations. Example 2: Input: nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1 Output: -1 Explanation: It can be proved that it is impossible to make the two arrays equal.   Constraints: n == nums1.length == nums2.length 2 <= n <= 105 0 <= nums1[i], nums2[j] <= 109 0 <= k <= 105
Medium
[ "array", "math", "greedy" ]
null
[]
2,542
maximum-subsequence-score
[ "How can we use sorting here?", "Try sorting the two arrays based on second array.", "Loop through nums2 and compute the max product given the minimum is nums2[i]. Update the answer accordingly." ]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @param {number} k * @return {number} */ var maxScore = function(nums1, nums2, k) { };
You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive integer k. You must choose a subsequence of indices from nums1 of length k. For chosen indices i0, i1, ..., ik - 1, your score is defined as: The sum of the selected elements from nums1 multiplied with the minimum of the selected elements from nums2. It can defined simply as: (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] , nums2[i1], ... ,nums2[ik - 1]). Return the maximum possible score. A subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1} by deleting some or no elements.   Example 1: Input: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3 Output: 12 Explanation: The four possible subsequence scores are: - We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7. - We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6. - We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12. - We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8. Therefore, we return the max score, which is 12. Example 2: Input: nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1 Output: 30 Explanation: Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.   Constraints: n == nums1.length == nums2.length 1 <= n <= 105 0 <= nums1[i], nums2[j] <= 105 1 <= k <= n
Medium
[ "array", "greedy", "sorting", "heap-priority-queue" ]
[ "const maxScore = function(nums1, nums2, k) {\n const pq = new MinPriorityQueue({ priority: e => e })\n const n = nums1.length\n const arr = []\n \n for(let i = 0; i < n; i++) {\n arr.push([nums1[i], nums2[i]])\n }\n \n arr.sort((a, b) => b[1] - a[1])\n let res = 0, left = 0\n for(let i = 0; i < n; i++) {\n const cur = arr[i]\n pq.enqueue(cur[0])\n left += cur[0]\n if(pq.size() > k) {\n const tmp = pq.dequeue().element\n left -= tmp\n }\n \n if(pq.size() === k) {\n res = Math.max(res, left * cur[1])\n }\n }\n \n return res\n};" ]
2,543
check-if-point-is-reachable
[ "Let’s go in reverse order, from (targetX, targetY) to (1, 1). So, now we can move from (x, y) to (x+y, y), (x, y+x), (x/2, y) if x is even, and (x, y/2) if y is even.", "When is it optimal to use the third and fourth operations?", "Think how GCD of (x, y) is affected if we apply the first two operations.", "How can we check if we can reach (1, 1) using the GCD value calculate above?" ]
/** * @param {number} targetX * @param {number} targetY * @return {boolean} */ var isReachable = function(targetX, targetY) { };
There exists an infinitely large grid. You are currently at point (1, 1), and you need to reach the point (targetX, targetY) using a finite number of steps. In one step, you can move from point (x, y) to any one of the following points: (x, y - x) (x - y, y) (2 * x, y) (x, 2 * y) Given two integers targetX and targetY representing the X-coordinate and Y-coordinate of your final position, return true if you can reach the point from (1, 1) using some number of steps, and false otherwise.   Example 1: Input: targetX = 6, targetY = 9 Output: false Explanation: It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned. Example 2: Input: targetX = 4, targetY = 7 Output: true Explanation: You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7).   Constraints: 1 <= targetX, targetY <= 109
Hard
[ "math", "number-theory" ]
null
[]
2,544
alternating-digit-sum
[ "The first step is to loop over the digits. We can convert the integer into a string, an array of digits, or just loop over its digits.", "Keep a variable sign that initially equals 1 and a variable answer that initially equals 0.", "Each time you loop over a digit i, add sign * i to answer, then multiply sign by -1." ]
/** * @param {number} n * @return {number} */ var alternateDigitSum = function(n) { };
You are given a positive integer n. Each digit of n has a sign according to the following rules: The most significant digit is assigned a positive sign. Each other digit has an opposite sign to its adjacent digits. Return the sum of all digits with their corresponding sign.   Example 1: Input: n = 521 Output: 4 Explanation: (+5) + (-2) + (+1) = 4. Example 2: Input: n = 111 Output: 1 Explanation: (+1) + (-1) + (+1) = 1. Example 3: Input: n = 886996 Output: 0 Explanation: (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.   Constraints: 1 <= n <= 109  
Easy
[ "math" ]
null
[]
2,545
sort-the-students-by-their-kth-score
[ "Find the row with the highest score in the kth exam and swap it with the first row.", "After fixing the first row, perform the same operation for the rest of the rows, and the matrix's rows will get sorted one by one." ]
/** * @param {number[][]} score * @param {number} k * @return {number[][]} */ var sortTheStudents = function(score, k) { };
There is a class with m students and n exams. You are given a 0-indexed m x n integer matrix score, where each row represents one student and score[i][j] denotes the score the ith student got in the jth exam. The matrix score contains distinct integers only. You are also given an integer k. Sort the students (i.e., the rows of the matrix) by their scores in the kth (0-indexed) exam from the highest to the lowest. Return the matrix after sorting it.   Example 1: Input: score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2 Output: [[7,5,11,2],[10,6,9,1],[4,8,3,15]] Explanation: In the above diagram, S denotes the student, while E denotes the exam. - The student with index 1 scored 11 in exam 2, which is the highest score, so they got first place. - The student with index 0 scored 9 in exam 2, which is the second highest score, so they got second place. - The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third place. Example 2: Input: score = [[3,4],[5,6]], k = 0 Output: [[5,6],[3,4]] Explanation: In the above diagram, S denotes the student, while E denotes the exam. - The student with index 1 scored 5 in exam 0, which is the highest score, so they got first place. - The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second place.   Constraints: m == score.length n == score[i].length 1 <= m, n <= 250 1 <= score[i][j] <= 105 score consists of distinct integers. 0 <= k < n
Medium
[ "array", "sorting", "matrix" ]
null
[]
2,546
apply-bitwise-operations-to-make-strings-equal
[ "Think of when it is impossible to convert the string to the target.", "If exactly one of the strings is having all 0’s, then it is impossible. And it is possible in all other cases. Why is that true?" ]
/** * @param {string} s * @param {string} target * @return {boolean} */ var makeStringsEqual = function(s, target) { };
You are given two 0-indexed binary strings s and target of the same length n. You can do the following operation on s any number of times: Choose two different indices i and j where 0 <= i, j < n. Simultaneously, replace s[i] with (s[i] OR s[j]) and s[j] with (s[i] XOR s[j]). For example, if s = "0110", you can choose i = 0 and j = 2, then simultaneously replace s[0] with (s[0] OR s[2] = 0 OR 1 = 1), and s[2] with (s[0] XOR s[2] = 0 XOR 1 = 1), so we will have s = "1110". Return true if you can make the string s equal to target, or false otherwise.   Example 1: Input: s = "1010", target = "0110" Output: true Explanation: We can do the following operations: - Choose i = 2 and j = 0. We have now s = "0010". - Choose i = 2 and j = 1. We have now s = "0110". Since we can make s equal to target, we return true. Example 2: Input: s = "11", target = "00" Output: false Explanation: It is not possible to make s equal to target with any number of operations.   Constraints: n == s.length == target.length 2 <= n <= 105 s and target consist of only the digits 0 and 1.
Medium
[ "string", "bit-manipulation" ]
null
[]
2,547
minimum-cost-to-split-an-array
[ "Let's denote dp[r] = minimum cost to partition the first r elements of nums. What would be the transitions of such dynamic programming?", "dp[r] = min(dp[l] + importance(nums[l..r])) over all 0 <= l < r. This already gives us an O(n^3) approach, as importance can be calculated in linear time, and there are a total of O(n^2) transitions.", "Can you think of a way to compute multiple importance values of related subarrays faster?", "importance(nums[l-1..r]) is either importance(nums[l..r]) if a new unique element is added, importance(nums[l..r]) + 1 if an old element that appeared at least twice is added, or importance(nums[l..r]) + 2, if a previously unique element is duplicated. This allows us to compute importance(nums[l..r]) for all 0 <= l < r in O(n) by keeping a frequency table and decreasing l from r-1 down to 0." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var minCost = function(nums, k) { };
You are given an integer array nums and an integer k. Split the array into some number of non-empty subarrays. The cost of a split is the sum of the importance value of each subarray in the split. Let trimmed(subarray) be the version of the subarray where all numbers which appear only once are removed. For example, trimmed([3,1,2,4,3,4]) = [3,4,3,4]. The importance value of a subarray is k + trimmed(subarray).length. For example, if a subarray is [1,2,3,3,3,4,4], then trimmed([1,2,3,3,3,4,4]) = [3,3,3,4,4].The importance value of this subarray will be k + 5. Return the minimum possible cost of a split of nums. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,2,1,2,1,3,3], k = 2 Output: 8 Explanation: We split nums to have two subarrays: [1,2], [1,2,1,3,3]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1,3,3] is 2 + (2 + 2) = 6. The cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits. Example 2: Input: nums = [1,2,1,2,1], k = 2 Output: 6 Explanation: We split nums to have two subarrays: [1,2], [1,2,1]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1] is 2 + (2) = 4. The cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits. Example 3: Input: nums = [1,2,1,2,1], k = 5 Output: 10 Explanation: We split nums to have one subarray: [1,2,1,2,1]. The importance value of [1,2,1,2,1] is 5 + (3 + 2) = 10. The cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits.   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] < nums.length 1 <= k <= 109  
Hard
[ "array", "hash-table", "dynamic-programming", "counting" ]
null
[]
2,549
count-distinct-numbers-on-board
[ "For n > 2, n % (n - 1) == 1 thus n - 1 will be added on the board the next day.", "As the operations are performed for so long time, all the numbers lesser than n except 1 will be added to the board.", "What will happen if n == 1?" ]
/** * @param {number} n * @return {number} */ var distinctIntegers = function(n) { };
You are given a positive integer n, that is initially placed on a board. Every day, for 109 days, you perform the following procedure: For each number x present on the board, find all numbers 1 <= i <= n such that x % i == 1. Then, place those numbers on the board. Return the number of distinct integers present on the board after 109 days have elapsed. Note: Once a number is placed on the board, it will remain on it until the end. % stands for the modulo operation. For example, 14 % 3 is 2.   Example 1: Input: n = 5 Output: 4 Explanation: Initially, 5 is present on the board. The next day, 2 and 4 will be added since 5 % 2 == 1 and 5 % 4 == 1. After that day, 3 will be added to the board because 4 % 3 == 1. At the end of a billion days, the distinct numbers on the board will be 2, 3, 4, and 5. Example 2: Input: n = 3 Output: 2 Explanation: Since 3 % 2 == 1, 2 will be added to the board. After a billion days, the only two distinct numbers on the board are 2 and 3.   Constraints: 1 <= n <= 100
Easy
[ "array", "hash-table", "math", "simulation" ]
null
[]
2,550
count-collisions-of-monkeys-on-a-polygon
[ "Try counting the number of ways in which the monkeys will not collide." ]
/** * @param {number} n * @return {number} */ var monkeyMove = function(n) { };
There is a regular convex polygon with n vertices. The vertices are labeled from 0 to n - 1 in a clockwise direction, and each vertex has exactly one monkey. The following figure shows a convex polygon of 6 vertices. Each monkey moves simultaneously to a neighboring vertex. A neighboring vertex for a vertex i can be: the vertex (i + 1) % n in the clockwise direction, or the vertex (i - 1 + n) % n in the counter-clockwise direction. A collision happens if at least two monkeys reside on the same vertex after the movement or intersect on an edge. Return the number of ways the monkeys can move so that at least one collision happens. Since the answer may be very large, return it modulo 109 + 7. Note that each monkey can only move once.   Example 1: Input: n = 3 Output: 6 Explanation: There are 8 total possible movements. Two ways such that they collide at some point are: - Monkey 1 moves in a clockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 2 collide. - Monkey 1 moves in an anticlockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 3 collide. It can be shown 6 total movements result in a collision. Example 2: Input: n = 4 Output: 14 Explanation: It can be shown that there are 14 ways for the monkeys to collide.   Constraints: 3 <= n <= 109
Medium
[ "math", "recursion" ]
null
[]
2,551
put-marbles-in-bags
[ "Each bag will contain a sub-array.", "Only the endpoints of the sub-array matter.", "Try to use a priority queue." ]
/** * @param {number[]} weights * @param {number} k * @return {number} */ var putMarbles = function(weights, k) { };
You have k bags. You are given a 0-indexed integer array weights where weights[i] is the weight of the ith marble. You are also given the integer k. Divide the marbles into the k bags according to the following rules: No bag is empty. If the ith marble and jth marble are in a bag, then all marbles with an index between the ith and jth indices should also be in that same bag. If a bag consists of all the marbles with an index from i to j inclusively, then the cost of the bag is weights[i] + weights[j]. The score after distributing the marbles is the sum of the costs of all the k bags. Return the difference between the maximum and minimum scores among marble distributions.   Example 1: Input: weights = [1,3,5,1], k = 2 Output: 4 Explanation: The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. Thus, we return their difference 10 - 6 = 4. Example 2: Input: weights = [1, 3], k = 2 Output: 0 Explanation: The only distribution possible is [1],[3]. Since both the maximal and minimal score are the same, we return 0.   Constraints: 1 <= k <= weights.length <= 105 1 <= weights[i] <= 109
Hard
[ "array", "greedy", "sorting", "heap-priority-queue" ]
[ "const putMarbles = function (weights, k) {\n if (weights.length === k) return 0\n let getEdgeWeights = weights.map((n, i, a) =>\n i < a.length - 1 ? n + a[i + 1] : 0\n )\n getEdgeWeights = getEdgeWeights.slice(0, weights.length - 1)\n getEdgeWeights = getEdgeWeights.sort((a, b) => a - b)\n let maxScores = getEdgeWeights\n .slice(getEdgeWeights.length - k + 1)\n .reduce((a, b) => a + b, 0)\n let minScores = getEdgeWeights.slice(0, k - 1).reduce((a, b) => a + b, 0)\n return maxScores - minScores\n}" ]
2,552
count-increasing-quadruplets
[ "Can you loop over all possible (j, k) and find the answer?", "We can pre-compute all possible (i, j) and (k, l) and store them in 2 matrices.", "The answer will the sum of prefix[j][k] * suffix[k][j]." ]
/** * @param {number[]} nums * @return {number} */ var countQuadruplets = function(nums) { };
Given a 0-indexed integer array nums of size n containing all numbers from 1 to n, return the number of increasing quadruplets. A quadruplet (i, j, k, l) is increasing if: 0 <= i < j < k < l < n, and nums[i] < nums[k] < nums[j] < nums[l].   Example 1: Input: nums = [1,3,2,4,5] Output: 2 Explanation: - When i = 0, j = 1, k = 2, and l = 3, nums[i] < nums[k] < nums[j] < nums[l]. - When i = 0, j = 1, k = 2, and l = 4, nums[i] < nums[k] < nums[j] < nums[l]. There are no other quadruplets, so we return 2. Example 2: Input: nums = [1,2,3,4] Output: 0 Explanation: There exists only one quadruplet with i = 0, j = 1, k = 2, l = 3, but since nums[j] < nums[k], we return 0.   Constraints: 4 <= nums.length <= 4000 1 <= nums[i] <= nums.length All the integers of nums are unique. nums is a permutation.
Hard
[ "array", "dynamic-programming", "binary-indexed-tree", "enumeration", "prefix-sum" ]
null
[]
2,553
separate-the-digits-in-an-array
[ "Convert each number into a list and append that list to the answer.", "You can convert the integer into a string to do that easily." ]
/** * @param {number[]} nums * @return {number[]} */ var separateDigits = function(nums) { };
Given an array of positive integers nums, return an array answer that consists of the digits of each integer in nums after separating them in the same order they appear in nums. To separate the digits of an integer is to get all the digits it has in the same order. For example, for the integer 10921, the separation of its digits is [1,0,9,2,1].   Example 1: Input: nums = [13,25,83,77] Output: [1,3,2,5,8,3,7,7] Explanation: - The separation of 13 is [1,3]. - The separation of 25 is [2,5]. - The separation of 83 is [8,3]. - The separation of 77 is [7,7]. answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order. Example 2: Input: nums = [7,1,3,9] Output: [7,1,3,9] Explanation: The separation of each integer in nums is itself. answer = [7,1,3,9].   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 105
Easy
[ "array", "simulation" ]
null
[]
2,554
maximum-number-of-integers-to-choose-from-a-range-i
[ "Keep the banned numbers that are less than n in a set.", "Loop over the numbers from 1 to n and if the number is not banned, use it.", "Keep adding numbers while they are not banned, and their sum is less than k." ]
/** * @param {number[]} banned * @param {number} n * @param {number} maxSum * @return {number} */ var maxCount = function(banned, n, maxSum) { };
You are given an integer array banned and two integers n and maxSum. You are choosing some number of integers following the below rules: The chosen integers have to be in the range [1, n]. Each integer can be chosen at most once. The chosen integers should not be in the array banned. The sum of the chosen integers should not exceed maxSum. Return the maximum number of integers you can choose following the mentioned rules.   Example 1: Input: banned = [1,6,5], n = 5, maxSum = 6 Output: 2 Explanation: You can choose the integers 2 and 4. 2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum. Example 2: Input: banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1 Output: 0 Explanation: You cannot choose any integer while following the mentioned conditions. Example 3: Input: banned = [11], n = 7, maxSum = 50 Output: 7 Explanation: You can choose the integers 1, 2, 3, 4, 5, 6, and 7. They are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum.   Constraints: 1 <= banned.length <= 104 1 <= banned[i], n <= 104 1 <= maxSum <= 109
Medium
[ "array", "hash-table", "binary-search", "greedy", "sorting" ]
null
[]
2,555
maximize-win-from-two-segments
[ "Try solving the problem for one interval.", "Using the solution with one interval, how can you combine that with a second interval?" ]
/** * @param {number[]} prizePositions * @param {number} k * @return {number} */ var maximizeWin = function(prizePositions, k) { };
There are some prizes on the X-axis. You are given an integer array prizePositions that is sorted in non-decreasing order, where prizePositions[i] is the position of the ith prize. There could be different prizes at the same position on the line. You are also given an integer k. You are allowed to select two segments with integer endpoints. The length of each segment must be k. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect. For example if k = 2, you can choose segments [1, 3] and [2, 4], and you will win any prize i that satisfies 1 <= prizePositions[i] <= 3 or 2 <= prizePositions[i] <= 4. Return the maximum number of prizes you can win if you choose the two segments optimally.   Example 1: Input: prizePositions = [1,1,2,2,3,3,5], k = 2 Output: 7 Explanation: In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5]. Example 2: Input: prizePositions = [1,2,3,4], k = 0 Output: 2 Explanation: For this example, one choice for the segments is [3, 3] and [4, 4], and you will be able to get 2 prizes.   Constraints: 1 <= prizePositions.length <= 105 1 <= prizePositions[i] <= 109 0 <= k <= 109 prizePositions is sorted in non-decreasing order.  
Medium
[ "array", "binary-search", "sliding-window" ]
[ "const maximizeWin = function(prizePositions, k) {\n let res = 0, j = 0\n const n = prizePositions.length, dp = new Array(n + 1).fill(0);\n for (let i = 0; i < n; ++i) {\n while (prizePositions[j] < prizePositions[i] - k) ++j;\n dp[i + 1] = Math.max(dp[i], i - j + 1);\n res = Math.max(res, i - j + 1 + dp[j]);\n }\n return res;\n};" ]
2,556
disconnect-path-in-a-binary-matrix-by-at-most-one-flip
[ "We can consider the grid a graph with edges between adjacent cells.", "If you can find two non-intersecting paths from (0, 0) to (m - 1, n - 1) then the answer is false. Otherwise, it is always true." ]
/** * @param {number[][]} grid * @return {boolean} */ var isPossibleToCutPath = function(grid) { };
You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row, col) to any of the cells (row + 1, col) or (row, col + 1) that has the value 1. The matrix is disconnected if there is no path from (0, 0) to (m - 1, n - 1). You can flip the value of at most one (possibly none) cell. You cannot flip the cells (0, 0) and (m - 1, n - 1). Return true if it is possible to make the matrix disconnect or false otherwise. Note that flipping a cell changes its value from 0 to 1 or from 1 to 0.   Example 1: Input: grid = [[1,1,1],[1,0,0],[1,1,1]] Output: true Explanation: We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid. Example 2: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: false Explanation: It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2).   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 1000 1 <= m * n <= 105 grid[i][j] is either 0 or 1. grid[0][0] == grid[m - 1][n - 1] == 1
Medium
[ "array", "dynamic-programming", "depth-first-search", "breadth-first-search", "matrix" ]
[ "const isPossibleToCutPath = function(grid) {\n const m = grid.length, n = grid[0].length\n const pre = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n const suf = Array.from({ length: m + 2 }, () => Array(n + 2).fill(0))\n \n for(let i = 1; i <= m; i++) {\n for(let j = 1; j <= n; j++) {\n if(i === 1 && j === 1) pre[i][j] = 1\n else if(grid[i - 1][j - 1] === 1) {\n pre[i][j] = pre[i - 1][j] + pre[i][j - 1]\n }\n }\n }\n \n for(let i = m; i > 0; i--) {\n for(let j = n; j > 0; j--) {\n if(i === m && j === n) suf[i][j] = 1\n else if(grid[i - 1][j - 1] === 1) {\n suf[i][j] = suf[i + 1][j] + suf[i][j + 1]\n }\n }\n }\n // console.log(pre, suf)\n \n const target = pre[m][n]\n \n for(let i = 1; i <= m; i++) {\n for(let j = 1; j <= n; j++) {\n if(i === 1 && j === 1) continue\n if(i === m && j === n) continue\n if(pre[i][j] * suf[i][j] === target) {\n return true\n }\n }\n }\n \n return false\n};" ]
2,558
take-gifts-from-the-richest-pile
[ "How can you keep track of the largest gifts in the array", "What is an efficient way to find the square root of a number?", "Can you keep adding up the values of the gifts while ensuring they are in a certain order?", "Can we use a priority queue or heap here?" ]
/** * @param {number[]} gifts * @param {number} k * @return {number} */ var pickGifts = function(gifts, k) { };
You are given an integer array gifts denoting the number of gifts in various piles. Every second, you do the following: Choose the pile with the maximum number of gifts. If there is more than one pile with the maximum number of gifts, choose any. Leave behind the floor of the square root of the number of gifts in the pile. Take the rest of the gifts. Return the number of gifts remaining after k seconds.   Example 1: Input: gifts = [25,64,9,4,100], k = 4 Output: 29 Explanation: The gifts are taken in the following way: - In the first second, the last pile is chosen and 10 gifts are left behind. - Then the second pile is chosen and 8 gifts are left behind. - After that the first pile is chosen and 5 gifts are left behind. - Finally, the last pile is chosen again and 3 gifts are left behind. The final remaining gifts are [5,8,9,4,3], so the total number of gifts remaining is 29. Example 2: Input: gifts = [1,1,1,1], k = 4 Output: 4 Explanation: In this case, regardless which pile you choose, you have to leave behind 1 gift in each pile. That is, you can't take any pile with you. So, the total gifts remaining are 4.   Constraints: 1 <= gifts.length <= 103 1 <= gifts[i] <= 109 1 <= k <= 103
Easy
[ "array", "heap-priority-queue", "simulation" ]
[ "const pickGifts = function(gifts, k) {\n \n const n = gifts.length\n while(k > 0) {\n \n const max = Math.max(...gifts)\n const idx = gifts.indexOf(max)\n gifts[idx] = ~~(Math.sqrt(max))\n \n k--\n }\n \n return gifts.reduce((ac, e) => ac + e, 0)\n};" ]
2,559
count-vowel-strings-in-ranges
[ "Precompute the prefix sum of strings that start and end with vowels.", "Use unordered_set to store vowels.", "Check if the first and last characters of the string are present in the vowels set.", "Subtract prefix sum for range [l-1, r] to find the number of strings starting and ending with vowels." ]
/** * @param {string[]} words * @param {number[][]} queries * @return {number[]} */ var vowelStrings = function(words, queries) { };
You are given a 0-indexed array of strings words and a 2D array of integers queries. Each query queries[i] = [li, ri] asks us to find the number of strings present in the range li to ri (both inclusive) of words that start and end with a vowel. Return an array ans of size queries.length, where ans[i] is the answer to the ith query. Note that the vowel letters are 'a', 'e', 'i', 'o', and 'u'.   Example 1: Input: words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]] Output: [2,3,0] Explanation: The strings starting and ending with a vowel are "aba", "ece", "aa" and "e". The answer to the query [0,2] is 2 (strings "aba" and "ece"). to query [1,4] is 3 (strings "ece", "aa", "e"). to query [1,1] is 0. We return [2,3,0]. Example 2: Input: words = ["a","e","i"], queries = [[0,2],[0,1],[2,2]] Output: [3,2,1] Explanation: Every string satisfies the conditions, so we return [3,2,1].   Constraints: 1 <= words.length <= 105 1 <= words[i].length <= 40 words[i] consists only of lowercase English letters. sum(words[i].length) <= 3 * 105 1 <= queries.length <= 105 0 <= li <= ri < words.length
Medium
[ "array", "string", "prefix-sum" ]
[ "const vowelStrings = function(words, queries) {\n const n = words.length\n const pre = Array(n + 1).fill(0)\n const set = new Set(['a', 'e', 'i', 'o', 'u'])\n for(let i = 0; i < n; i++) {\n const cur = words[i]\n if(set.has(cur[0]) && set.has(cur[cur.length - 1])) pre[i + 1] = 1\n }\n \n const cnt = Array(n + 1).fill(0)\n for(let i = 1; i <= n; i++) {\n cnt[i] = cnt[i - 1] + pre[i]\n }\n \n const res = []\n \n for(const [l, r] of queries) {\n res.push(cnt[r + 1] - cnt[l])\n }\n \n return res\n};" ]
2,560
house-robber-iv
[ "Can we use binary search to find the minimum value of a non-contiguous subsequence of a given size k?", "Initialize the search range with the minimum and maximum elements of the input array.", "Use a check function to determine if it is possible to select k non-consecutive elements that are less than or equal to the current \"guess\" value.", "Adjust the search range based on the outcome of the check function, until the range converges and the minimum value is found." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var minCapability = function(nums, k) { };
There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he refuses to steal from adjacent homes. The capability of the robber is the maximum amount of money he steals from one house of all the houses he robbed. You are given an integer array nums representing how much money is stashed in each house. More formally, the ith house from the left has nums[i] dollars. You are also given an integer k, representing the minimum number of houses the robber will steal from. It is always possible to steal at least k houses. Return the minimum capability of the robber out of all the possible ways to steal at least k houses.   Example 1: Input: nums = [2,3,5,9], k = 2 Output: 5 Explanation: There are three ways to rob at least 2 houses: - Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5. - Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9. - Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9. Therefore, we return min(5, 9, 9) = 5. Example 2: Input: nums = [2,7,9,3,1], k = 2 Output: 2 Explanation: There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109 1 <= k <= (nums.length + 1)/2
Medium
[ "array", "binary-search" ]
[ "const minCapability = function(nums, k) {\n const n = nums.length\n let l = 1, r = 1e9\n while(l < r) {\n const mid = Math.floor((l + r) / 2)\n let cnt = 0\n for(let i = 0; i < n; i++) {\n if(nums[i] <= mid) {\n cnt++\n i++\n }\n }\n if(cnt >= k) r = mid\n else l = mid + 1\n }\n return l\n};" ]
2,561
rearranging-fruits
[ "Create two frequency maps for both arrays, and find the minimum element among all elements of both arrays.", "Check if the sum of frequencies of an element in both arrays is odd, if so return -1", "Store the elements that need to be swapped in a vector, and sort it.", "Can we reduce swapping cost with the help of minimum element?", "Calculate the minimum cost of swapping." ]
/** * @param {number[]} basket1 * @param {number[]} basket2 * @return {number} */ var minCost = function(basket1, basket2) { };
You have two fruit baskets containing n fruits each. You are given two 0-indexed integer arrays basket1 and basket2 representing the cost of fruit in each basket. You want to make both baskets equal. To do so, you can use the following operation as many times as you want: Chose two indices i and j, and swap the ith fruit of basket1 with the jth fruit of basket2. The cost of the swap is min(basket1[i],basket2[j]). Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets. Return the minimum cost to make both the baskets equal or -1 if impossible.   Example 1: Input: basket1 = [4,2,2,2], basket2 = [1,4,1,2] Output: 1 Explanation: Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal. Example 2: Input: basket1 = [2,3,4,1], basket2 = [3,2,5,1] Output: -1 Explanation: It can be shown that it is impossible to make both the baskets equal.   Constraints: basket1.length == basket2.length 1 <= basket1.length <= 105 1 <= basket1[i],basket2[i] <= 109
Hard
[ "array", "hash-table", "greedy" ]
[ "const minCost = function (basket1, basket2) {\n const [map1, map2] = [new Map(), new Map()]\n let minVal = Number.MAX_SAFE_INTEGER\n\n for (const val of basket1) {\n if (!map1.has(val)) map1.set(val, 0)\n map1.set(val, map1.get(val) + 1)\n minVal = Math.min(minVal, val)\n }\n for (const val of basket2) {\n if (!map2.has(val)) map2.set(val, 0)\n map2.set(val, map2.get(val) + 1)\n minVal = Math.min(minVal, val)\n }\n\n const [swapList1, swapList2] = [[], []]\n for (const [key, c1] of map1.entries()) {\n const c2 = map2.get(key) || 0\n if ((c1 + c2) % 2) return -1\n if (c1 > c2) {\n let addCnt = (c1 - c2) >> 1\n while (addCnt--) {\n swapList1.push(key)\n }\n }\n }\n for (const [key, c2] of map2.entries()) {\n const c1 = map1.get(key) || 0\n if ((c1 + c2) % 2) return -1\n if (c2 > c1) {\n let addCnt = (c2 - c1) >> 1\n while (addCnt--) {\n swapList2.push(key)\n }\n }\n }\n\n swapList1.sort((a, b) => a - b)\n swapList2.sort((a, b) => b - a)\n const n = swapList1.length\n\n let res = 0\n for (let i = 0; i < n; i++) {\n res += Math.min(2 * minVal, swapList1[i], swapList2[i])\n }\n\n return res\n}" ]
2,562
find-the-array-concatenation-value
[ "Consider simulating the process to calculate the answer", "iterate until the array becomes empty. In each iteration, concatenate the first element to the last element and add their concatenation value to the answer.", "Don’t forget to handle cases when one element is left in the end, not two elements." ]
/** * @param {number[]} nums * @return {number} */ var findTheArrayConcVal = function(nums) { };
You are given a 0-indexed integer array nums. The concatenation of two numbers is the number formed by concatenating their numerals. For example, the concatenation of 15, 49 is 1549. The concatenation value of nums is initially equal to 0. Perform this operation until nums becomes empty: If there exists more than one number in nums, pick the first element and last element in nums respectively and add the value of their concatenation to the concatenation value of nums, then delete the first and last element from nums. If one element exists, add its value to the concatenation value of nums, then delete it. Return the concatenation value of the nums.   Example 1: Input: nums = [7,52,2,4] Output: 596 Explanation: Before performing any operation, nums is [7,52,2,4] and concatenation value is 0. - In the first operation: We pick the first element, 7, and the last element, 4. Their concatenation is 74, and we add it to the concatenation value, so it becomes equal to 74. Then we delete them from nums, so nums becomes equal to [52,2]. - In the second operation: We pick the first element, 52, and the last element, 2. Their concatenation is 522, and we add it to the concatenation value, so it becomes equal to 596. Then we delete them from the nums, so nums becomes empty. Since the concatenation value is 596 so the answer is 596. Example 2: Input: nums = [5,14,13,8,12] Output: 673 Explanation: Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0. - In the first operation: We pick the first element, 5, and the last element, 12. Their concatenation is 512, and we add it to the concatenation value, so it becomes equal to 512. Then we delete them from the nums, so nums becomes equal to [14,13,8]. - In the second operation: We pick the first element, 14, and the last element, 8. Their concatenation is 148, and we add it to the concatenation value, so it becomes equal to 660. Then we delete them from the nums, so nums becomes equal to [13]. - In the third operation: nums has only one element, so we pick 13 and add it to the concatenation value, so it becomes equal to 673. Then we delete it from nums, so nums become empty. Since the concatenation value is 673 so the answer is 673.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 104  
Easy
[ "array", "two-pointers", "simulation" ]
null
[]
2,563
count-the-number-of-fair-pairs
[ "Sort the array in ascending order.", "For each number in the array, keep track of the smallest and largest numbers in the array that can form a fair pair with this number.", "As you move to larger number, both boundaries move down." ]
/** * @param {number[]} nums * @param {number} lower * @param {number} upper * @return {number} */ var countFairPairs = function(nums, lower, upper) { };
Given a 0-indexed integer array nums of size n and two integers lower and upper, return the number of fair pairs. A pair (i, j) is fair if: 0 <= i < j < n, and lower <= nums[i] + nums[j] <= upper   Example 1: Input: nums = [0,1,7,4,4,5], lower = 3, upper = 6 Output: 6 Explanation: There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5). Example 2: Input: nums = [1,7,9,2,5], lower = 11, upper = 11 Output: 1 Explanation: There is a single fair pair: (2,3).   Constraints: 1 <= nums.length <= 105 nums.length == n -109 <= nums[i] <= 109 -109 <= lower <= upper <= 109
Medium
[ "array", "two-pointers", "binary-search", "sorting" ]
[ "const countFairPairs = function(nums, lower, upper) {\n const n = nums.length\n nums.sort((a, b) => a - b)\n \n let total = BigInt(n * (n - 1)) / 2n\n return Number(total - BigInt(large(nums, upper) + low(nums, lower)))\n};\n\n\nfunction large(arr, target) {\n let count = 0;\n for (let lo = 0, hi = arr.length - 1; lo < hi; ) {\n if (arr[lo] + arr[hi] > target) {\n count += (hi - lo);\n hi--;\n } else {\n lo++;\n }\n }\n return count;\n}\n\nfunction low(arr, target) {\n let count = 0;\n for (let lo = 0, hi = arr.length - 1; lo < hi; ) {\n if (arr[lo] + arr[hi] < target) {\n count += (hi - lo);\n lo++;\n } else {\n hi--;\n }\n }\n return count;\n}" ]
2,564
substring-xor-queries
[ "You do not need to consider substrings having lengths greater than 30.", "Pre-process all substrings with lengths not greater than 30, and add the best endpoints to a dictionary." ]
/** * @param {string} s * @param {number[][]} queries * @return {number[][]} */ var substringXorQueries = function(s, queries) { };
You are given a binary string s, and a 2D integer array queries where queries[i] = [firsti, secondi]. For the ith query, find the shortest substring of s whose decimal value, val, yields secondi when bitwise XORed with firsti. In other words, val ^ firsti == secondi. The answer to the ith query is the endpoints (0-indexed) of the substring [lefti, righti] or [-1, -1] if no such substring exists. If there are multiple answers, choose the one with the minimum lefti. Return an array ans where ans[i] = [lefti, righti] is the answer to the ith query. A substring is a contiguous non-empty sequence of characters within a string.   Example 1: Input: s = "101101", queries = [[0,5],[1,2]] Output: [[0,2],[2,3]] Explanation: For the first query the substring in range [0,2] is "101" which has a decimal value of 5, and 5 ^ 0 = 5, hence the answer to the first query is [0,2]. In the second query, the substring in range [2,3] is "11", and has a decimal value of 3, and 3 ^ 1 = 2. So, [2,3] is returned for the second query. Example 2: Input: s = "0101", queries = [[12,8]] Output: [[-1,-1]] Explanation: In this example there is no substring that answers the query, hence [-1,-1] is returned. Example 3: Input: s = "1", queries = [[4,5]] Output: [[0,0]] Explanation: For this example, the substring in range [0,0] has a decimal value of 1, and 1 ^ 4 = 5. So, the answer is [0,0].   Constraints: 1 <= s.length <= 104 s[i] is either '0' or '1'. 1 <= queries.length <= 105 0 <= firsti, secondi <= 109
Medium
[ "array", "hash-table", "string", "bit-manipulation" ]
null
[]
2,565
subsequence-with-the-minimum-score
[ "Maintain two pointers: i and j. We need to perform a similar operation: while t[0:i] + t[j:n] is not a subsequence of the string s, increase j.", "We can check the condition greedily. Create the array leftmost[i] which denotes minimum index k, such that in prefix s[0:k] exists subsequence t[0:i]. Similarly, we define rightmost[i].", "If leftmost[i] < rightmost[j] then t[0:i] + t[j:n] is the subsequence of s." ]
/** * @param {string} s * @param {string} t * @return {number} */ var minimumScore = function(s, t) { };
You are given two strings s and t. You are allowed to remove any number of characters from the string t. The score of the string is 0 if no characters are removed from the string t, otherwise: Let left be the minimum index among all removed characters. Let right be the maximum index among all removed characters. Then the score of the string is right - left + 1. Return the minimum possible score to make t a subsequence of s. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).   Example 1: Input: s = "abacaba", t = "bzaa" Output: 1 Explanation: In this example, we remove the character "z" at index 1 (0-indexed). The string t becomes "baa" which is a subsequence of the string "abacaba" and the score is 1 - 1 + 1 = 1. It can be proven that 1 is the minimum score that we can achieve. Example 2: Input: s = "cde", t = "xyz" Output: 3 Explanation: In this example, we remove characters "x", "y" and "z" at indices 0, 1, and 2 (0-indexed). The string t becomes "" which is a subsequence of the string "cde" and the score is 2 - 0 + 1 = 3. It can be proven that 3 is the minimum score that we can achieve.   Constraints: 1 <= s.length, t.length <= 105 s and t consist of only lowercase English letters.
Hard
[ "two-pointers", "string", "binary-search" ]
[ "var minimumScore = function(s, t) {\n let sl = s.length, tl = t.length, k = tl - 1;\n const dp = new Array(tl).fill(-1);\n for (let i = sl - 1; i >= 0 && k >= 0; --i) {\n if (s.charAt(i) === t.charAt(k)) dp[k--] = i;\n }\n let res = k + 1;\n for (let i = 0, j = 0; i < sl && j < tl && res > 0; ++i) {\n if (s.charAt(i) === t.charAt(j)) {\n while(k < tl && dp[k] <= i) k++\n j++\n res = Math.min(res, k - j);\n } \n }\n\n return res;\n};" ]
2,566
maximum-difference-by-remapping-a-digit
[ "Try to remap the first non-zero digit to 9 to obtain the maximum number.", "Try to remap the first non-nine digit to 0 to obtain the minimum number." ]
/** * @param {number} num * @return {number} */ var minMaxDifference = function(num) { };
You are given an integer num. You know that Danny Mittal will sneakily remap one of the 10 possible digits (0 to 9) to another digit. Return the difference between the maximum and minimum values Danny can make by remapping exactly one digit in num. Notes: When Danny remaps a digit d1 to another digit d2, Danny replaces all occurrences of d1 in num with d2. Danny can remap a digit to itself, in which case num does not change. Danny can remap different digits for obtaining minimum and maximum values respectively. The resulting number after remapping can contain leading zeroes. We mentioned "Danny Mittal" to congratulate him on being in the top 10 in Weekly Contest 326.   Example 1: Input: num = 11891 Output: 99009 Explanation: To achieve the maximum value, Danny can remap the digit 1 to the digit 9 to yield 99899. To achieve the minimum value, Danny can remap the digit 1 to the digit 0, yielding 890. The difference between these two numbers is 99009. Example 2: Input: num = 90 Output: 99 Explanation: The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0). Thus, we return 99.   Constraints: 1 <= num <= 108
Easy
[ "math", "greedy" ]
null
[]
2,567
minimum-score-by-changing-two-elements
[ "Changing the minimum or maximum values will only minimize the score.", "Think about what all possible pairs of minimum and maximum values can be changed to form the minimum score." ]
/** * @param {number[]} nums * @return {number} */ var minimizeSum = function(nums) { };
You are given a 0-indexed integer array nums. The low score of nums is the minimum value of |nums[i] - nums[j]| over all 0 <= i < j < nums.length. The high score of nums is the maximum value of |nums[i] - nums[j]| over all 0 <= i < j < nums.length. The score of nums is the sum of the high and low scores of nums. To minimize the score of nums, we can change the value of at most two elements of nums. Return the minimum possible score after changing the value of at most two elements of nums. Note that |x| denotes the absolute value of x.   Example 1: Input: nums = [1,4,3] Output: 0 Explanation: Change value of nums[1] and nums[2] to 1 so that nums becomes [1,1,1]. Now, the value of |nums[i] - nums[j]| is always equal to 0, so we return 0 + 0 = 0. Example 2: Input: nums = [1,4,7,8,5] Output: 3 Explanation: Change nums[0] and nums[1] to be 6. Now nums becomes [6,6,7,8,5]. Our low score is achieved when i = 0 and j = 1, in which case |nums[i] - nums[j]| = |6 - 6| = 0. Our high score is achieved when i = 3 and j = 4, in which case |nums[i] - nums[j]| = |8 - 5| = 3. The sum of our high and low score is 3, which we can prove to be minimal.   Constraints: 3 <= nums.length <= 105 1 <= nums[i] <= 109
Medium
[ "array", "greedy", "sorting" ]
[ "const minimizeSum = function(nums) {\n let s1 = Infinity, s2 = Infinity, s3 = Infinity\n let l1 = -1, l2 = -1, l3 = -1\n const { max, min } = Math\n // s1, s2, s3, ..., l3, l2, l1\n for(const e of nums) {\n if(s1 > e) {\n s3 = s2;\n s2 = s1;\n s1 = e;\n } else if(s2 > e) {\n s3 = s2\n s2 = e\n } else if(s3 > e) {\n s3 = e\n }\n \n if(e > l1) {\n l3 = l2\n l2 = l1\n l1 = e\n } else if(e > l2) {\n l3 = l2\n l2 = e\n } else if(e > l3) {\n l3 = e\n }\n }\n \n return min(l1 - s3, l2 - s2, l3 - s1)\n};", "const minimizeSum = function(nums) {\n nums.sort((a, b) => a - b)\n const { max, min, abs } = Math\n const res1 = nums.at(-1) - nums[2]\n const res2 = nums.at(-2) - nums[1]\n const res3 = nums.at(-3) - nums[0]\n return min(res1, res2, res3)\n};" ]
2,568
minimum-impossible-or
[ "Think about forming numbers in the powers of 2 using their bit representation.", "The minimum power of 2 not present in the array will be the first number that could not be expressed using the given operation." ]
/** * @param {number[]} nums * @return {number} */ var minImpossibleOR = function(nums) { };
You are given a 0-indexed integer array nums. We say that an integer x is expressible from nums if there exist some integers 0 <= index1 < index2 < ... < indexk < nums.length for which nums[index1] | nums[index2] | ... | nums[indexk] = x. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of nums. Return the minimum positive non-zero integer that is not expressible from nums.   Example 1: Input: nums = [2,1] Output: 4 Explanation: 1 and 2 are already present in the array. We know that 3 is expressible, since nums[0] | nums[1] = 2 | 1 = 3. Since 4 is not expressible, we return 4. Example 2: Input: nums = [5,3,2] Output: 1 Explanation: We can show that 1 is the smallest number that is not expressible.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109
Medium
[ "array", "bit-manipulation", "brainteaser" ]
[ "var minImpossibleOR = function(nums) {\n const s = new Set();\n for (const e of nums) s.add(e);\n let res = 1;\n while (s.has(res)) res <<= 1;\n return res;\n};" ]
2,569
handling-sum-queries-after-update
[ "Use the Lazy Segment Tree to process the queries quickly." ]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @param {number[][]} queries * @return {number[]} */ var handleQuery = function(nums1, nums2, queries) { };
You are given two 0-indexed arrays nums1 and nums2 and a 2D array queries of queries. There are three types of queries: For a query of type 1, queries[i] = [1, l, r]. Flip the values from 0 to 1 and from 1 to 0 in nums1 from index l to index r. Both l and r are 0-indexed. For a query of type 2, queries[i] = [2, p, 0]. For every index 0 <= i < n, set nums2[i] = nums2[i] + nums1[i] * p. For a query of type 3, queries[i] = [3, 0, 0]. Find the sum of the elements in nums2. Return an array containing all the answers to the third type queries.   Example 1: Input: nums1 = [1,0,1], nums2 = [0,0,0], queries = [[1,1,1],[2,1,0],[3,0,0]] Output: [3] Explanation: After the first query nums1 becomes [1,1,1]. After the second query, nums2 becomes [1,1,1], so the answer to the third query is 3. Thus, [3] is returned. Example 2: Input: nums1 = [1], nums2 = [5], queries = [[2,0,0],[3,0,0]] Output: [5] Explanation: After the first query, nums2 remains [5], so the answer to the second query is 5. Thus, [5] is returned.   Constraints: 1 <= nums1.length,nums2.length <= 105 nums1.length = nums2.length 1 <= queries.length <= 105 queries[i].length = 3 0 <= l <= r <= nums1.length - 1 0 <= p <= 106 0 <= nums1[i] <= 1 0 <= nums2[i] <= 109
Hard
[ "array", "segment-tree" ]
null
[]
2,570
merge-two-2d-arrays-by-summing-values
[ "Use a dictionary/hash map to keep track of the indices and their sum\r\nvalues." ]
/** * @param {number[][]} nums1 * @param {number[][]} nums2 * @return {number[][]} */ var mergeArrays = function(nums1, nums2) { };
You are given two 2D integer arrays nums1 and nums2. nums1[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali. nums2[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali. Each array contains unique ids and is sorted in ascending order by id. Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions: Only ids that appear in at least one of the two arrays should be included in the resulting array. Each id should be included only once and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be 0. Return the resulting array. The returned array must be sorted in ascending order by id.   Example 1: Input: nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]] Output: [[1,6],[2,3],[3,2],[4,6]] Explanation: The resulting array contains the following: - id = 1, the value of this id is 2 + 4 = 6. - id = 2, the value of this id is 3. - id = 3, the value of this id is 2. - id = 4, the value of this id is 5 + 1 = 6. Example 2: Input: nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]] Output: [[1,3],[2,4],[3,6],[4,3],[5,5]] Explanation: There are no common ids, so we just include each id with its value in the resulting list.   Constraints: 1 <= nums1.length, nums2.length <= 200 nums1[i].length == nums2[j].length == 2 1 <= idi, vali <= 1000 Both arrays contain unique ids. Both arrays are in strictly ascending order by id.
Easy
[ "array", "hash-table", "two-pointers" ]
[ "var mergeArrays = function(nums1, nums2) {\n const map = new Map()\n for(const [id, val] of nums1) {\n if(!map.has(id)) map.set(id, 0)\n map.set(id, map.get(id) + val)\n }\n for(const [id, val] of nums2) {\n if(!map.has(id)) map.set(id, 0)\n map.set(id, map.get(id) + val)\n }\n const entries = [...map.entries()]\n entries.sort((a, b) => a[0] - b[0])\n return entries\n};" ]
2,571
minimum-operations-to-reduce-an-integer-to-0
[ "Can we set/unset the bits in binary representation?", "If there are multiple adjacent ones, how can we optimally add and subtract in 2 operations such that all ones get unset?", "Bonus: Try to solve the problem with higher constraints: n ≤ 10^18." ]
/** * @param {number} n * @return {number} */ var minOperations = function(n) { };
You are given a positive integer n, you can do the following operation any number of times: Add or subtract a power of 2 from n. Return the minimum number of operations to make n equal to 0. A number x is power of 2 if x == 2i where i >= 0.   Example 1: Input: n = 39 Output: 3 Explanation: We can do the following operations: - Add 20 = 1 to n, so now n = 40. - Subtract 23 = 8 from n, so now n = 32. - Subtract 25 = 32 from n, so now n = 0. It can be shown that 3 is the minimum number of operations we need to make n equal to 0. Example 2: Input: n = 54 Output: 3 Explanation: We can do the following operations: - Add 21 = 2 to n, so now n = 56. - Add 23 = 8 to n, so now n = 64. - Subtract 26 = 64 from n, so now n = 0. So the minimum number of operations is 3.   Constraints: 1 <= n <= 105
Medium
[ "dynamic-programming", "greedy", "bit-manipulation" ]
[ "function dec2bin(dec) {\n return (dec >>> 0).toString(2);\n}\nfunction bitCnt(s) {\n let res = 0\n for(const e of s) {\n if(e === '1') res++\n }\n return res\n}\nfunction cnt(num) {\n return bitCnt(dec2bin(num))\n}\n\nconst minOperations = function(n) {\n let res = 0\n for(let i = 0; i < 14; i++) {\n if(cnt(n + (1 << i)) < cnt(n)) {\n res++\n n += (1 << i)\n }\n }\n \n return res + cnt(n)\n};", "function dec2bin(dec) {\n return (dec >>> 0).toString(2);\n}\nfunction bitCnt(s) {\n let res = 0\n for(const e of s) {\n if(e === '1') res++\n }\n return res\n}\n\nvar minOperations = function(n) {\n if(n === 0) return 0 \n if(bitCnt(dec2bin(n)) === 1) return 1\n const lowBit = n & -n\n let low = minOperations(n + lowBit);\n let high = minOperations(n - lowBit);\n return Math.min(low, high) + 1;\n};" ]
2,572
count-the-number-of-square-free-subsets
[ "There are 10 primes before number 30.", "Label primes from {2, 3, … 29} with {0,1, … 9} and let DP(i, mask) denote the number of subsets before index: i with the subset of taken primes: mask.", "If the mask and prime factorization of nums[i] have a common prime, then it is impossible to add to the current subset, otherwise, it is possible." ]
/** * @param {number[]} nums * @return {number} */ var squareFreeSubsets = function(nums) { };
You are given a positive integer 0-indexed array nums. A subset of the array nums is square-free if the product of its elements is a square-free integer. A square-free integer is an integer that is divisible by no square number other than 1. Return the number of square-free non-empty subsets of the array nums. Since the answer may be too large, return it modulo 109 + 7. A non-empty subset of nums is an array that can be obtained by deleting some (possibly none but not all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.   Example 1: Input: nums = [3,4,4,5] Output: 3 Explanation: There are 3 square-free subsets in this example: - The subset consisting of the 0th element [3]. The product of its elements is 3, which is a square-free integer. - The subset consisting of the 3rd element [5]. The product of its elements is 5, which is a square-free integer. - The subset consisting of 0th and 3rd elements [3,5]. The product of its elements is 15, which is a square-free integer. It can be proven that there are no more than 3 square-free subsets in the given array. Example 2: Input: nums = [1] Output: 1 Explanation: There is 1 square-free subset in this example: - The subset consisting of the 0th element [1]. The product of its elements is 1, which is a square-free integer. It can be proven that there is no more than 1 square-free subset in the given array.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 30
Medium
[ "array", "math", "dynamic-programming", "bit-manipulation", "bitmask" ]
[ "const divisibilityArray = function(word, m) {\n let ans = [];\n let cur = 0;\n for (let i = 0; i < word.length; i++) {\n cur = (cur * 10 + Number(word[i])) % m;\n ans.push(cur === 0 ? 1 : 0);\n }\n return ans;\n};" ]
2,573
find-the-string-with-lcp
[ "Use the LCP array to determine which groups of elements must be equal.", "Match the smallest letter to the group that contains the smallest unassigned index.", "Build the LCP matrix of the resulting string then check if it is equal to the target LCP." ]
/** * @param {number[][]} lcp * @return {string} */ var findTheString = function(lcp) { };
We define the lcp matrix of any 0-indexed string word of n lowercase English letters as an n x n grid such that: lcp[i][j] is equal to the length of the longest common prefix between the substrings word[i,n-1] and word[j,n-1]. Given an n x n matrix lcp, return the alphabetically smallest string word that corresponds to lcp. If there is no such string, return an empty string. A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, "aabd" is lexicographically smaller than "aaca" because the first position they differ is at the third letter, and 'b' comes before 'c'.   Example 1: Input: lcp = [[4,0,2,0],[0,3,0,1],[2,0,2,0],[0,1,0,1]] Output: "abab" Explanation: lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab". Example 2: Input: lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,1]] Output: "aaaa" Explanation: lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa". Example 3: Input: lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,3]] Output: "" Explanation: lcp[3][3] cannot be equal to 3 since word[3,...,3] consists of only a single letter; Thus, no answer exists.   Constraints: 1 <= n == lcp.length == lcp[i].length <= 1000 0 <= lcp[i][j] <= n
Hard
[ "string", "dynamic-programming", "greedy", "union-find" ]
[ "const findTheString = function (lcp) {\n const n = lcp.length\n let c = 0\n const arr = new Array(n).fill(0)\n for (let i = 0; i < n; ++i) {\n if (arr[i] > 0) continue\n if (++c > 26) return ''\n for (let j = i; j < n; ++j) {\n if (lcp[i][j] > 0) arr[j] = c\n }\n }\n for (let i = 0; i < n; ++i) {\n for (let j = 0; j < n; ++j) {\n let v = i + 1 < n && j + 1 < n ? lcp[i + 1][j + 1] : 0\n v = arr[i] === arr[j] ? v + 1 : 0\n if (lcp[i][j] != v) return ''\n }\n }\n const res = []\n const ac = 'a'.charCodeAt(0)\n for (let a of arr) res.push(String.fromCharCode(ac + a - 1))\n return res.join('')\n}" ]
2,574
left-and-right-sum-differences
[ "For each index i, maintain two variables leftSum and rightSum.", "Iterate on the range j: [0 … i - 1] and add nums[j] to the leftSum and similarly iterate on the range j: [i + 1 … nums.length - 1] and add nums[j] to the rightSum." ]
/** * @param {number[]} nums * @return {number[]} */ var leftRightDifference = function(nums) { };
Given a 0-indexed integer array nums, find a 0-indexed integer array answer where: answer.length == nums.length. answer[i] = |leftSum[i] - rightSum[i]|. Where: leftSum[i] is the sum of elements to the left of the index i in the array nums. If there is no such element, leftSum[i] = 0. rightSum[i] is the sum of elements to the right of the index i in the array nums. If there is no such element, rightSum[i] = 0. Return the array answer.   Example 1: Input: nums = [10,4,8,3] Output: [15,1,11,22] Explanation: The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0]. The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22]. Example 2: Input: nums = [1] Output: [0] Explanation: The array leftSum is [0] and the array rightSum is [0]. The array answer is [|0 - 0|] = [0].   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 105
Easy
[ "array", "prefix-sum" ]
[ "const leftRigthDifference = function(nums) {\n const {abs} = Math\n const n = nums.length\n \n const pre = new Array(n + 2).fill(0)\n const post = new Array(n + 2).fill(0)\n const res = []\n for(let i = 1, cur = 0; i <= n; i++) {\n pre[i] = cur\n cur += nums[i - 1]\n }\n \n for(let i = n, cur = 0; i >= 1; i--) {\n post[i] = cur\n cur += nums[i - 1]\n }\n \n for(let i = 1; i <= n; i++) {\n res[i - 1] = abs(pre[i] - post[i])\n }\n \n return res\n};" ]
2,575
find-the-divisibility-array-of-a-string
[ "We can check if the numeric value of the prefix of the given string is divisible by m by computing the remainder of the numeric value of the prefix when divided by m.", "The remainder of the numeric value of a prefix ending at index i can be computed from the remainder of the prefix ending at index i-1." ]
/** * @param {string} word * @param {number} m * @return {number[]} */ var divisibilityArray = function(word, m) { };
You are given a 0-indexed string word of length n consisting of digits, and a positive integer m. The divisibility array div of word is an integer array of length n such that: div[i] = 1 if the numeric value of word[0,...,i] is divisible by m, or div[i] = 0 otherwise. Return the divisibility array of word.   Example 1: Input: word = "998244353", m = 3 Output: [1,1,0,0,0,1,1,0,0] Explanation: There are only 4 prefixes that are divisible by 3: "9", "99", "998244", and "9982443". Example 2: Input: word = "1010", m = 10 Output: [0,1,0,1] Explanation: There are only 2 prefixes that are divisible by 10: "10", and "1010".   Constraints: 1 <= n <= 105 word.length == n word consists of digits from 0 to 9 1 <= m <= 109
Medium
[ "array", "math", "string" ]
null
[]
2,576
find-the-maximum-number-of-marked-indices
[ "Think about how to check that performing k operations is possible.", "To perform k operations, it’s optimal to use the smallest k elements and the largest k elements and think about how to match them.", "It’s optimal to match the ith smallest number with the k-i + 1 largest number.", "Now we need to binary search on the answer and find the greatest possible valid k." ]
/** * @param {number[]} nums * @return {number} */ var maxNumOfMarkedIndices = function(nums) { };
You are given a 0-indexed integer array nums. Initially, all of the indices are unmarked. You are allowed to make this operation any number of times: Pick two different unmarked indices i and j such that 2 * nums[i] <= nums[j], then mark i and j. Return the maximum possible number of marked indices in nums using the above operation any number of times.   Example 1: Input: nums = [3,5,2,4] Output: 2 Explanation: In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] <= nums[1]. Then mark index 2 and 1. It can be shown that there's no other valid operation so the answer is 2. Example 2: Input: nums = [9,2,5,4] Output: 4 Explanation: In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] <= nums[0]. Then mark index 3 and 0. In the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] <= nums[2]. Then mark index 1 and 2. Since there is no other operation, the answer is 4. Example 3: Input: nums = [7,6,8] Output: 0 Explanation: There is no valid operation to do, so the answer is 0.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109  
Medium
[ "array", "two-pointers", "binary-search", "greedy", "sorting" ]
[ "const maxNumOfMarkedIndices = function(nums) {\n let res = 0\n const n = nums.length\n nums.sort((a, b) => a - b)\n for(let i = 0, j = n - Math.floor(n / 2); j < n; j++) {\n if(nums[i] * 2 <= nums[j]) {\n res += 2\n i++\n }\n }\n \n return res\n};", "const maxNumOfMarkedIndices = function(nums) {\n let i = 0, n = nums.length;\n nums.sort((a, b) => a - b)\n for (let j = n - (~~(n / 2)); j < n; ++j) {\n i += 2 * nums[i] <= nums[j] ? 1 : 0; \n }\n return i * 2;\n};" ]
2,577
minimum-time-to-visit-a-cell-in-a-grid
[ "Try using some algorithm that can find the shortest paths on a graph.", "Consider the case where you have to go back and forth between two cells of the matrix to unlock some other cells." ]
/** * @param {number[][]} grid * @return {number} */ var minimumTime = function(grid) { };
You are given a m x n matrix grid consisting of non-negative integers where grid[row][col] represents the minimum time required to be able to visit the cell (row, col), which means you can visit the cell (row, col) only when the time you visit it is greater than or equal to grid[row][col]. You are standing in the top-left cell of the matrix in the 0th second, and you must move to any adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second. Return the minimum time required in which you can visit the bottom-right cell of the matrix. If you cannot visit the bottom-right cell, then return -1.   Example 1: Input: grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]] Output: 7 Explanation: One of the paths that we can take is the following: - at t = 0, we are on the cell (0,0). - at t = 1, we move to the cell (0,1). It is possible because grid[0][1] <= 1. - at t = 2, we move to the cell (1,1). It is possible because grid[1][1] <= 2. - at t = 3, we move to the cell (1,2). It is possible because grid[1][2] <= 3. - at t = 4, we move to the cell (1,1). It is possible because grid[1][1] <= 4. - at t = 5, we move to the cell (1,2). It is possible because grid[1][2] <= 5. - at t = 6, we move to the cell (1,3). It is possible because grid[1][3] <= 6. - at t = 7, we move to the cell (2,3). It is possible because grid[2][3] <= 7. The final time is 7. It can be shown that it is the minimum time possible. Example 2: Input: grid = [[0,2,4],[3,2,1],[1,0,4]] Output: -1 Explanation: There is no path from the top left to the bottom-right cell.   Constraints: m == grid.length n == grid[i].length 2 <= m, n <= 1000 4 <= m * n <= 105 0 <= grid[i][j] <= 105 grid[0][0] == 0  
Hard
[ "array", "breadth-first-search", "graph", "heap-priority-queue", "matrix", "shortest-path" ]
[ "const minimumTime = function (grid) {\n const directions = [\n [-1, 0],\n [0, 1],\n [1, 0],\n [0, -1],\n ]\n let m = grid.length,\n n = grid[0].length\n if (grid[0][1] > 1 && grid[1][0] > 1) return -1\n let dist = Array(m)\n .fill(0)\n .map(() => Array(n).fill(Infinity))\n let heap = new Heap((a, b) => a[2] - b[2])\n heap.add([0, 0, 0])\n dist[0][0] = 0\n\n while (!heap.isEmpty()) {\n let [row, col, time] = heap.remove()\n if (dist[row][col] < time) continue\n if (row === m - 1 && col === n - 1) return time\n for (let [x, y] of directions) {\n let newRow = row + x,\n newCol = col + y\n if (newRow < 0 || newRow >= m || newCol < 0 || newCol >= n) continue\n let diff = grid[newRow][newCol] - time\n let moves = diff % 2 === 1 ? diff : diff + 1\n let weight = grid[newRow][newCol] <= time + 1 ? 1 : moves\n if (dist[newRow][newCol] > time + weight) {\n dist[newRow][newCol] = Math.min(dist[newRow][newCol], time + weight)\n heap.add([newRow, newCol, time + weight])\n }\n }\n }\n}\n\nclass Heap {\n constructor(comparator = (a, b) => a - b) {\n this.values = []\n this.comparator = comparator\n this.size = 0\n }\n add(val) {\n this.size++\n this.values.push(val)\n let idx = this.size - 1,\n parentIdx = Math.floor((idx - 1) / 2)\n while (\n parentIdx >= 0 &&\n this.comparator(this.values[parentIdx], this.values[idx]) > 0\n ) {\n ;[this.values[parentIdx], this.values[idx]] = [\n this.values[idx],\n this.values[parentIdx],\n ]\n idx = parentIdx\n parentIdx = Math.floor((idx - 1) / 2)\n }\n }\n remove() {\n if (this.size === 0) return -1\n this.size--\n if (this.size === 0) return this.values.pop()\n let removedVal = this.values[0]\n this.values[0] = this.values.pop()\n let idx = 0\n while (idx < this.size && idx < Math.floor(this.size / 2)) {\n let leftIdx = idx * 2 + 1,\n rightIdx = idx * 2 + 2\n if (rightIdx === this.size) {\n if (this.comparator(this.values[leftIdx], this.values[idx]) > 0) break\n ;[this.values[leftIdx], this.values[idx]] = [\n this.values[idx],\n this.values[leftIdx],\n ]\n idx = leftIdx\n } else if (\n this.comparator(this.values[leftIdx], this.values[idx]) < 0 ||\n this.comparator(this.values[rightIdx], this.values[idx]) < 0\n ) {\n if (this.comparator(this.values[leftIdx], this.values[rightIdx]) <= 0) {\n ;[this.values[leftIdx], this.values[idx]] = [\n this.values[idx],\n this.values[leftIdx],\n ]\n idx = leftIdx\n } else {\n ;[this.values[rightIdx], this.values[idx]] = [\n this.values[idx],\n this.values[rightIdx],\n ]\n idx = rightIdx\n }\n } else {\n break\n }\n }\n return removedVal\n }\n top() {\n return this.values[0]\n }\n isEmpty() {\n return this.size === 0\n }\n}" ]
2,578
split-with-minimum-sum
[ "Sort the digits of num in non decreasing order.", "Assign digits to num1 and num2 alternatively." ]
/** * @param {number} num * @return {number} */ var splitNum = function(num) { };
Given a positive integer num, split it into two non-negative integers num1 and num2 such that: The concatenation of num1 and num2 is a permutation of num. In other words, the sum of the number of occurrences of each digit in num1 and num2 is equal to the number of occurrences of that digit in num. num1 and num2 can contain leading zeros. Return the minimum possible sum of num1 and num2. Notes: It is guaranteed that num does not contain any leading zeros. The order of occurrence of the digits in num1 and num2 may differ from the order of occurrence of num.   Example 1: Input: num = 4325 Output: 59 Explanation: We can split 4325 so that num1 is 24 and num2 is 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum. Example 2: Input: num = 687 Output: 75 Explanation: We can split 687 so that num1 is 68 and num2 is 7, which would give an optimal sum of 75.   Constraints: 10 <= num <= 109
Easy
[ "math", "greedy", "sorting" ]
null
[]
2,579
count-total-number-of-colored-cells
[ "Derive a mathematical relation between total number of colored cells and the time elapsed in minutes." ]
/** * @param {number} n * @return {number} */ var coloredCells = function(n) { };
There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer n, indicating that you must do the following routine for n minutes: At the first minute, color any arbitrary unit cell blue. Every minute thereafter, color blue every uncolored cell that touches a blue cell. Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3. Return the number of colored cells at the end of n minutes.   Example 1: Input: n = 1 Output: 1 Explanation: After 1 minute, there is only 1 blue cell, so we return 1. Example 2: Input: n = 2 Output: 5 Explanation: After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5.   Constraints: 1 <= n <= 105
Medium
[ "math" ]
null
[]
2,580
count-ways-to-group-overlapping-ranges
[ "Can we use sorting here?", "Sort the ranges and merge the overlapping ranges. Then count number of non-overlapping ranges.", "How many ways can we group these non-overlapping ranges?" ]
/** * @param {number[][]} ranges * @return {number} */ var countWays = function(ranges) { };
You are given a 2D integer array ranges where ranges[i] = [starti, endi] denotes that all integers between starti and endi (both inclusive) are contained in the ith range. You are to split ranges into two (possibly empty) groups such that: Each range belongs to exactly one group. Any two overlapping ranges must belong to the same group. Two ranges are said to be overlapping if there exists at least one integer that is present in both ranges. For example, [1, 3] and [2, 5] are overlapping because 2 and 3 occur in both ranges. Return the total number of ways to split ranges into two groups. Since the answer may be very large, return it modulo 109 + 7.   Example 1: Input: ranges = [[6,10],[5,15]] Output: 2 Explanation: The two ranges are overlapping, so they must be in the same group. Thus, there are two possible ways: - Put both the ranges together in group 1. - Put both the ranges together in group 2. Example 2: Input: ranges = [[1,3],[10,20],[2,5],[4,8]] Output: 4 Explanation: Ranges [1,3], and [2,5] are overlapping. So, they must be in the same group. Again, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group. Thus, there are four possible ways to group them: - All the ranges in group 1. - All the ranges in group 2. - Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2. - Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1.   Constraints: 1 <= ranges.length <= 105 ranges[i].length == 2 0 <= starti <= endi <= 109
Medium
[ "array", "sorting" ]
null
[]
2,581
count-number-of-possible-root-nodes
[ "How can we check if any node can be the root?", "Can we use this information to check its neighboring nodes?", "When we traverse from current node to a neighboring node, how will we update our answer?" ]
/** * @param {number[][]} edges * @param {number[][]} guesses * @param {number} k * @return {number} */ var rootCount = function(edges, guesses, k) { };
Alice has an undirected tree with n nodes labeled from 0 to n - 1. The tree is represented as a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Alice wants Bob to find the root of the tree. She allows Bob to make several guesses about her tree. In one guess, he does the following: Chooses two distinct integers u and v such that there exists an edge [u, v] in the tree. He tells Alice that u is the parent of v in the tree. Bob's guesses are represented by a 2D integer array guesses where guesses[j] = [uj, vj] indicates Bob guessed uj to be the parent of vj. Alice being lazy, does not reply to each of Bob's guesses, but just says that at least k of his guesses are true. Given the 2D integer arrays edges, guesses and the integer k, return the number of possible nodes that can be the root of Alice's tree. If there is no such tree, return 0.   Example 1: Input: edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3 Output: 3 Explanation: Root = 0, correct guesses = [1,3], [0,1], [2,4] Root = 1, correct guesses = [1,3], [1,0], [2,4] Root = 2, correct guesses = [1,3], [1,0], [2,4] Root = 3, correct guesses = [1,0], [2,4] Root = 4, correct guesses = [1,3], [1,0] Considering 0, 1, or 2 as root node leads to 3 correct guesses. Example 2: Input: edges = [[0,1],[1,2],[2,3],[3,4]], guesses = [[1,0],[3,4],[2,1],[3,2]], k = 1 Output: 5 Explanation: Root = 0, correct guesses = [3,4] Root = 1, correct guesses = [1,0], [3,4] Root = 2, correct guesses = [1,0], [2,1], [3,4] Root = 3, correct guesses = [1,0], [2,1], [3,2], [3,4] Root = 4, correct guesses = [1,0], [2,1], [3,2] Considering any node as root will give at least 1 correct guess.   Constraints: edges.length == n - 1 2 <= n <= 105 1 <= guesses.length <= 105 0 <= ai, bi, uj, vj <= n - 1 ai != bi uj != vj edges represents a valid tree. guesses[j] is an edge of the tree. guesses is unique. 0 <= k <= guesses.length
Hard
[ "hash-table", "dynamic-programming", "tree", "depth-first-search" ]
null
[]
2,582
pass-the-pillow
[ "Maintain two integer variables, direction and i, where direction denotes the current direction in which the pillow should pass, and i denotes an index of the person holding the pillow.", "While time is positive, update the current index with the current direction. If the index reaches the end of the line, multiply direction by - 1." ]
/** * @param {number} n * @param {number} time * @return {number} */ var passThePillow = function(n, time) { };
There are n people standing in a line labeled from 1 to n. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction. For example, once the pillow reaches the nth person they pass it to the n - 1th person, then to the n - 2th person and so on. Given the two positive integers n and time, return the index of the person holding the pillow after time seconds.   Example 1: Input: n = 4, time = 5 Output: 2 Explanation: People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2. Afer five seconds, the pillow is given to the 2nd person. Example 2: Input: n = 3, time = 2 Output: 3 Explanation: People pass the pillow in the following way: 1 -> 2 -> 3. Afer two seconds, the pillow is given to the 3rd person.   Constraints: 2 <= n <= 1000 1 <= time <= 1000
Easy
[ "math", "simulation" ]
[ "const passThePillow = function(n, time) {\n const k = ~~(time / (n - 1))\n const r = time % (n - 1)\n \n return k % 2 === 1 ? n - r : r + 1 \n};" ]
2,583
kth-largest-sum-in-a-binary-tree
[ "Find the sum of values of nodes on each level and return the kth largest one.", "To find the sum of the values of nodes on each level, you can use a DFS or BFS algorithm to traverse the tree and keep track of the level of each node." ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} k * @return {number} */ var kthLargestLevelSum = function(root, k) { };
You are given the root of a binary tree and a positive integer k. The level sum in the tree is the sum of the values of the nodes that are on the same level. Return the kth largest level sum in the tree (not necessarily distinct). If there are fewer than k levels in the tree, return -1. Note that two nodes are on the same level if they have the same distance from the root.   Example 1: Input: root = [5,8,9,2,1,3,7,4,6], k = 2 Output: 13 Explanation: The level sums are the following: - Level 1: 5. - Level 2: 8 + 9 = 17. - Level 3: 2 + 1 + 3 + 7 = 13. - Level 4: 4 + 6 = 10. The 2nd largest level sum is 13. Example 2: Input: root = [1,2,null,3], k = 1 Output: 3 Explanation: The largest level sum is 3.   Constraints: The number of nodes in the tree is n. 2 <= n <= 105 1 <= Node.val <= 106 1 <= k <= n
Medium
[ "binary-search", "tree", "breadth-first-search" ]
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
[ "const kthLargestLevelSum = function(root, k) {\n let row = [root]\n const pq = new PQ((a, b) => a < b)\n while(row.length) {\n let sum = 0\n const nxt = []\n const len = row.length\n for(let i = 0; i < len; i++) {\n const cur = row[i]\n sum += cur.val\n if(cur.left) nxt.push(cur.left)\n if(cur.right) nxt.push(cur.right)\n }\n \n pq.push(sum)\n if(pq.size() > k) pq.pop()\n row = nxt\n }\n \n return pq.size() < k ? -1 : pq.peek()\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}" ]
2,584
split-the-array-to-make-coprime-products
[ "Two numbers with GCD equal to 1 have no common prime divisor.", "Find the prime factorization of the left and right sides and check if they share a prime divisor." ]
/** * @param {number[]} nums * @return {number} */ var findValidSplit = function(nums) { };
You are given a 0-indexed integer array nums of length n. A split at an index i where 0 <= i <= n - 2 is called valid if the product of the first i + 1 elements and the product of the remaining elements are coprime. For example, if nums = [2, 3, 3], then a split at the index i = 0 is valid because 2 and 9 are coprime, while a split at the index i = 1 is not valid because 6 and 3 are not coprime. A split at the index i = 2 is not valid because i == n - 1. Return the smallest index i at which the array can be split validly or -1 if there is no such split. Two values val1 and val2 are coprime if gcd(val1, val2) == 1 where gcd(val1, val2) is the greatest common divisor of val1 and val2.   Example 1: Input: nums = [4,7,8,15,3,5] Output: 2 Explanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i. The only valid split is at index 2. Example 2: Input: nums = [4,7,15,8,3,5] Output: -1 Explanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i. There is no valid split.   Constraints: n == nums.length 1 <= n <= 104 1 <= nums[i] <= 106
Hard
[ "array", "hash-table", "math", "number-theory" ]
[ "const findValidSplit = function(nums) {\n const n = nums.length, right = {};\n for (let i = 0; i < n; i++) {\n const primeFactorsCount = getPrimeFactors(nums[i]);\n for (let prime in primeFactorsCount) {\n const count = primeFactorsCount[prime];\n right[prime] = (right[prime] || 0) + count;\n }\n }\n const left = {}, common = new Set();\n for (let i = 0; i <= n - 2; i++) {\n const primesFactorsCount = getPrimeFactors(nums[i]);\n for (const prime in primesFactorsCount) {\n const count = primesFactorsCount[prime];\n left[prime] = (left[prime] || 0) + count;\n right[prime] -= count;\n if (right[prime] > 0) common.add(prime);\n else if (right[prime] === 0) common.delete(prime);\n }\n if (common.size === 0) return i;\n }\n return -1;\n};\n\nfunction getPrimeFactors(n) {\n const counts = {};\n for (let x = 2; (x * x) <= n; x++) {\n while (n % x === 0) {\n counts[x] = (counts[x] || 0) + 1;\n n /= x;\n }\n }\n if (n > 1) counts[n] = (counts[n] || 0) + 1;\n return counts;\n}", "const findValidSplit = function (nums) {\n const map = new Map()\n const n = nums.length\n const max = Math.max(...nums)\n const primes = Eratosthenes(max)\n\n for (let i = 0; i < n; i++) {\n let x = nums[i]\n for (const p of primes) {\n if (p * p > x && x > 1) {\n if (!map.has(x)) {\n map.set(x, [i, i])\n }\n map.get(x)[1] = i\n break\n }\n\n if (x % p === 0) {\n if (!map.has(p)) {\n map.set(p, [i, i])\n }\n const a = map.get(p)\n a[1] = i\n }\n while (x % p === 0) x = x / p\n }\n }\n\n const diff = Array(n + 1).fill(0)\n for (const [k, v] of map) {\n const [s, e] = v\n // if(s === e) continue\n diff[s] += 1\n diff[e] -= 1\n }\n // console.log(diff)\n let sum = 0\n for (let i = 0; i < n - 1; i++) {\n sum += diff[i]\n if (sum === 0) return i\n }\n\n return -1\n}\n\nfunction Eratosthenes(n) {\n const q = Array(n + 1).fill(0)\n const primes = []\n for (let i = 2; i <= Math.sqrt(n); i++) {\n if (q[i] == 1) continue\n let j = i * 2\n while (j <= n) {\n q[j] = 1\n j += i\n }\n }\n for (let i = 2; i <= n; i++) {\n if (q[i] == 0) primes.push(i)\n }\n return primes\n}" ]
2,585
number-of-ways-to-earn-points
[ "Use Dynamic Programming", "Let ways[i][points] be the number of ways to score a given number of points after solving some questions of the first i types.", "ways[i][points] is equal to the sum of ways[i-1][points - solved * marks[i] over 0 <= solved <= count_i" ]
/** * @param {number} target * @param {number[][]} types * @return {number} */ var waysToReachTarget = function(target, types) { };
There is a test that has n types of questions. You are given an integer target and a 0-indexed 2D integer array types where types[i] = [counti, marksi] indicates that there are counti questions of the ith type, and each one of them is worth marksi points. Return the number of ways you can earn exactly target points in the exam. Since the answer may be too large, return it modulo 109 + 7. Note that questions of the same type are indistinguishable. For example, if there are 3 questions of the same type, then solving the 1st and 2nd questions is the same as solving the 1st and 3rd questions, or the 2nd and 3rd questions.   Example 1: Input: target = 6, types = [[6,1],[3,2],[2,3]] Output: 7 Explanation: You can earn 6 points in one of the seven ways: - Solve 6 questions of the 0th type: 1 + 1 + 1 + 1 + 1 + 1 = 6 - Solve 4 questions of the 0th type and 1 question of the 1st type: 1 + 1 + 1 + 1 + 2 = 6 - Solve 2 questions of the 0th type and 2 questions of the 1st type: 1 + 1 + 2 + 2 = 6 - Solve 3 questions of the 0th type and 1 question of the 2nd type: 1 + 1 + 1 + 3 = 6 - Solve 1 question of the 0th type, 1 question of the 1st type and 1 question of the 2nd type: 1 + 2 + 3 = 6 - Solve 3 questions of the 1st type: 2 + 2 + 2 = 6 - Solve 2 questions of the 2nd type: 3 + 3 = 6 Example 2: Input: target = 5, types = [[50,1],[50,2],[50,5]] Output: 4 Explanation: You can earn 5 points in one of the four ways: - Solve 5 questions of the 0th type: 1 + 1 + 1 + 1 + 1 = 5 - Solve 3 questions of the 0th type and 1 question of the 1st type: 1 + 1 + 1 + 2 = 5 - Solve 1 questions of the 0th type and 2 questions of the 1st type: 1 + 2 + 2 = 5 - Solve 1 question of the 2nd type: 5 Example 3: Input: target = 18, types = [[6,1],[3,2],[2,3]] Output: 1 Explanation: You can only earn 18 points by answering all questions.   Constraints: 1 <= target <= 1000 n == types.length 1 <= n <= 50 types[i].length == 2 1 <= counti, marksi <= 50
Hard
[ "array", "dynamic-programming" ]
[ "const waysToReachTarget = function(target, types) {\n const n = types.length\n const dp = Array.from({ length: n + 1 }, () => Array(target + 1).fill(0))\n const mod = 1e9 + 7\n let res = 0\n dp[0][0] = 1\n for(let i = 1; i <= n; i++) {\n const [cnt, mark] = types[i - 1]\n for(let j = 0, tmp = 0; j <= cnt; j++) {\n const tmp = mark * j\n for(let k = tmp; k <= target; k++) {\n dp[i][k] = (dp[i][k] + dp[i - 1][k - tmp]) % mod \n }\n }\n }\n \n return dp[n][target] % mod\n};" ]
2,586
count-the-number-of-vowel-strings-in-range
[ "consider iterating over all strings from left to right and use an if condition to check if the first character and last character are vowels." ]
/** * @param {string[]} words * @param {number} left * @param {number} right * @return {number} */ var vowelStrings = function(words, left, right) { };
You are given a 0-indexed array of string words and two integers left and right. A string is called a vowel string if it starts with a vowel character and ends with a vowel character where vowel characters are 'a', 'e', 'i', 'o', and 'u'. Return the number of vowel strings words[i] where i belongs to the inclusive range [left, right].   Example 1: Input: words = ["are","amy","u"], left = 0, right = 2 Output: 2 Explanation: - "are" is a vowel string because it starts with 'a' and ends with 'e'. - "amy" is not a vowel string because it does not end with a vowel. - "u" is a vowel string because it starts with 'u' and ends with 'u'. The number of vowel strings in the mentioned range is 2. Example 2: Input: words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4 Output: 3 Explanation: - "aeo" is a vowel string because it starts with 'a' and ends with 'o'. - "mu" is not a vowel string because it does not start with a vowel. - "ooo" is a vowel string because it starts with 'o' and ends with 'o'. - "artro" is a vowel string because it starts with 'a' and ends with 'o'. The number of vowel strings in the mentioned range is 3.   Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 10 words[i] consists of only lowercase English letters. 0 <= left <= right < words.length
Easy
[ "array", "string" ]
null
[]