Datasets:

QID
int64
1
2.85k
titleSlug
stringlengths
3
77
Hints
list
Code
stringlengths
80
1.34k
Body
stringlengths
190
4.55k
Difficulty
stringclasses
3 values
Topics
list
Definitions
stringclasses
14 values
Solutions
list
2,587
rearrange-array-to-maximize-prefix-score
[ "The best order of the array is in decreasing order.", "Sort the array in decreasing order and count the number of positive values in the prefix sum array." ]
/** * @param {number[]} nums * @return {number} */ var maxScore = function(nums) { };
You are given a 0-indexed integer array nums. You can rearrange the elements of nums to any order (including the given order). Let prefix be the array containing the prefix sums of nums after rearranging it. In other words, prefix[i] is the sum of the elements from 0 to i in nums after rearranging it. The score of nums is the number of positive integers in the array prefix. Return the maximum score you can achieve.   Example 1: Input: nums = [2,-1,0,1,-3,3,-3] Output: 6 Explanation: We can rearrange the array into nums = [2,3,1,-1,-3,0,-3]. prefix = [2,5,6,5,2,2,-1], so the score is 6. It can be shown that 6 is the maximum score we can obtain. Example 2: Input: nums = [-2,-3,0] Output: 0 Explanation: Any rearrangement of the array will result in a score of 0.   Constraints: 1 <= nums.length <= 105 -106 <= nums[i] <= 106
Medium
[ "array", "greedy", "sorting", "prefix-sum" ]
null
[]
2,588
count-the-number-of-beautiful-subarrays
[ "A subarray is beautiful if its xor is equal to zero.", "Compute the prefix xor for every index, then the xor of subarray [left, right] is equal to zero if prefix_xor[left] ^ perfix_xor[right] == 0", "Iterate from left to right and maintain a hash table to count the number of indices equal to the current prefix xor." ]
/** * @param {number[]} nums * @return {number} */ var beautifulSubarrays = function(nums) { };
You are given a 0-indexed integer array nums. In one operation, you can: Choose two different indices i and j such that 0 <= i, j < nums.length. Choose a non-negative integer k such that the kth bit (0-indexed) in the binary representation of nums[i] and nums[j] is 1. Subtract 2k from nums[i] and nums[j]. A subarray is beautiful if it is possible to make all of its elements equal to 0 after applying the above operation any number of times. Return the number of beautiful subarrays in the array nums. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [4,3,1,2,4] Output: 2 Explanation: There are 2 beautiful subarrays in nums: [4,3,1,2,4] and [4,3,1,2,4]. - We can make all elements in the subarray [3,1,2] equal to 0 in the following way: - Choose [3, 1, 2] and k = 1. Subtract 21 from both numbers. The subarray becomes [1, 1, 0]. - Choose [1, 1, 0] and k = 0. Subtract 20 from both numbers. The subarray becomes [0, 0, 0]. - We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way: - Choose [4, 3, 1, 2, 4] and k = 2. Subtract 22 from both numbers. The subarray becomes [0, 3, 1, 2, 0]. - Choose [0, 3, 1, 2, 0] and k = 0. Subtract 20 from both numbers. The subarray becomes [0, 2, 0, 2, 0]. - Choose [0, 2, 0, 2, 0] and k = 1. Subtract 21 from both numbers. The subarray becomes [0, 0, 0, 0, 0]. Example 2: Input: nums = [1,10,4] Output: 0 Explanation: There are no beautiful subarrays in nums.   Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 106
Medium
[ "array", "hash-table", "bit-manipulation", "prefix-sum" ]
null
[]
2,589
minimum-time-to-complete-all-tasks
[ "Sort the tasks in ascending order of end time", "Since there are only up to 2000 time points to consider, you can check them one by one", "It is always beneficial to run the task as late as possible so that later tasks can run simultaneously." ]
/** * @param {number[][]} tasks * @return {number} */ var findMinimumTime = function(tasks) { };
There is a computer that can run an unlimited number of tasks at the same time. You are given a 2D integer array tasks where tasks[i] = [starti, endi, durationi] indicates that the ith task should run for a total of durationi seconds (not necessarily continuous) within the inclusive time range [starti, endi]. You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle. Return the minimum time during which the computer should be turned on to complete all tasks.   Example 1: Input: tasks = [[2,3,1],[4,5,1],[1,5,2]] Output: 2 Explanation: - The first task can be run in the inclusive time range [2, 2]. - The second task can be run in the inclusive time range [5, 5]. - The third task can be run in the two inclusive time ranges [2, 2] and [5, 5]. The computer will be on for a total of 2 seconds. Example 2: Input: tasks = [[1,3,2],[2,5,3],[5,6,2]] Output: 4 Explanation: - The first task can be run in the inclusive time range [2, 3]. - The second task can be run in the inclusive time ranges [2, 3] and [5, 5]. - The third task can be run in the two inclusive time range [5, 6]. The computer will be on for a total of 4 seconds.   Constraints: 1 <= tasks.length <= 2000 tasks[i].length == 3 1 <= starti, endi <= 2000 1 <= durationi <= endi - starti + 1
Hard
[ "array", "binary-search", "stack", "greedy", "sorting" ]
null
[]
2,591
distribute-money-to-maximum-children
[ "Can we distribute the money according to the rules if we give 'k' children exactly 8 dollars?", "Brute force to find the largest possible value of k, or return -1 if there doesn’t exist any such k." ]
/** * @param {number} money * @param {number} children * @return {number} */ var distMoney = function(money, children) { };
You are given an integer money denoting the amount of money (in dollars) that you have and another integer children denoting the number of children that you must distribute the money to. You have to distribute the money according to the following rules: All money must be distributed. Everyone must receive at least 1 dollar. Nobody receives 4 dollars. Return the maximum number of children who may receive exactly 8 dollars if you distribute the money according to the aforementioned rules. If there is no way to distribute the money, return -1.   Example 1: Input: money = 20, children = 3 Output: 1 Explanation: The maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is: - 8 dollars to the first child. - 9 dollars to the second child. - 3 dollars to the third child. It can be proven that no distribution exists such that number of children getting 8 dollars is greater than 1. Example 2: Input: money = 16, children = 2 Output: 2 Explanation: Each child can be given 8 dollars.   Constraints: 1 <= money <= 200 2 <= children <= 30
Easy
[ "math", "greedy" ]
null
[]
2,592
maximize-greatness-of-an-array
[ "Can we use sorting and two pointers here?", "Assign every element the next bigger unused element as many times as possible." ]
/** * @param {number[]} nums * @return {number} */ var maximizeGreatness = function(nums) { };
You are given a 0-indexed integer array nums. You are allowed to permute nums into a new array perm of your choosing. We define the greatness of nums be the number of indices 0 <= i < nums.length for which perm[i] > nums[i]. Return the maximum possible greatness you can achieve after permuting nums.   Example 1: Input: nums = [1,3,5,2,1,3,1] Output: 4 Explanation: One of the optimal rearrangements is perm = [2,5,1,3,3,1,1]. At indices = 0, 1, 3, and 4, perm[i] > nums[i]. Hence, we return 4. Example 2: Input: nums = [1,2,3,4] Output: 3 Explanation: We can prove the optimal perm is [2,3,4,1]. At indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3.   Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109
Medium
[ "array", "two-pointers", "greedy", "sorting" ]
null
[]
2,593
find-score-of-an-array-after-marking-all-elements
[ "Try simulating the process of marking the elements and their adjacent.", "If there is an element that was already marked, then you skip it." ]
/** * @param {number[]} nums * @return {number} */ var findScore = function(nums) { };
You are given an array nums consisting of positive integers. Starting with score = 0, apply the following algorithm: Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index. Add the value of the chosen integer to score. Mark the chosen element and its two adjacent elements if they exist. Repeat until all the array elements are marked. Return the score you get after applying the above algorithm.   Example 1: Input: nums = [2,1,3,4,5,2] Output: 7 Explanation: We mark the elements as follows: - 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,1,3,4,5,2]. - 2 is the smallest unmarked element, so we mark it and its left adjacent element: [2,1,3,4,5,2]. - 4 is the only remaining unmarked element, so we mark it: [2,1,3,4,5,2]. Our score is 1 + 2 + 4 = 7. Example 2: Input: nums = [2,3,5,1,3,2] Output: 5 Explanation: We mark the elements as follows: - 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,3,5,1,3,2]. - 2 is the smallest unmarked element, since there are two of them, we choose the left-most one, so we mark the one at index 0 and its right adjacent element: [2,3,5,1,3,2]. - 2 is the only remaining unmarked element, so we mark it: [2,3,5,1,3,2]. Our score is 1 + 2 + 2 = 5.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 106
Medium
[ "array", "sorting", "heap-priority-queue", "simulation" ]
null
[]
2,594
minimum-time-to-repair-cars
[ "For a predefined fixed time, can all the cars be repaired?", "Try using binary search on the answer." ]
/** * @param {number[]} ranks * @param {number} cars * @return {number} */ var repairCars = function(ranks, cars) { };
You are given an integer array ranks representing the ranks of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank r can repair n cars in r * n2 minutes. You are also given an integer cars representing the total number of cars waiting in the garage to be repaired. Return the minimum time taken to repair all the cars. Note: All the mechanics can repair the cars simultaneously.   Example 1: Input: ranks = [4,2,3,1], cars = 10 Output: 16 Explanation: - The first mechanic will repair two cars. The time required is 4 * 2 * 2 = 16 minutes. - The second mechanic will repair two cars. The time required is 2 * 2 * 2 = 8 minutes. - The third mechanic will repair two cars. The time required is 3 * 2 * 2 = 12 minutes. - The fourth mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes. It can be proved that the cars cannot be repaired in less than 16 minutes.​​​​​ Example 2: Input: ranks = [5,1,8], cars = 6 Output: 16 Explanation: - The first mechanic will repair one car. The time required is 5 * 1 * 1 = 5 minutes. - The second mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes. - The third mechanic will repair one car. The time required is 8 * 1 * 1 = 8 minutes. It can be proved that the cars cannot be repaired in less than 16 minutes.​​​​​   Constraints: 1 <= ranks.length <= 105 1 <= ranks[i] <= 100 1 <= cars <= 106
Medium
[ "array", "binary-search" ]
null
[]
2,595
number-of-even-and-odd-bits
[ "Maintain two integer variables, even and odd, to count the number of even and odd indices in the binary representation of integer n.", "Divide n by 2 while n is positive, and if n modulo 2 is 1, add 1 to its corresponding variable." ]
/** * @param {number} n * @return {number[]} */ var evenOddBit = function(n) { };
You are given a positive integer n. Let even denote the number of even indices in the binary representation of n (0-indexed) with value 1. Let odd denote the number of odd indices in the binary representation of n (0-indexed) with value 1. Return an integer array answer where answer = [even, odd].   Example 1: Input: n = 17 Output: [2,0] Explanation: The binary representation of 17 is 10001. It contains 1 on the 0th and 4th indices. There are 2 even and 0 odd indices. Example 2: Input: n = 2 Output: [0,1] Explanation: The binary representation of 2 is 10. It contains 1 on the 1st index. There are 0 even and 1 odd indices.   Constraints: 1 <= n <= 1000
Easy
[ "bit-manipulation" ]
null
[]
2,596
check-knight-tour-configuration
[ "It is enough to check if each move of the knight is valid.", "Try all cases of the knight's movements to check if a move is valid." ]
/** * @param {number[][]} grid * @return {boolean} */ var checkValidGrid = function(grid) { };
There is a knight on an n x n chessboard. In a valid configuration, the knight starts at the top-left cell of the board and visits every cell on the board exactly once. You are given an n x n integer matrix grid consisting of distinct integers from the range [0, n * n - 1] where grid[row][col] indicates that the cell (row, col) is the grid[row][col]th cell that the knight visited. The moves are 0-indexed. Return true if grid represents a valid configuration of the knight's movements or false otherwise. Note that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell.   Example 1: Input: grid = [[0,11,16,5,20],[17,4,19,10,15],[12,1,8,21,6],[3,18,23,14,9],[24,13,2,7,22]] Output: true Explanation: The above diagram represents the grid. It can be shown that it is a valid configuration. Example 2: Input: grid = [[0,3,6],[5,8,1],[2,7,4]] Output: false Explanation: The above diagram represents the grid. The 8th move of the knight is not valid considering its position after the 7th move.   Constraints: n == grid.length == grid[i].length 3 <= n <= 7 0 <= grid[row][col] < n * n All integers in grid are unique.
Medium
[ "array", "depth-first-search", "breadth-first-search", "matrix", "simulation" ]
null
[]
2,597
the-number-of-beautiful-subsets
[ "Sort the array nums and create another array cnt of size nums[i].", "Use backtracking to generate all the beautiful subsets. If cnt[nums[i] - k] is positive, then it is impossible to add nums[i] in the subset, and we just move to the next index. Otherwise, it is also possible to add nums[i] in the subset, in this case, increase cnt[nums[i]], and move to the next index.", "Bonus: Can you solve the problem in O(n log n)?" ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var beautifulSubsets = function(nums, k) { };
You are given an array nums of positive integers and a positive integer k. A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k. Return the number of non-empty beautiful subsets of the array nums. A subset of nums is an array that can be obtained by deleting some (possibly none) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.   Example 1: Input: nums = [2,4,6], k = 2 Output: 4 Explanation: The beautiful subsets of the array nums are: [2], [4], [6], [2, 6]. It can be proved that there are only 4 beautiful subsets in the array [2,4,6]. Example 2: Input: nums = [1], k = 1 Output: 1 Explanation: The beautiful subset of the array nums is [1]. It can be proved that there is only 1 beautiful subset in the array [1].   Constraints: 1 <= nums.length <= 20 1 <= nums[i], k <= 1000
Medium
[ "array", "dynamic-programming", "backtracking" ]
null
[]
2,598
smallest-missing-non-negative-integer-after-operations
[ "Think about using modular arithmetic.", "if x = nums[i] (mod value), then we can make nums[i] equal to x after some number of operations", "How does finding the frequency of (nums[i] mod value) help?" ]
/** * @param {number[]} nums * @param {number} value * @return {number} */ var findSmallestInteger = function(nums, value) { };
You are given a 0-indexed integer array nums and an integer value. In one operation, you can add or subtract value from any element of nums. For example, if nums = [1,2,3] and value = 2, you can choose to subtract value from nums[0] to make nums = [-1,2,3]. The MEX (minimum excluded) of an array is the smallest missing non-negative integer in it. For example, the MEX of [-1,2,3] is 0 while the MEX of [1,0,3] is 2. Return the maximum MEX of nums after applying the mentioned operation any number of times.   Example 1: Input: nums = [1,-10,7,13,6,8], value = 5 Output: 4 Explanation: One can achieve this result by applying the following operations: - Add value to nums[1] twice to make nums = [1,0,7,13,6,8] - Subtract value from nums[2] once to make nums = [1,0,2,13,6,8] - Subtract value from nums[3] twice to make nums = [1,0,2,3,6,8] The MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve. Example 2: Input: nums = [1,-10,7,13,6,8], value = 7 Output: 2 Explanation: One can achieve this result by applying the following operation: - subtract value from nums[2] once to make nums = [1,-10,0,13,6,8] The MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve.   Constraints: 1 <= nums.length, value <= 105 -109 <= nums[i] <= 109
Medium
[ "array", "hash-table", "math", "greedy" ]
null
[]
2,600
k-items-with-the-maximum-sum
[ "It is always optimal to take items with the number 1 written on them as much as possible.", "If k > numOnes, after taking all items with the number 1, it is always optimal to take items with the number 0 written on them as much as possible.", "If k > numOnes + numZeroes we are forced to take k - numOnes - numZeroes -1s." ]
/** * @param {number} numOnes * @param {number} numZeros * @param {number} numNegOnes * @param {number} k * @return {number} */ var kItemsWithMaximumSum = function(numOnes, numZeros, numNegOnes, k) { };
There is a bag that consists of items, each item has a number 1, 0, or -1 written on it. You are given four non-negative integers numOnes, numZeros, numNegOnes, and k. The bag initially contains: numOnes items with 1s written on them. numZeroes items with 0s written on them. numNegOnes items with -1s written on them. We want to pick exactly k items among the available items. Return the maximum possible sum of numbers written on the items.   Example 1: Input: numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2 Output: 2 Explanation: We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2. It can be proven that 2 is the maximum possible sum. Example 2: Input: numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4 Output: 3 Explanation: We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3. It can be proven that 3 is the maximum possible sum.   Constraints: 0 <= numOnes, numZeros, numNegOnes <= 50 0 <= k <= numOnes + numZeros + numNegOnes
Easy
[ "math", "greedy" ]
null
[]
2,601
prime-subtraction-operation
[ "Think about if we have many primes to subtract from nums[i]. Which prime is more optimal?", "The most optimal prime to subtract from nums[i] is the one that makes nums[i] the smallest as possible and greater than nums[i-1]." ]
/** * @param {number[]} nums * @return {boolean} */ var primeSubOperation = function(nums) { };
You are given a 0-indexed integer array nums of length n. You can perform the following operation as many times as you want: Pick an index i that you haven’t picked before, and pick a prime p strictly less than nums[i], then subtract p from nums[i]. Return true if you can make nums a strictly increasing array using the above operation and false otherwise. A strictly increasing array is an array whose each element is strictly greater than its preceding element.   Example 1: Input: nums = [4,9,6,10] Output: true Explanation: In the first operation: Pick i = 0 and p = 3, and then subtract 3 from nums[0], so that nums becomes [1,9,6,10]. In the second operation: i = 1, p = 7, subtract 7 from nums[1], so nums becomes equal to [1,2,6,10]. After the second operation, nums is sorted in strictly increasing order, so the answer is true. Example 2: Input: nums = [6,8,11,12] Output: true Explanation: Initially nums is sorted in strictly increasing order, so we don't need to make any operations. Example 3: Input: nums = [5,8,3] Output: false Explanation: It can be proven that there is no way to perform operations to make nums sorted in strictly increasing order, so the answer is false.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 1000 nums.length == n
Medium
[ "array", "math", "binary-search", "greedy", "number-theory" ]
null
[]
2,602
minimum-operations-to-make-all-array-elements-equal
[ "For each query, you should decrease all elements greater than queries[i] and increase all elements less than queries[i].", "The answer is the sum of absolute differences between queries[i] and every element of the array. How do you calculate that optimally?" ]
/** * @param {number[]} nums * @param {number[]} queries * @return {number[]} */ var minOperations = function(nums, queries) { };
You are given an array nums consisting of positive integers. You are also given an integer array queries of size m. For the ith query, you want to make all of the elements of nums equal to queries[i]. You can perform the following operation on the array any number of times: Increase or decrease an element of the array by 1. Return an array answer of size m where answer[i] is the minimum number of operations to make all elements of nums equal to queries[i]. Note that after each query the array is reset to its original state.   Example 1: Input: nums = [3,1,6,8], queries = [1,5] Output: [14,10] Explanation: For the first query we can do the following operations: - Decrease nums[0] 2 times, so that nums = [1,1,6,8]. - Decrease nums[2] 5 times, so that nums = [1,1,1,8]. - Decrease nums[3] 7 times, so that nums = [1,1,1,1]. So the total number of operations for the first query is 2 + 5 + 7 = 14. For the second query we can do the following operations: - Increase nums[0] 2 times, so that nums = [5,1,6,8]. - Increase nums[1] 4 times, so that nums = [5,5,6,8]. - Decrease nums[2] 1 time, so that nums = [5,5,5,8]. - Decrease nums[3] 3 times, so that nums = [5,5,5,5]. So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10. Example 2: Input: nums = [2,9,6,3], queries = [10] Output: [20] Explanation: We can increase each value in the array to 10. The total number of operations will be 8 + 1 + 4 + 7 = 20.   Constraints: n == nums.length m == queries.length 1 <= n, m <= 105 1 <= nums[i], queries[i] <= 109
Medium
[ "array", "binary-search", "sorting", "prefix-sum" ]
null
[]
2,603
collect-coins-in-a-tree
[ "All leaves that do not have a coin are redundant and can be deleted from the tree.", "Remove the leaves that do not have coins on them, so that the resulting tree will have a coin on every leaf.", "In the remaining tree, remove each leaf node and its parent from the tree. The remaining nodes in the tree are the ones that must be visited. Hence, the answer is equal to (# remaining nodes -1) * 2" ]
/** * @param {number[]} coins * @param {number[][]} edges * @return {number} */ var collectTheCoins = function(coins, edges) { };
There exists an undirected and unrooted tree with n nodes indexed from 0 to n - 1. You are given an 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. You are also given an array coins of size n where coins[i] can be either 0 or 1, where 1 indicates the presence of a coin in the vertex i. Initially, you choose to start at any vertex in the tree. Then, you can perform the following operations any number of times:  Collect all the coins that are at a distance of at most 2 from the current vertex, or Move to any adjacent vertex in the tree. Find the minimum number of edges you need to go through to collect all the coins and go back to the initial vertex. Note that if you pass an edge several times, you need to count it into the answer several times.   Example 1: Input: coins = [1,0,0,0,0,1], edges = [[0,1],[1,2],[2,3],[3,4],[4,5]] Output: 2 Explanation: Start at vertex 2, collect the coin at vertex 0, move to vertex 3, collect the coin at vertex 5 then move back to vertex 2. Example 2: Input: coins = [0,0,0,1,1,0,0,1], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[5,6],[5,7]] Output: 2 Explanation: Start at vertex 0, collect the coins at vertices 4 and 3, move to vertex 2, collect the coin at vertex 7, then move back to vertex 0.   Constraints: n == coins.length 1 <= n <= 3 * 104 0 <= coins[i] <= 1 edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi edges represents a valid tree.
Hard
[ "array", "tree", "graph", "topological-sort" ]
null
[]
2,605
form-smallest-number-from-two-digit-arrays
[ "How many digits will the resulting number have at most?", "The resulting number will have either one or two digits. Try to find when each case is possible." ]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var minNumber = function(nums1, nums2) { };
Given two arrays of unique digits nums1 and nums2, return the smallest number that contains at least one digit from each array.   Example 1: Input: nums1 = [4,1,3], nums2 = [5,7] Output: 15 Explanation: The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have. Example 2: Input: nums1 = [3,5,2,6], nums2 = [3,1,7] Output: 3 Explanation: The number 3 contains the digit 3 which exists in both arrays.   Constraints: 1 <= nums1.length, nums2.length <= 9 1 <= nums1[i], nums2[i] <= 9 All digits in each array are unique.
Easy
[ "array", "hash-table", "enumeration" ]
null
[]
2,606
find-the-substring-with-maximum-cost
[ "Create a new integer array where arr[i] denotes the value of character s[i].", "We can use Kadane’s maximum subarray sum algorithm to find the maximum cost." ]
/** * @param {string} s * @param {string} chars * @param {number[]} vals * @return {number} */ var maximumCostSubstring = function(s, chars, vals) { };
You are given a string s, a string chars of distinct characters and an integer array vals of the same length as chars. The cost of the substring is the sum of the values of each character in the substring. The cost of an empty string is considered 0. The value of the character is defined in the following way: If the character is not in the string chars, then its value is its corresponding position (1-indexed) in the alphabet. For example, the value of 'a' is 1, the value of 'b' is 2, and so on. The value of 'z' is 26. Otherwise, assuming i is the index where the character occurs in the string chars, then its value is vals[i]. Return the maximum cost among all substrings of the string s.   Example 1: Input: s = "adaa", chars = "d", vals = [-1000] Output: 2 Explanation: The value of the characters "a" and "d" is 1 and -1000 respectively. The substring with the maximum cost is "aa" and its cost is 1 + 1 = 2. It can be proven that 2 is the maximum cost. Example 2: Input: s = "abc", chars = "abc", vals = [-1,-1,-1] Output: 0 Explanation: The value of the characters "a", "b" and "c" is -1, -1, and -1 respectively. The substring with the maximum cost is the empty substring "" and its cost is 0. It can be proven that 0 is the maximum cost.   Constraints: 1 <= s.length <= 105 s consist of lowercase English letters. 1 <= chars.length <= 26 chars consist of distinct lowercase English letters. vals.length == chars.length -1000 <= vals[i] <= 1000
Medium
[ "array", "hash-table", "string", "dynamic-programming" ]
null
[]
2,607
make-k-subarray-sums-equal
[ "Think about gcd(n, k). How will it help to calculate the answer?", "indices i and j are in the same group if gcd(n, k) mod i = gcd(n, k) mod j. Each group should have equal elements. Think about the minimum number of operations for each group", "The minimum number of operations for each group equals the summation of differences between the elements and the median of elements inside the group." ]
/** * @param {number[]} arr * @param {number} k * @return {number} */ var makeSubKSumEqual = function(arr, k) { };
You are given a 0-indexed integer array arr and an integer k. The array arr is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element. You can do the following operation any number of times: Pick any element from arr and increase or decrease it by 1. Return the minimum number of operations such that the sum of each subarray of length k is equal. A subarray is a contiguous part of the array.   Example 1: Input: arr = [1,4,1,3], k = 2 Output: 1 Explanation: we can do one operation on index 1 to make its value equal to 3. The array after the operation is [1,3,1,3] - Subarray starts at index 0 is [1, 3], and its sum is 4 - Subarray starts at index 1 is [3, 1], and its sum is 4 - Subarray starts at index 2 is [1, 3], and its sum is 4 - Subarray starts at index 3 is [3, 1], and its sum is 4 Example 2: Input: arr = [2,5,5,7], k = 3 Output: 5 Explanation: we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5. The array after the operations is [5,5,5,5] - Subarray starts at index 0 is [5, 5, 5], and its sum is 15 - Subarray starts at index 1 is [5, 5, 5], and its sum is 15 - Subarray starts at index 2 is [5, 5, 5], and its sum is 15 - Subarray starts at index 3 is [5, 5, 5], and its sum is 15   Constraints: 1 <= k <= arr.length <= 105 1 <= arr[i] <= 109
Medium
[ "array", "math", "sorting", "number-theory" ]
null
[]
2,608
shortest-cycle-in-a-graph
[ "How can BFS be used?", "For each vertex u, calculate the length of the shortest cycle that contains vertex u using BFS" ]
/** * @param {number} n * @param {number[][]} edges * @return {number} */ var findShortestCycle = function(n, edges) { };
There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1. The edges in the graph are represented by a given 2D integer array edges, where edges[i] = [ui, vi] denotes an edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. Return the length of the shortest cycle in the graph. If no cycle exists, return -1. A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.   Example 1: Input: n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]] Output: 3 Explanation: The cycle with the smallest length is : 0 -> 1 -> 2 -> 0 Example 2: Input: n = 4, edges = [[0,1],[0,2]] Output: -1 Explanation: There are no cycles in this graph.   Constraints: 2 <= n <= 1000 1 <= edges.length <= 1000 edges[i].length == 2 0 <= ui, vi < n ui != vi There are no repeated edges.
Hard
[ "breadth-first-search", "graph" ]
[ "const findShortestCycle = function(n, edges) {\n let res = Infinity\n const graph = new Map()\n for(const [u, v] of edges) {\n if(graph.get(u) == null) graph.set(u, [])\n if(graph.get(v) == null) graph.set(v, [])\n graph.get(u).push(v)\n graph.get(v).push(u)\n }\n for(let i = 0; i < n; i++) {\n bfs(i)\n }\n \n if(res === Infinity) return -1\n return res\n \n function bfs(src) {\n const parent = Array(n), dis = Array(n).fill(Infinity)\n let q = []\n dis[src] = 0\n q.push(src)\n while(q.length) {\n const node = q.shift()\n for(const nxt of (graph.get(node) || [])) {\n if(dis[nxt] === Infinity) {\n dis[nxt] = dis[node] + 1\n parent[nxt] = node\n q.push(nxt)\n } else if(parent[node] !== nxt && parent[nxt] !== node) {\n res = Math.min(res, dis[nxt] + dis[node] + 1) \n }\n }\n }\n }\n};" ]
2,609
find-the-longest-balanced-substring-of-a-binary-string
[ "Consider iterating over each subarray and checking if it’s balanced or not.", "Among all balanced subarrays, the answer is the longest one of them." ]
/** * @param {string} s * @return {number} */ var findTheLongestBalancedSubstring = function(s) { };
You are given a binary string s consisting only of zeroes and ones. A substring of s is considered balanced if all zeroes are before ones and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return the length of the longest balanced substring of s. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "01000111" Output: 6 Explanation: The longest balanced substring is "000111", which has length 6. Example 2: Input: s = "00111" Output: 4 Explanation: The longest balanced substring is "0011", which has length 4.  Example 3: Input: s = "111" Output: 0 Explanation: There is no balanced substring except the empty substring, so the answer is 0.   Constraints: 1 <= s.length <= 50 '0' <= s[i] <= '1'
Easy
[ "string" ]
[ "const findTheLongestBalancedSubstring = function(s) {\n let res = 0\n \n const n = s.length\n for(let i = 0; i < n - 1; i++) {\n for(let j = i + 1; j < n; j++) {\n const str = s.slice(i, j + 1)\n if(valid(str)) {\n res = Math.max(res, str.length)\n }\n }\n }\n \n return res\n \n function valid(str) {\n let res = true\n const len = str.length\n if(len % 2 === 1) return false\n const lastZeroIdx = str.lastIndexOf('0')\n const firstOneIdx = str.indexOf('1')\n \n return firstOneIdx - lastZeroIdx === 1 && len / 2 === firstOneIdx\n }\n};" ]
2,610
convert-an-array-into-a-2d-array-with-conditions
[ "Process the elements in the array one by one in any order and only create a new row in the matrix when we cannot put it into the existing rows", "We can simply iterate over the existing rows of the matrix to see if we can place each element." ]
/** * @param {number[]} nums * @return {number[][]} */ var findMatrix = function(nums) { };
You are given an integer array nums. You need to create a 2D array from nums satisfying the following conditions: The 2D array should contain only the elements of the array nums. Each row in the 2D array contains distinct integers. The number of rows in the 2D array should be minimal. Return the resulting array. If there are multiple answers, return any of them. Note that the 2D array can have a different number of elements on each row.   Example 1: Input: nums = [1,3,4,1,2,3,1] Output: [[1,3,4,2],[1,3],[1]] Explanation: We can create a 2D array that contains the following rows: - 1,3,4,2 - 1,3 - 1 All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer. It can be shown that we cannot have less than 3 rows in a valid array. Example 2: Input: nums = [1,2,3,4] Output: [[4,3,2,1]] Explanation: All elements of the array are distinct, so we can keep all of them in the first row of the 2D array.   Constraints: 1 <= nums.length <= 200 1 <= nums[i] <= nums.length
Medium
[ "array", "hash-table" ]
[ "const findMatrix = function(nums) {\n\n const hash = new Map()\n for(const e of nums) {\n if(!hash.has(e)) hash.set(e, 0)\n hash.set(e, hash.get(e) + 1)\n }\n \n const arr = []\n for(const [k, v] of hash) {\n arr.push([v, k])\n }\n \n arr.sort((a, b) => b[0] - a[0])\n \n const res = []\n for(let i = 0, len = arr.length; i < len; i++) {\n const [freq, val] = arr[i]\n for(let j = 0; j < freq; j++) {\n if(res[j] == null) res[j] = []\n res[j].push(val)\n }\n }\n \n return res\n};" ]
2,611
mice-and-cheese
[ "The intended solution uses greedy approach.", "Imagine at first that the second mouse eats all the cheese, then we should choose k types of cheese with the maximum sum of - reward2[i] + reward1[i]." ]
/** * @param {number[]} reward1 * @param {number[]} reward2 * @param {number} k * @return {number} */ var miceAndCheese = function(reward1, reward2, k) { };
There are two mice and n different types of cheese, each type of cheese should be eaten by exactly one mouse. A point of the cheese with index i (0-indexed) is: reward1[i] if the first mouse eats it. reward2[i] if the second mouse eats it. You are given a positive integer array reward1, a positive integer array reward2, and a non-negative integer k. Return the maximum points the mice can achieve if the first mouse eats exactly k types of cheese.   Example 1: Input: reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2 Output: 15 Explanation: In this example, the first mouse eats the 2nd (0-indexed) and the 3rd types of cheese, and the second mouse eats the 0th and the 1st types of cheese. The total points are 4 + 4 + 3 + 4 = 15. It can be proven that 15 is the maximum total points that the mice can achieve. Example 2: Input: reward1 = [1,1], reward2 = [1,1], k = 2 Output: 2 Explanation: In this example, the first mouse eats the 0th (0-indexed) and 1st types of cheese, and the second mouse does not eat any cheese. The total points are 1 + 1 = 2. It can be proven that 2 is the maximum total points that the mice can achieve.   Constraints: 1 <= n == reward1.length == reward2.length <= 105 1 <= reward1[i], reward2[i] <= 1000 0 <= k <= n
Medium
[ "array", "greedy", "sorting", "heap-priority-queue" ]
[ "const miceAndCheese = function(reward1, reward2, k) {\n const pq = new PQ((a, b) => a[2] > b[2])\n \n const n = reward1.length\n \n for(let i = 0; i < n; i++) {\n const tmp = [reward1[i], reward2[i], reward1[i] - reward2[i]]\n pq.push(tmp)\n }\n \n let res = 0\n while(k) {\n const [v1, v2, delta] = pq.pop()\n res += v1\n \n k--\n }\n \n while(!pq.isEmpty()) {\n const [v1, v2] = pq.pop()\n res += v2\n }\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,612
minimum-reverse-operations
[ "Can we use a breadth-first search to find the minimum number of operations?", "Find the beginning and end indices of the subarray of size k that can be reversed to bring 1 to a particular position.", "Can we visit every index or do we need to consider the parity of k?" ]
/** * @param {number} n * @param {number} p * @param {number[]} banned * @param {number} k * @return {number[]} */ var minReverseOperations = function(n, p, banned, k) { };
You are given an integer n and an integer p in the range [0, n - 1]. Representing a 0-indexed array arr of length n where all positions are set to 0's, except position p which is set to 1. You are also given an integer array banned containing some positions from the array. For the ith position in banned, arr[banned[i]] = 0, and banned[i] != p. You can perform multiple operations on arr. In an operation, you can choose a subarray with size k and reverse the subarray. However, the 1 in arr should never go to any of the positions in banned. In other words, after each operation arr[banned[i]] remains 0. Return an array ans where for each i from [0, n - 1], ans[i] is the minimum number of reverse operations needed to bring the 1 to position i in arr, or -1 if it is impossible. A subarray is a contiguous non-empty sequence of elements within an array. The values of ans[i] are independent for all i's. The reverse of an array is an array containing the values in reverse order.   Example 1: Input: n = 4, p = 0, banned = [1,2], k = 4 Output: [0,-1,-1,1] Explanation: In this case k = 4 so there is only one possible reverse operation we can perform, which is reversing the whole array. Initially, 1 is placed at position 0 so the amount of operations we need for position 0 is 0. We can never place a 1 on the banned positions, so the answer for positions 1 and 2 is -1. Finally, with one reverse operation we can bring the 1 to index 3, so the answer for position 3 is 1. Example 2: Input: n = 5, p = 0, banned = [2,4], k = 3 Output: [0,-1,-1,-1,-1] Explanation: In this case the 1 is initially at position 0, so the answer for that position is 0. We can perform reverse operations of size 3. The 1 is currently located at position 0, so we need to reverse the subarray [0, 2] for it to leave that position, but reversing that subarray makes position 2 have a 1, which shouldn't happen. So, we can't move the 1 from position 0, making the result for all the other positions -1. Example 3: Input: n = 4, p = 2, banned = [0,1,3], k = 1 Output: [-1,-1,0,-1] Explanation: In this case we can only perform reverse operations of size 1. So the 1 never changes its position.   Constraints: 1 <= n <= 105 0 <= p <= n - 1 0 <= banned.length <= n - 1 0 <= banned[i] <= n - 1 1 <= k <= n  banned[i] != p all values in banned are unique 
Hard
[ "array", "breadth-first-search", "ordered-set" ]
null
[]
2,614
prime-in-diagonal
[ "Iterate over the diagonals of the matrix and check for each element.", "Check if the element is prime or not in O(sqrt(n)) time." ]
/** * @param {number[][]} nums * @return {number} */ var diagonalPrime = function(nums) { };
You are given a 0-indexed two-dimensional integer array nums. Return the largest prime number that lies on at least one of the diagonals of nums. In case, no prime is present on any of the diagonals, return 0. Note that: An integer is prime if it is greater than 1 and has no positive integer divisors other than 1 and itself. An integer val is on one of the diagonals of nums if there exists an integer i for which nums[i][i] = val or an i for which nums[i][nums.length - i - 1] = val. In the above diagram, one diagonal is [1,5,9] and another diagonal is [3,5,7].   Example 1: Input: nums = [[1,2,3],[5,6,7],[9,10,11]] Output: 11 Explanation: The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11. Example 2: Input: nums = [[1,2,3],[5,17,7],[9,11,10]] Output: 17 Explanation: The numbers 1, 3, 9, 10, and 17 are all present on at least one of the diagonals. 17 is the largest prime, so we return 17.   Constraints: 1 <= nums.length <= 300 nums.length == numsi.length 1 <= nums[i][j] <= 4*106
Easy
[ "array", "math", "matrix", "number-theory" ]
[ "const isPrime = num => {\n for(let i = 2, s = Math.sqrt(num); i <= s; i++) {\n if(num % i === 0) return false;\n }\n return num > 1;\n}\n\nvar diagonalPrime = function(nums) {\n const n = nums.length\n let res = 0\n for(let i = 0; i < n; i++) {\n if(isPrime(nums[i][i])) {\n res = Math.max(res, nums[i][i])\n }\n }\n \n for(let i = 0; i < n; i++) {\n if(isPrime(nums[i][n - 1 - i])) {\n res = Math.max(res, nums[i][n - 1 - i])\n }\n }\n \n \n return res\n \n\n};" ]
2,615
sum-of-distances
[ "Can we use the prefix sum here?", "For each number x, collect all the indices where x occurs, and calculate the prefix sum of the array.", "For each occurrence of x, the indices to the right will be regular subtraction while the indices to the left will be reversed subtraction." ]
/** * @param {number[]} nums * @return {number[]} */ var distance = function(nums) { };
You are given a 0-indexed integer array nums. There exists an array arr of length nums.length, where arr[i] is the sum of |i - j| over all j such that nums[j] == nums[i] and j != i. If there is no such j, set arr[i] to be 0. Return the array arr.   Example 1: Input: nums = [1,3,1,1,2] Output: [5,0,3,4,0] Explanation: When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5. When i = 1, arr[1] = 0 because there is no other index with value 3. When i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3. When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4. When i = 4, arr[4] = 0 because there is no other index with value 2. Example 2: Input: nums = [0,5,3] Output: [0,0,0] Explanation: Since each element in nums is distinct, arr[i] = 0 for all i.   Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109
Medium
[ "array", "hash-table", "prefix-sum" ]
[ "const distance = function(nums) {\n const n = nums.length\n const res = Array(n).fill(0)\n const hash = {}\n for(let i = 0; i < n; i++) {\n const e = nums[i]\n if(hash[e] == null) hash[e] = []\n hash[e].push(i)\n }\n \n const keys = Object.keys(hash)\n for(const k of keys) {\n const arr = hash[k]\n const totalSum = arr.reduce((ac, e) => ac + e, 0)\n let preSum = 0\n if(arr.length < 2) continue\n for(let i = 0, len = arr.length; i < len; i++) {\n const idx = arr[i]\n const postSum = totalSum - (preSum + idx)\n \n res[idx] += idx * i\n res[idx] -= preSum\n res[idx] -= idx * (len - 1 - i)\n res[idx] += postSum\n \n preSum += idx\n }\n }\n \n \n return res\n};" ]
2,616
minimize-the-maximum-difference-of-pairs
[ "Can we use dynamic programming here?", "To minimize the answer, the array should be sorted first.", "The recurrence relation is fn(i, x) = min(fn(i+1, x), max(abs(nums[i]-nums[i+1]), fn(i+2, p-1)), and fn(0,p) gives the desired answer." ]
/** * @param {number[]} nums * @param {number} p * @return {number} */ var minimizeMax = function(nums, p) { };
You are given a 0-indexed integer array nums and an integer p. Find p pairs of indices of nums such that the maximum difference amongst all the pairs is minimized. Also, ensure no index appears more than once amongst the p pairs. Note that for a pair of elements at the index i and j, the difference of this pair is |nums[i] - nums[j]|, where |x| represents the absolute value of x. Return the minimum maximum difference among all p pairs. We define the maximum of an empty set to be zero.   Example 1: Input: nums = [10,1,2,7,1,3], p = 2 Output: 1 Explanation: The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. Example 2: Input: nums = [4,2,1,2], p = 1 Output: 0 Explanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain.   Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109 0 <= p <= (nums.length)/2
Medium
[ "array", "binary-search", "greedy" ]
[ "const minimizeMax = function(nums, p) {\n nums.sort((a, b) => a - b)\n const n = nums.length\n let l = 0, r = nums.at(-1) - nums[0]\n \n while(l < r) {\n const mid = Math.floor(l + (r - l) / 2)\n let k = 0\n for(let i = 1; i < n;) {\n if(nums[i] - nums[i - 1] <= mid) {\n k++\n i += 2\n } else {\n i++\n }\n }\n \n if(k >= p) {\n r = mid\n } else {\n l = mid + 1\n }\n }\n \n return l\n};" ]
2,617
minimum-number-of-visited-cells-in-a-grid
[ "For each cell (i,j), it is critical to find out the minimum number of steps to reach (i,j), denoted dis[i][j], quickly, given the tight constraint.", "Calculate dis[i][j] going left to right, top to bottom.", "Suppose we want to calculate dis[i][j], keep track of a priority queue that stores (dis[i][k], i, k) for all k ≤ j, and another priority queue that stores (dis[k][j], k, j) for all k ≤ i." ]
/** * @param {number[][]} grid * @return {number} */ var minimumVisitedCells = function(grid) { };
You are given a 0-indexed m x n integer matrix grid. Your initial position is at the top-left cell (0, 0). Starting from the cell (i, j), you can move to one of the following cells: Cells (i, k) with j < k <= grid[i][j] + j (rightward movement), or Cells (k, j) with i < k <= grid[i][j] + i (downward movement). Return the minimum number of cells you need to visit to reach the bottom-right cell (m - 1, n - 1). If there is no valid path, return -1.   Example 1: Input: grid = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]] Output: 4 Explanation: The image above shows one of the paths that visits exactly 4 cells. Example 2: Input: grid = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]] Output: 3 Explanation: The image above shows one of the paths that visits exactly 3 cells. Example 3: Input: grid = [[2,1,0],[1,0,0]] Output: -1 Explanation: It can be proven that no path exists.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 105 1 <= m * n <= 105 0 <= grid[i][j] < m * n grid[m - 1][n - 1] == 0
Hard
[ "array", "binary-search", "dynamic-programming", "stack", "union-find", "binary-indexed-tree", "segment-tree" ]
null
[]
2,639
find-the-width-of-columns-of-a-grid
[ "You can find the length of a number by dividing it by 10 and then rounding it down again and again until this number becomes equal to 0. Add 1 if this number is negative.", "Traverse the matrix column-wise to find the maximum length in each column." ]
/** * @param {number[][]} grid * @return {number[]} */ var findColumnWidth = function(grid) { };
You are given a 0-indexed m x n integer matrix grid. The width of a column is the maximum length of its integers. For example, if grid = [[-10], [3], [12]], the width of the only column is 3 since -10 is of length 3. Return an integer array ans of size n where ans[i] is the width of the ith column. The length of an integer x with len digits is equal to len if x is non-negative, and len + 1 otherwise.   Example 1: Input: grid = [[1],[22],[333]] Output: [3] Explanation: In the 0th column, 333 is of length 3. Example 2: Input: grid = [[-15,1,3],[15,7,12],[5,6,-2]] Output: [3,1,2] Explanation: In the 0th column, only -15 is of length 3. In the 1st column, all integers are of length 1. In the 2nd column, both 12 and -2 are of length 2.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 -109 <= grid[r][c] <= 109
Easy
[ "array", "matrix" ]
null
[]
2,640
find-the-score-of-all-prefixes-of-an-array
[ "Keep track of the prefix maximum of the array", "Establish a relationship between ans[i] and ans[i-1]", "for 0 < i < n, ans[i] = ans[i-1]+conver[i]. In other words, array ans is the prefix sum array of the conversion array" ]
/** * @param {number[]} nums * @return {number[]} */ var findPrefixScore = function(nums) { };
We define the conversion array conver of an array arr as follows: conver[i] = arr[i] + max(arr[0..i]) where max(arr[0..i]) is the maximum value of arr[j] over 0 <= j <= i. We also define the score of an array arr as the sum of the values of the conversion array of arr. Given a 0-indexed integer array nums of length n, return an array ans of length n where ans[i] is the score of the prefix nums[0..i].   Example 1: Input: nums = [2,3,7,5,10] Output: [4,10,24,36,56] Explanation: For the prefix [2], the conversion array is [4] hence the score is 4 For the prefix [2, 3], the conversion array is [4, 6] hence the score is 10 For the prefix [2, 3, 7], the conversion array is [4, 6, 14] hence the score is 24 For the prefix [2, 3, 7, 5], the conversion array is [4, 6, 14, 12] hence the score is 36 For the prefix [2, 3, 7, 5, 10], the conversion array is [4, 6, 14, 12, 20] hence the score is 56 Example 2: Input: nums = [1,1,2,4,8,16] Output: [2,4,8,16,32,64] Explanation: For the prefix [1], the conversion array is [2] hence the score is 2 For the prefix [1, 1], the conversion array is [2, 2] hence the score is 4 For the prefix [1, 1, 2], the conversion array is [2, 2, 4] hence the score is 8 For the prefix [1, 1, 2, 4], the conversion array is [2, 2, 4, 8] hence the score is 16 For the prefix [1, 1, 2, 4, 8], the conversion array is [2, 2, 4, 8, 16] hence the score is 32 For the prefix [1, 1, 2, 4, 8, 16], the conversion array is [2, 2, 4, 8, 16, 32] hence the score is 64   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109
Medium
[ "array", "prefix-sum" ]
[ "const findPrefixScore = function(nums) {\n const { max } = Math\n const res = []\n let ma = 0, sum = 0\n for(const e of nums) {\n ma = max(e, ma)\n sum += ma + e\n res.push(sum)\n }\n \n return res\n};" ]
2,641
cousins-in-binary-tree-ii
[ "Use DFS two times.", "For the first time, find the sum of values of all the levels of the binary tree.", "For the second time, update the value of the node with the sum of the values of the current level - sibling node’s values." ]
/** * 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 {TreeNode} */ var replaceValueInTree = function(root) { };
Given the root of a binary tree, replace the value of each node in the tree with the sum of all its cousins' values. Two nodes of a binary tree are cousins if they have the same depth with different parents. Return the root of the modified tree. Note that the depth of a node is the number of edges in the path from the root node to it.   Example 1: Input: root = [5,4,9,1,10,null,7] Output: [0,0,0,7,7,null,11] Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 5 does not have any cousins so its sum is 0. - Node with value 4 does not have any cousins so its sum is 0. - Node with value 9 does not have any cousins so its sum is 0. - Node with value 1 has a cousin with value 7 so its sum is 7. - Node with value 10 has a cousin with value 7 so its sum is 7. - Node with value 7 has cousins with values 1 and 10 so its sum is 11. Example 2: Input: root = [3,1,2] Output: [0,0,0] Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 3 does not have any cousins so its sum is 0. - Node with value 1 does not have any cousins so its sum is 0. - Node with value 2 does not have any cousins so its sum is 0.   Constraints: The number of nodes in the tree is in the range [1, 105]. 1 <= Node.val <= 104
Medium
[ "hash-table", "tree", "depth-first-search", "breadth-first-search", "binary-tree" ]
null
[]
2,642
design-graph-with-shortest-path-calculator
[ "After adding each edge, update your graph with the new edge, and you can calculate the shortest path in your graph each time the shortestPath method is called.", "Use dijkstra’s algorithm to calculate the shortest paths." ]
/** * @param {number} n * @param {number[][]} edges */ var Graph = function(n, edges) { }; /** * @param {number[]} edge * @return {void} */ Graph.prototype.addEdge = function(edge) { }; /** * @param {number} node1 * @param {number} node2 * @return {number} */ Graph.prototype.shortestPath = function(node1, node2) { }; /** * Your Graph object will be instantiated and called as such: * var obj = new Graph(n, edges) * obj.addEdge(edge) * var param_2 = obj.shortestPath(node1,node2) */
There is a directed weighted graph that consists of n nodes numbered from 0 to n - 1. The edges of the graph are initially represented by the given array edges where edges[i] = [fromi, toi, edgeCosti] meaning that there is an edge from fromi to toi with the cost edgeCosti. Implement the Graph class: Graph(int n, int[][] edges) initializes the object with n nodes and the given edges. addEdge(int[] edge) adds an edge to the list of edges where edge = [from, to, edgeCost]. It is guaranteed that there is no edge between the two nodes before adding this one. int shortestPath(int node1, int node2) returns the minimum cost of a path from node1 to node2. If no path exists, return -1. The cost of a path is the sum of the costs of the edges in the path.   Example 1: Input ["Graph", "shortestPath", "shortestPath", "addEdge", "shortestPath"] [[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]] Output [null, 6, -1, null, 6] Explanation Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -> 0 -> 1 -> 2 with a total cost of 3 + 2 + 1 = 6. g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -> 1 -> 3 with a total cost of 2 + 4 = 6.   Constraints: 1 <= n <= 100 0 <= edges.length <= n * (n - 1) edges[i].length == edge.length == 3 0 <= fromi, toi, from, to, node1, node2 <= n - 1 1 <= edgeCosti, edgeCost <= 106 There are no repeated edges and no self-loops in the graph at any point. At most 100 calls will be made for addEdge. At most 100 calls will be made for shortestPath.
Hard
[ "graph", "design", "heap-priority-queue", "shortest-path" ]
[ "const Graph = function (n, edges) {\n this.map = new Map()\n const map = this.map\n for (let i = 0; i < edges.length; i++) {\n let edge = edges[i]\n let from = edge[0]\n let to = edge[1]\n let cost = edge[2]\n if (!map.has(from)) {\n map.set(from, new Set())\n }\n\n map.get(from).add({ to, cost })\n }\n}\n\n\nGraph.prototype.addEdge = function (edge) {\n let map = this.map\n let from = edge[0]\n let to = edge[1]\n let cost = edge[2]\n if (!map.has(from)) {\n map.set(from, new Set())\n }\n\n map.get(from).add({ to, cost })\n}\n\n\nGraph.prototype.shortestPath = function (node1, node2) {\n const heap = new MinPriorityQueue()\n heap.enqueue({ node: node1, cost: 0 }, 0)\n let visited = new Set()\n\n while (heap.size() > 0) {\n const top = heap.dequeue().element\n\n if (visited.has(top.node)) {\n continue\n }\n visited.add(top.node)\n if (top.node === node2) {\n return top.cost\n }\n let next = this.map.get(top.node)\n if (next) {\n for (let n of next) {\n heap.enqueue({ node: n.to, cost: top.cost + n.cost }, top.cost + n.cost)\n }\n }\n }\n\n return -1\n}" ]
2,643
row-with-maximum-ones
[ "Iterate through each row and keep the count of ones." ]
/** * @param {number[][]} mat * @return {number[]} */ var rowAndMaximumOnes = function(mat) { };
Given a m x n binary matrix mat, find the 0-indexed position of the row that contains the maximum count of ones, and the number of ones in that row. In case there are multiple rows that have the maximum count of ones, the row with the smallest row number should be selected. Return an array containing the index of the row, and the number of ones in it.   Example 1: Input: mat = [[0,1],[1,0]] Output: [0,1] Explanation: Both rows have the same number of 1's. So we return the index of the smaller row, 0, and the maximum count of ones (1). So, the answer is [0,1]. Example 2: Input: mat = [[0,0,0],[0,1,1]] Output: [1,2] Explanation: The row indexed 1 has the maximum count of ones (2). So we return its index, 1, and the count. So, the answer is [1,2]. Example 3: Input: mat = [[0,0],[1,1],[0,0]] Output: [1,2] Explanation: The row indexed 1 has the maximum count of ones (2). So the answer is [1,2].   Constraints: m == mat.length  n == mat[i].length  1 <= m, n <= 100  mat[i][j] is either 0 or 1.
Easy
[ "array", "matrix" ]
[ "var rowAndMaximumOnes = function(mat) {\n const arr= []\n const m = mat.length, n = mat[0].length\n let ma = 0\n for(let i = 0; i < m; i++) {\n let cnt = 0\n for(let j = 0; j < n; j++) {\n if(mat[i][j] === 1) cnt++\n }\n arr[i] = cnt\n ma = Math.max(ma, cnt)\n }\n \n for(let i = 0; i < m; i++) {\n if(arr[i] === ma) return [i, ma]\n }\n};" ]
2,644
find-the-maximum-divisibility-score
[ "Consider counting for each element in divisors the count of elements in nums divisible by it using bruteforce.", "After counting for each divisor, take the one with the maximum count. In case of a tie, take the minimum one of them." ]
/** * @param {number[]} nums * @param {number[]} divisors * @return {number} */ var maxDivScore = function(nums, divisors) { };
You are given two 0-indexed integer arrays nums and divisors. The divisibility score of divisors[i] is the number of indices j such that nums[j] is divisible by divisors[i]. Return the integer divisors[i] with the maximum divisibility score. If there is more than one integer with the maximum score, return the minimum of them.   Example 1: Input: nums = [4,7,9,3,9], divisors = [5,2,3] Output: 3 Explanation: The divisibility score for every element in divisors is: The divisibility score of divisors[0] is 0 since no number in nums is divisible by 5. The divisibility score of divisors[1] is 1 since nums[0] is divisible by 2. The divisibility score of divisors[2] is 3 since nums[2], nums[3], and nums[4] are divisible by 3. Since divisors[2] has the maximum divisibility score, we return it. Example 2: Input: nums = [20,14,21,10], divisors = [5,7,5] Output: 5 Explanation: The divisibility score for every element in divisors is: The divisibility score of divisors[0] is 2 since nums[0] and nums[3] are divisible by 5. The divisibility score of divisors[1] is 2 since nums[1] and nums[2] are divisible by 7. The divisibility score of divisors[2] is 2 since nums[0] and nums[3] are divisible by 5. Since divisors[0], divisors[1], and divisors[2] all have the maximum divisibility score, we return the minimum of them (i.e., divisors[2]). Example 3: Input: nums = [12], divisors = [10,16] Output: 10 Explanation: The divisibility score for every element in divisors is: The divisibility score of divisors[0] is 0 since no number in nums is divisible by 10. The divisibility score of divisors[1] is 0 since no number in nums is divisible by 16. Since divisors[0] and divisors[1] both have the maximum divisibility score, we return the minimum of them (i.e., divisors[0]).   Constraints: 1 <= nums.length, divisors.length <= 1000 1 <= nums[i], divisors[i] <= 109
Easy
[ "array" ]
[ "var maxDivScore = function(nums, divisors) {\n divisors.sort((a, b) => a - b)\n nums.sort((a, b) => a - b)\n \n let arr = [], ma = 0\n for(let i = 0; i < divisors.length; i++) {\n const div = divisors[i]\n let cnt = 0\n for(let j = 0; j < nums.length; j++) {\n if(nums[j] % div === 0) cnt++\n }\n arr[i] = cnt\n ma = Math.max(ma, cnt)\n }\n \n for(let i = 0; i < divisors.length; i++) {\n if(arr[i] === ma) return divisors[i]\n }\n};" ]
2,645
minimum-additions-to-make-valid-string
[ "Maintain a pointer on word and another pointer on string “abc”.", "If the two characters that are being pointed to differ, Increment the answer and the pointer to the string “abc” by one." ]
/** * @param {string} word * @return {number} */ var addMinimum = function(word) { };
Given a string word to which you can insert letters "a", "b" or "c" anywhere and any number of times, return the minimum number of letters that must be inserted so that word becomes valid. A string is called valid if it can be formed by concatenating the string "abc" several times.   Example 1: Input: word = "b" Output: 2 Explanation: Insert the letter "a" right before "b", and the letter "c" right next to "a" to obtain the valid string "abc". Example 2: Input: word = "aaa" Output: 6 Explanation: Insert letters "b" and "c" next to each "a" to obtain the valid string "abcabcabc". Example 3: Input: word = "abc" Output: 0 Explanation: word is already valid. No modifications are needed.   Constraints: 1 <= word.length <= 50 word consists of letters "a", "b" and "c" only. 
Medium
[ "string", "dynamic-programming", "stack", "greedy" ]
[ "var addMinimum = function(word) {\n\tlet pattern = \"abc\"\n\tlet p1 = 0, p2 = 0\n\tlet cnt = 0\n\twhile( p1 < word.length) {\n\t\twhile( p1 < word.length && word[p1] != pattern[p2]) {\n\t\t\tp2 = (p2 + 1) % 3\n\t\t\tcnt++\n\t\t}\n\t\tp1++\n\t\tp2 = (p2 + 1) % 3\n\t}\n\tif (p2 == 1) {\n\t\tcnt += 2\n\t} else if (p2 == 2) {\n\t\tcnt += 1\n\t}\n\treturn cnt\n};" ]
2,646
minimize-the-total-price-of-the-trips
[ "The final answer is the price[i] * freq[i], where freq[i] is the number of times node i was visited during the trip, and price[i] is the final price.", "To find freq[i] we will use dfs or bfs for each trip and update every node on the path start and end.", "Finally, to find the final price[i] we will use dynamic programming on the tree. Let dp(v, 0/1) denote the minimum total price with the node v’s price being halved or not." ]
/** * @param {number} n * @param {number[][]} edges * @param {number[]} price * @param {number[][]} trips * @return {number} */ var minimumTotalPrice = function(n, edges, price, trips) { };
There exists an undirected and 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. Additionally, you are given a 2D integer array trips, where trips[i] = [starti, endi] indicates that you start the ith trip from the node starti and travel to the node endi by any path you like. Before performing your first trip, you can choose some non-adjacent nodes and halve the prices. Return the minimum total price sum to perform all the given trips.   Example 1: Input: n = 4, edges = [[0,1],[1,2],[1,3]], price = [2,2,10,6], trips = [[0,3],[2,1],[2,3]] Output: 23 Explanation: The diagram above denotes the tree after rooting it at node 2. The first part shows the initial tree and the second part shows the tree after choosing nodes 0, 2, and 3, and making their price half. For the 1st trip, we choose path [0,1,3]. The price sum of that path is 1 + 2 + 3 = 6. For the 2nd trip, we choose path [2,1]. The price sum of that path is 2 + 5 = 7. For the 3rd trip, we choose path [2,1,3]. The price sum of that path is 5 + 2 + 3 = 10. The total price sum of all trips is 6 + 7 + 10 = 23. It can be proven, that 23 is the minimum answer that we can achieve. Example 2: Input: n = 2, edges = [[0,1]], price = [2,2], trips = [[0,0]] Output: 1 Explanation: The diagram above denotes the tree after rooting it at node 0. The first part shows the initial tree and the second part shows the tree after choosing node 0, and making its price half. For the 1st trip, we choose path [0]. The price sum of that path is 1. The total price sum of all trips is 1. It can be proven, that 1 is the minimum answer that we can achieve.   Constraints: 1 <= n <= 50 edges.length == n - 1 0 <= ai, bi <= n - 1 edges represents a valid tree. price.length == n price[i] is an even integer. 1 <= price[i] <= 1000 1 <= trips.length <= 100 0 <= starti, endi <= n - 1
Hard
[ "array", "dynamic-programming", "tree", "depth-first-search", "graph" ]
[ "var minimumTotalPrice = function (n, edges, price, trips) {\n const graph = []\n const { min, max } = Math\n for (const [u, v] of edges) {\n if (graph[u] == null) graph[u] = []\n if (graph[v] == null) graph[v] = []\n graph[u].push(v)\n graph[v].push(u)\n }\n\n const cnt = Array(n).fill(0)\n\n function dfs(p, i, e) {\n if (i == e) {\n ++cnt[i]\n return true\n }\n for (const j of graph[i] || []) {\n if (j != p && dfs(i, j, e)) {\n ++cnt[i]\n return true\n }\n }\n return false\n }\n\n for (const t of trips) dfs(-1, t[0], t[1])\n\n const dp = Array.from({ length: n }, () => Array(2).fill(Infinity))\n\n function minCost(pre, i, status) {\n if (dp[i][status] == Infinity) {\n dp[i][status] = (price[i] >> status) * cnt[i]\n for (const j of graph[i] || []) {\n if (j == pre) continue\n if (status == 1) dp[i][status] += minCost(i, j, 0)\n else dp[i][status] += min(minCost(i, j, 0), minCost(i, j, 1))\n }\n }\n return dp[i][status]\n }\n\n return min(minCost(-1, 0, 0), minCost(-1, 0, 1))\n}" ]
2,651
calculate-delayed-arrival-time
[ "Use the modulo operator to handle the case when the arrival time plus the delayed time goes beyond 24 hours.", "If the arrival time plus the delayed time is greater than or equal to 24, you can also subtract 24 to get the time in the 24-hour format.", "Use the modulo operator to handle the case when the arrival time plus the delayed time goes beyond 24 hours.", "If the arrival time plus the delayed time is greater than or equal to 24, you can also subtract 24 to get the time in the 24-hour format." ]
/** * @param {number} arrivalTime * @param {number} delayedTime * @return {number} */ var findDelayedArrivalTime = function(arrivalTime, delayedTime) { };
You are given a positive integer arrivalTime denoting the arrival time of a train in hours, and another positive integer delayedTime denoting the amount of delay in hours. Return the time when the train will arrive at the station. Note that the time in this problem is in 24-hours format.   Example 1: Input: arrivalTime = 15, delayedTime = 5 Output: 20 Explanation: Arrival time of the train was 15:00 hours. It is delayed by 5 hours. Now it will reach at 15+5 = 20 (20:00 hours). Example 2: Input: arrivalTime = 13, delayedTime = 11 Output: 0 Explanation: Arrival time of the train was 13:00 hours. It is delayed by 11 hours. Now it will reach at 13+11=24 (Which is denoted by 00:00 in 24 hours format so return 0).   Constraints: 1 <= arrivaltime < 24 1 <= delayedTime <= 24
Easy
[ "math" ]
[ "var findDelayedArrivalTime = function(arrivalTime, delayedTime) {\n return (arrivalTime + delayedTime) % 24\n};" ]
2,652
sum-multiples
[ "Iterate through the range 1 to n and count numbers divisible by either 3, 5, or 7." ]
/** * @param {number} n * @return {number} */ var sumOfMultiples = function(n) { };
Given a positive integer n, find the sum of all integers in the range [1, n] inclusive that are divisible by 3, 5, or 7. Return an integer denoting the sum of all numbers in the given range satisfying the constraint.   Example 1: Input: n = 7 Output: 21 Explanation: Numbers in the range [1, 7] that are divisible by 3, 5, or 7 are 3, 5, 6, 7. The sum of these numbers is 21. Example 2: Input: n = 10 Output: 40 Explanation: Numbers in the range [1, 10] that are divisible by 3, 5, or 7 are 3, 5, 6, 7, 9, 10. The sum of these numbers is 40. Example 3: Input: n = 9 Output: 30 Explanation: Numbers in the range [1, 9] that are divisible by 3, 5, or 7 are 3, 5, 6, 7, 9. The sum of these numbers is 30.   Constraints: 1 <= n <= 103
Easy
[ "array", "math", "number-theory" ]
[ "const sumOfMultiples = function(n) {\n let res = 0\n const set = new Set()\n for(let i = 3; i <= n; i += 3) {\n set.add(i)\n }\n \n for(let i = 5; i <= n; i += 5) {\n set.add(i)\n }\n \n for(let i = 7; i <= n; i += 7) {\n set.add(i)\n }\n \n for(const e of set) {\n res += e\n }\n \n return res\n};" ]
2,653
sliding-subarray-beauty
[ "Try to maintain the frequency of negative numbers in the current window of size k.", "The x^th smallest negative integer can be gotten by iterating through the frequencies of the numbers in order." ]
/** * @param {number[]} nums * @param {number} k * @param {number} x * @return {number[]} */ var getSubarrayBeauty = function(nums, k, x) { };
Given an integer array nums containing n integers, find the beauty of each subarray of size k. The beauty of a subarray is the xth smallest integer in the subarray if it is negative, or 0 if there are fewer than x negative integers. Return an integer array containing n - k + 1 integers, which denote the beauty of the subarrays in order from the first index in the array. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,-1,-3,-2,3], k = 3, x = 2 Output: [-1,-2,-2] Explanation: There are 3 subarrays with size k = 3. The first subarray is [1, -1, -3] and the 2nd smallest negative integer is -1.  The second subarray is [-1, -3, -2] and the 2nd smallest negative integer is -2.  The third subarray is [-3, -2, 3] and the 2nd smallest negative integer is -2. Example 2: Input: nums = [-1,-2,-3,-4,-5], k = 2, x = 2 Output: [-1,-2,-3,-4] Explanation: There are 4 subarrays with size k = 2. For [-1, -2], the 2nd smallest negative integer is -1. For [-2, -3], the 2nd smallest negative integer is -2. For [-3, -4], the 2nd smallest negative integer is -3. For [-4, -5], the 2nd smallest negative integer is -4.  Example 3: Input: nums = [-3,1,2,-3,0,-3], k = 2, x = 1 Output: [-3,0,-3,-3,-3] Explanation: There are 5 subarrays with size k = 2. For [-3, 1], the 1st smallest negative integer is -3. For [1, 2], there is no negative integer so the beauty is 0. For [2, -3], the 1st smallest negative integer is -3. For [-3, 0], the 1st smallest negative integer is -3. For [0, -3], the 1st smallest negative integer is -3.   Constraints: n == nums.length  1 <= n <= 105 1 <= k <= n 1 <= x <= k  -50 <= nums[i] <= 50 
Medium
[ "array", "hash-table", "sliding-window" ]
[ "const getSubarrayBeauty = function(nums, k, x) {\n const arr = Array(101).fill(0)\n const res = [], n = nums.length, delta = 50\n for(let i = 0; i < n; i++) {\n const cur = nums[i]\n const idx = cur + delta\n arr[idx]++\n if(i < k - 1) continue\n else if(i === k - 1) res.push(helper())\n else {\n const prev = nums[i - k]\n arr[prev + delta]--\n res.push(helper())\n }\n }\n \n return res\n \n function helper() {\n let res = 0, neg = 0\n // -50 ---> 0\n // -1 ---> 49\n for(let i = 0, len = arr.length; i < len; i++) {\n if(i < delta && arr[i] > 0) neg += arr[i]\n if(neg >= x) {\n res = i - delta\n break\n }\n }\n \n return res\n }\n};", "const getSubarrayBeauty = function(nums, k, x) {\n let counter = Array(50).fill(0), ans = new Array(nums.length - k + 1).fill(0);\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] < 0) counter[nums[i] + 50]++;\n if (i - k >= 0 && nums[i - k] < 0) counter[nums[i - k] + 50]--;\n if (i - k + 1 < 0) continue;\n let count = 0;\n for (let j = 0; j < 50; j++) {\n count += counter[j];\n if (count >= x) {\n ans[i - k + 1] = j - 50;\n break;\n }\n }\n }\n return ans;\n};" ]
2,654
minimum-number-of-operations-to-make-all-array-elements-equal-to-1
[ "Note that if you have at least one occurrence of 1 in the array, then you can make all the other elements equal to 1 with one operation each.", "Try finding the shortest subarray with a gcd equal to 1." ]
/** * @param {number[]} nums * @return {number} */ var minOperations = function(nums) { };
You are given a 0-indexed array nums consisiting of positive integers. You can do the following operation on the array any number of times: Select an index i such that 0 <= i < n - 1 and replace either of nums[i] or nums[i+1] with their gcd value. Return the minimum number of operations to make all elements of nums equal to 1. If it is impossible, return -1. The gcd of two integers is the greatest common divisor of the two integers.   Example 1: Input: nums = [2,6,3,4] Output: 4 Explanation: We can do the following operations: - Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4]. - Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4]. - Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4]. - Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1]. Example 2: Input: nums = [2,10,6,14] Output: -1 Explanation: It can be shown that it is impossible to make all the elements equal to 1.   Constraints: 2 <= nums.length <= 50 1 <= nums[i] <= 106   Follow-up: The O(n) time complexity solution works, but could you find an O(1) constant time complexity solution?
Medium
[ "array", "math", "number-theory" ]
[ "var minOperations = function(nums) {\n let n = nums.length;\n\n let ones = cntOnes();\n if (ones) return n - ones;\n\n for (let r = 2; r <= n; r++) {\n for (let i = 0; i + r <= n; i++) {\n let g = 0;\n for (let j = i; j < i + r; j++) g = gcd(g, nums[j]);\n if (g == 1) return r - 1 + n - 1;\n }\n }\n\n return -1;\n \n function cntOnes() {\n let res = 0\n for(const e of nums) {\n if(e === 1) res++\n }\n return res\n }\n function gcd(a, b) {\n return b ? gcd(b, a % b) : a\n }\n};" ]
2,656
maximum-sum-with-exactly-k-elements
[]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var maximizeSum = function(nums, k) { };
You are given a 0-indexed integer array nums and an integer k. Your task is to perform the following operation exactly k times in order to maximize your score: Select an element m from nums. Remove the selected element m from the array. Add a new element with a value of m + 1 to the array. Increase your score by m. Return the maximum score you can achieve after performing the operation exactly k times.   Example 1: Input: nums = [1,2,3,4,5], k = 3 Output: 18 Explanation: We need to choose exactly 3 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [1,2,3,4,6] For the second iteration, we choose 6. Then sum is 5 + 6 and nums = [1,2,3,4,7] For the third iteration, we choose 7. Then sum is 5 + 6 + 7 = 18 and nums = [1,2,3,4,8] So, we will return 18. It can be proven, that 18 is the maximum answer that we can achieve. Example 2: Input: nums = [5,5,5], k = 2 Output: 11 Explanation: We need to choose exactly 2 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [5,5,6] For the second iteration, we choose 6. Then sum is 5 + 6 = 11 and nums = [5,5,7] So, we will return 11. It can be proven, that 11 is the maximum answer that we can achieve.   Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100 1 <= k <= 100  
Easy
[ "array", "greedy" ]
null
[]
2,657
find-the-prefix-common-array-of-two-arrays
[ "Consider keeping a frequency array that stores the count of occurrences of each number till index i.", "If a number occurred two times, it means it occurred in both A and B since they’re both permutations so add one to the answer." ]
/** * @param {number[]} A * @param {number[]} B * @return {number[]} */ var findThePrefixCommonArray = function(A, B) { };
You are given two 0-indexed integer permutations A and B of length n. A prefix common array of A and B is an array C such that C[i] is equal to the count of numbers that are present at or before the index i in both A and B. Return the prefix common array of A and B. A sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.   Example 1: Input: A = [1,3,2,4], B = [3,1,2,4] Output: [0,2,3,4] Explanation: At i = 0: no number is common, so C[0] = 0. At i = 1: 1 and 3 are common in A and B, so C[1] = 2. At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3. At i = 3: 1, 2, 3, and 4 are common in A and B, so C[3] = 4. Example 2: Input: A = [2,3,1], B = [3,1,2] Output: [0,1,3] Explanation: At i = 0: no number is common, so C[0] = 0. At i = 1: only 3 is common in A and B, so C[1] = 1. At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3.   Constraints: 1 <= A.length == B.length == n <= 50 1 <= A[i], B[i] <= n It is guaranteed that A and B are both a permutation of n integers.
Medium
[ "array", "hash-table" ]
null
[]
2,658
maximum-number-of-fish-in-a-grid
[ "Run DFS from each non-zero cell.", "Each time you pick a cell to start from, add up the number of fish contained in the cells you visit." ]
/** * @param {number[][]} grid * @return {number} */ var findMaxFish = function(grid) { };
You are given a 0-indexed 2D matrix grid of size m x n, where (r, c) represents: A land cell if grid[r][c] = 0, or A water cell containing grid[r][c] fish, if grid[r][c] > 0. A fisher can start at any water cell (r, c) and can do the following operations any number of times: Catch all the fish at cell (r, c), or Move to any adjacent water cell. Return the maximum number of fish the fisher can catch if he chooses his starting cell optimally, or 0 if no water cell exists. An adjacent cell of the cell (r, c), is one of the cells (r, c + 1), (r, c - 1), (r + 1, c) or (r - 1, c) if it exists.   Example 1: Input: grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]] Output: 7 Explanation: The fisher can start at cell (1,3) and collect 3 fish, then move to cell (2,3) and collect 4 fish. Example 2: Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] Output: 1 Explanation: The fisher can start at cells (0,0) or (3,3) and collect a single fish.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 10 0 <= grid[i][j] <= 10
Medium
[ "array", "depth-first-search", "breadth-first-search", "union-find", "matrix" ]
[ "const deepCopy2DArray = (g) => {\n let d = []\n for (const a of g) d.push([...a])\n return d\n}\n\nconst dx = [1, -1, 0, 0],\n dy = [0, 0, 1, -1]\nconst getAllAreasCoordinates = (g) => {\n const forbid = 0,\n floodFillMakeConnected = '*' // forbid is land cell\n let n = g.length,\n m = g[0].length,\n res = []\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (g[i][j] != forbid) {\n let q = [[i, j]],\n area = []\n while (q.length) {\n let [x, y] = q.shift()\n for (let k = 0; k < 4; k++) {\n let nx = x + dx[k],\n ny = y + dy[k]\n if (\n nx < 0 ||\n nx >= n ||\n ny < 0 ||\n ny >= m ||\n g[nx][ny] == forbid ||\n g[nx][ny] == floodFillMakeConnected\n )\n continue\n g[nx][ny] = floodFillMakeConnected\n area.push([nx, ny])\n q.push([nx, ny])\n }\n }\n if (area.length == 0 && g[i][j] != floodFillMakeConnected)\n area.push([i, j])\n res.push(area)\n }\n }\n }\n return res\n}\n\n\nconst findMaxFish = (g) => {\n let areas = getAllAreasCoordinates(deepCopy2DArray(g)),\n res = 0\n for (const area of areas) {\n let sum = 0\n for (const [x, y] of area) sum += g[x][y]\n res = Math.max(res, sum)\n }\n return res\n}" ]
2,659
make-array-empty
[ "Understand the order in which the indices are removed from the array.", "We don’t really need to delete or move the elements, only the array length matters.", "Upon removing an index, decide how many steps it takes to move to the next one.", "Use a data structure to speed up the calculation." ]
/** * @param {number[]} nums * @return {number} */ var countOperationsToEmptyArray = function(nums) { };
You are given an integer array nums containing distinct numbers, and you can perform the following operations until the array is empty: If the first element has the smallest value, remove it Otherwise, put the first element at the end of the array. Return an integer denoting the number of operations it takes to make nums empty.   Example 1: Input: nums = [3,4,-1] Output: 5 Operation Array 1 [4, -1, 3] 2 [-1, 3, 4] 3 [3, 4] 4 [4] 5 [] Example 2: Input: nums = [1,2,4,3] Output: 5 Operation Array 1 [2, 4, 3] 2 [4, 3] 3 [3, 4] 4 [4] 5 [] Example 3: Input: nums = [1,2,3] Output: 3 Operation Array 1 [2, 3] 2 [3] 3 []   Constraints: 1 <= nums.length <= 105 -109 <= nums[i] <= 109 All values in nums are distinct.
Hard
[ "array", "binary-search", "greedy", "binary-indexed-tree", "segment-tree", "sorting", "ordered-set" ]
null
[]
2,660
determine-the-winner-of-a-bowling-game
[ "Think about simulating the process to calculate the answer.", "Iterate over each element and check the previous two elements. See if one of them is 10 and can affect the score." ]
/** * @param {number[]} player1 * @param {number[]} player2 * @return {number} */ var isWinner = function(player1, player2) { };
You are given two 0-indexed integer arrays player1 and player2, that represent the number of pins that player 1 and player 2 hit in a bowling game, respectively. The bowling game consists of n turns, and the number of pins in each turn is exactly 10. Assume a player hit xi pins in the ith turn. The value of the ith turn for the player is: 2xi if the player hit 10 pins in any of the previous two turns. Otherwise, It is xi. The score of the player is the sum of the values of their n turns. Return 1 if the score of player 1 is more than the score of player 2, 2 if the score of player 2 is more than the score of player 1, and 0 in case of a draw.   Example 1: Input: player1 = [4,10,7,9], player2 = [6,5,2,3] Output: 1 Explanation: The score of player1 is 4 + 10 + 2*7 + 2*9 = 46. The score of player2 is 6 + 5 + 2 + 3 = 16. Score of player1 is more than the score of player2, so, player1 is the winner, and the answer is 1. Example 2: Input: player1 = [3,5,7,6], player2 = [8,10,10,2] Output: 2 Explanation: The score of player1 is 3 + 5 + 7 + 6 = 21. The score of player2 is 8 + 10 + 2*10 + 2*2 = 42. Score of player2 is more than the score of player1, so, player2 is the winner, and the answer is 2. Example 3: Input: player1 = [2,3], player2 = [4,1] Output: 0 Explanation: The score of player1 is 2 + 3 = 5 The score of player2 is 4 + 1 = 5 The score of player1 equals to the score of player2, so, there is a draw, and the answer is 0.   Constraints: n == player1.length == player2.length 1 <= n <= 1000 0 <= player1[i], player2[i] <= 10
Easy
[ "array", "simulation" ]
[ "var isWinner = function(player1, player2) {\n const n = player1.length\n let sum1 = 0, sum2 = 0\n // 1\n for(let i = 0; i < n; i++) {\n const cur = player1[i]\n sum1 += cur\n if( (i >= 1 && player1[i - 1] === 10) || (i >= 2 && player1[i - 2] === 10) ) {\n sum1 += cur\n }\n }\n \n \n // 2\n for(let i = 0; i < n; i++) {\n const cur = player2[i]\n sum2 += cur\n if( (i >= 1 && player2[i - 1] === 10) || (i >= 2 && player2[i - 2] === 10) ) {\n sum2 += cur\n }\n }\n \n return sum1 === sum2 ? 0 : (sum1 > sum2 ? 1 : 2)\n};" ]
2,661
first-completely-painted-row-or-column
[ "Can we use a frequency array?", "Pre-process the positions of the values in the matrix.", "Traverse the array and increment the corresponding row and column frequency using the pre-processed positions.", "If the row frequency becomes equal to the number of columns, or vice-versa return the current index." ]
/** * @param {number[]} arr * @param {number[][]} mat * @return {number} */ var firstCompleteIndex = function(arr, mat) { };
You are given a 0-indexed integer array arr, and an m x n integer matrix mat. arr and mat both contain all the integers in the range [1, m * n]. Go through each index i in arr starting from index 0 and paint the cell in mat containing the integer arr[i]. Return the smallest index i at which either a row or a column will be completely painted in mat.   Example 1: Input: arr = [1,3,4,2], mat = [[1,4],[2,3]] Output: 2 Explanation: The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2]. Example 2: Input: arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]] Output: 3 Explanation: The second column becomes fully painted at arr[3].   Constraints: m == mat.length n = mat[i].length arr.length == m * n 1 <= m, n <= 105 1 <= m * n <= 105 1 <= arr[i], mat[r][c] <= m * n All the integers of arr are unique. All the integers of mat are unique.
Medium
[ "array", "hash-table", "matrix" ]
[ "const firstCompleteIndex = function(arr, mat) {\n const map = new Map()\n const m = mat.length, n = mat[0].length\n \n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n map.set(mat[i][j], [i, j])\n }\n }\n \n const rows = Array(m).fill(0)\n const cols = Array(n).fill(0)\n \n for(let i = 0; i < m * n; i++) {\n const e = arr[i]\n const [r, c] = map.get(e)\n rows[r]++\n cols[c]++\n // console.log(r, c, rows, cols, m, n)\n if(rows[r] === n) return i\n if(cols[c] === m) return i\n }\n \n};" ]
2,662
minimum-cost-of-a-path-with-special-roads
[ "It can be proven that it is optimal to go only to the positions that are either the start or the end of a special road or the target position.", "Consider all positions given to you as nodes in a graph, and the edges of the graph are the special roads.", "Now the problem is equivalent to finding the shortest path in a directed graph." ]
/** * @param {number[]} start * @param {number[]} target * @param {number[][]} specialRoads * @return {number} */ var minimumCost = function(start, target, specialRoads) { };
You are given an array start where start = [startX, startY] represents your initial position (startX, startY) in a 2D space. You are also given the array target where target = [targetX, targetY] represents your target position (targetX, targetY). The cost of going from a position (x1, y1) to any other position in the space (x2, y2) is |x2 - x1| + |y2 - y1|. There are also some special roads. You are given a 2D array specialRoads where specialRoads[i] = [x1i, y1i, x2i, y2i, costi] indicates that the ith special road can take you from (x1i, y1i) to (x2i, y2i) with a cost equal to costi. You can use each special road any number of times. Return the minimum cost required to go from (startX, startY) to (targetX, targetY).   Example 1: Input: start = [1,1], target = [4,5], specialRoads = [[1,2,3,3,2],[3,4,4,5,1]] Output: 5 Explanation: The optimal path from (1,1) to (4,5) is the following: - (1,1) -> (1,2). This move has a cost of |1 - 1| + |2 - 1| = 1. - (1,2) -> (3,3). This move uses the first special edge, the cost is 2. - (3,3) -> (3,4). This move has a cost of |3 - 3| + |4 - 3| = 1. - (3,4) -> (4,5). This move uses the second special edge, the cost is 1. So the total cost is 1 + 2 + 1 + 1 = 5. It can be shown that we cannot achieve a smaller total cost than 5. Example 2: Input: start = [3,2], target = [5,7], specialRoads = [[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]] Output: 7 Explanation: It is optimal to not use any special edges and go directly from the starting to the ending position with a cost |5 - 3| + |7 - 2| = 7.   Constraints: start.length == target.length == 2 1 <= startX <= targetX <= 105 1 <= startY <= targetY <= 105 1 <= specialRoads.length <= 200 specialRoads[i].length == 5 startX <= x1i, x2i <= targetX startY <= y1i, y2i <= targetY 1 <= costi <= 105
Medium
[ "array", "graph", "heap-priority-queue", "shortest-path" ]
[ "var minimumCost = function (start, target, specialRoads) {\n const INF = 1e9 + 10\n let n = specialRoads.length\n const { abs, min, max } = Math\n\n // Initialize the distance of each special road to infinity\n const d = Array(n).fill(INF)\n\n // Create a priority queue and push the distance from start to each special road\n const pq = new PQ((a, b) => a[0] < b[0])\n for (let i = 0; i < n; i++) {\n d[i] =\n abs(start[0] - specialRoads[i][0]) +\n abs(start[1] - specialRoads[i][1]) +\n specialRoads[i][4]\n pq.push([d[i], i])\n }\n\n // Initialize the answer with the manhattan distance between start and target\n let ans = abs(start[0] - target[0]) + abs(start[1] - target[1])\n\n // Continue to search for the shortest path until the priority queue is empty\n while (pq.size()) {\n // Pop the pair with smallest distance\n let [d_c, c] = pq.pop()\n\n // If the distance stored in d is not equal to the current distance d_c, skip this node\n if (d_c != d[c]) continue\n\n // Update the answer by finding the distance from the current special road to the target\n ans = min(\n ans,\n d_c +\n abs(target[0] - specialRoads[c][2]) +\n abs(target[1] - specialRoads[c][3])\n )\n\n // For each special road that can be reached from the current special road, update its distance\n for (let nxt = 0; nxt < n; nxt++) {\n let w =\n abs(specialRoads[c][2] - specialRoads[nxt][0]) +\n abs(specialRoads[c][3] - specialRoads[nxt][1]) +\n specialRoads[nxt][4]\n if (d_c + w < d[nxt]) {\n d[nxt] = d_c + w\n pq.push([d[nxt], nxt])\n }\n }\n }\n\n // Return the minimum cost of reaching the target\n return ans\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,663
lexicographically-smallest-beautiful-string
[ "If the string does not contain any palindromic substrings of lengths 2 and 3, then the string does not contain any palindromic substrings at all.", "Iterate from right to left and if it is possible to increase character at index i without creating any palindromic substrings of lengths 2 and 3, then increase it.", "After increasing the character at index i, set every character after index i equal to character a. With this, we will ensure that we have created a lexicographically larger string than s, which does not contain any palindromes before index i and is lexicographically the smallest.", "Finally, we are just left with a case to fix palindromic substrings, which come after index i. This can be done with a similar method mentioned in the second hint." ]
/** * @param {string} s * @param {number} k * @return {string} */ var smallestBeautifulString = function(s, k) { };
A string is beautiful if: It consists of the first k letters of the English lowercase alphabet. It does not contain any substring of length 2 or more which is a palindrome. You are given a beautiful string s of length n and a positive integer k. Return the lexicographically smallest string of length n, which is larger than s and is beautiful. If there is no such string, return an empty string. A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, "abcd" is lexicographically larger than "abcc" because the first position they differ is at the fourth character, and d is greater than c.   Example 1: Input: s = "abcz", k = 26 Output: "abda" Explanation: The string "abda" is beautiful and lexicographically larger than the string "abcz". It can be proven that there is no string that is lexicographically larger than the string "abcz", beautiful, and lexicographically smaller than the string "abda". Example 2: Input: s = "dc", k = 4 Output: "" Explanation: It can be proven that there is no string that is lexicographically larger than the string "dc" and is beautiful.   Constraints: 1 <= n == s.length <= 105 4 <= k <= 26 s is a beautiful string.
Hard
[ "string", "greedy" ]
[ "const smallestBeautifulString = function(s, k) {\n const n = s.length\n const original = s\n const chars = s.split(''), a = 'a'.charCodeAt(0), z = 'z'.charCodeAt(0)\n const codeToCh = code => String.fromCharCode(code)\n let flag = false\n for(let i = n - 1; i >= 0; i--) {\n const code = chars[i].charCodeAt(0)\n for(let j = code + 1; j < a + k && j <= z; j++) {\n if(!valid(i, codeToCh(j))) continue\n chars[i] = codeToCh(j)\n for(let nxt = i + 1; nxt < n; nxt++) {\n for(let c = a; c < a + k; c++) {\n if(valid(nxt, codeToCh(c))) {\n chars[nxt] = codeToCh(c)\n break\n }\n }\n }\n flag = true\n break\n }\n if(flag) break\n }\n \n const res = chars.join('')\n if(res === original) return ''\n return res\n \n function valid(idx, ch) {\n if(idx >= 1 && ch === chars[idx - 1]) return false\n if(idx >= 2 && ch === chars[idx - 2]) return false\n return true\n }\n};", "const smallestBeautifulString = function (s, k) {\n const chars = s.split('')\n\n for (let i = chars.length - 1; i >= 0; i--) {\n chars[i] = String.fromCharCode(chars[i].charCodeAt(0) + 1)\n while (containsPalindrome(chars, i)) {\n chars[i] = String.fromCharCode(chars[i].charCodeAt(0) + 1)\n }\n if (chars[i] < String.fromCharCode('a'.charCodeAt(0) + k)) {\n // If s[i] is among the first k letters, then change the letters after\n // s[i] to the smallest ones that don't form any palindrome substring.\n return changeSuffix(chars, i + 1)\n }\n }\n\n return ''\n\n // Returns true if chars[0..i] contains palindrome.\n function containsPalindrome(chars, i) {\n return (\n (i > 0 && chars[i] == chars[i - 1]) || (i > 1 && chars[i] == chars[i - 2])\n )\n }\n\n // Returns string where chars[i..] replaced with the smallest letters that\n // don't form any palindrome substring.\n function changeSuffix(chars, i) {\n for (let j = i; j < chars.length; j++) {\n chars[j] = 'a'\n while (containsPalindrome(chars, j)) {\n chars[j] = String.fromCharCode(chars[j].charCodeAt(0) + 1)\n }\n }\n return chars.join('')\n }\n}" ]
2,670
find-the-distinct-difference-array
[ "Which data structure will help you maintain distinct elements?", "Iterate over all possible prefix sizes. Then, use a nested loop to add the elements of the prefix to a set, and another nested loop to add the elements of the suffix to another set." ]
/** * @param {number[]} nums * @return {number[]} */ var distinctDifferenceArray = function(nums) { };
You are given a 0-indexed array nums of length n. The distinct difference array of nums is an array diff of length n such that diff[i] is equal to the number of distinct elements in the suffix nums[i + 1, ..., n - 1] subtracted from the number of distinct elements in the prefix nums[0, ..., i]. Return the distinct difference array of nums. Note that nums[i, ..., j] denotes the subarray of nums starting at index i and ending at index j inclusive. Particularly, if i > j then nums[i, ..., j] denotes an empty subarray.   Example 1: Input: nums = [1,2,3,4,5] Output: [-3,-1,1,3,5] Explanation: For index i = 0, there is 1 element in the prefix and 4 distinct elements in the suffix. Thus, diff[0] = 1 - 4 = -3. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 3 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 3 - 2 = 1. For index i = 3, there are 4 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 4 - 1 = 3. For index i = 4, there are 5 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 5 - 0 = 5. Example 2: Input: nums = [3,2,3,4,2] Output: [-2,-1,0,2,3] Explanation: For index i = 0, there is 1 element in the prefix and 3 distinct elements in the suffix. Thus, diff[0] = 1 - 3 = -2. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 2 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 2 - 2 = 0. For index i = 3, there are 3 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 3 - 1 = 2. For index i = 4, there are 3 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 3 - 0 = 3.   Constraints: 1 <= n == nums.length <= 50 1 <= nums[i] <= 50
Easy
[ "array", "hash-table" ]
[ "const distinctDifferenceArray = function(nums) {\n const res = []\n \n for(let i = 0, n = nums.length; i < n; i++) {\n const pre = nums.slice(0, i + 1), suf = nums.slice(i + 1)\n res[i] = new Set(pre).size - new Set(suf).size\n }\n \n return res\n};" ]
2,671
frequency-tracker
[ "Put all the numbers in a hash map (or just an integer array given the number range is small) to maintain each number’s frequency dynamically.", "Put each frequency in another hash map (or just an integer array given the range is small, note there are only 200000 calls in total) to maintain each kind of frequency dynamically.", "Keep the 2 hash maps in sync." ]
var FrequencyTracker = function() { }; /** * @param {number} number * @return {void} */ FrequencyTracker.prototype.add = function(number) { }; /** * @param {number} number * @return {void} */ FrequencyTracker.prototype.deleteOne = function(number) { }; /** * @param {number} frequency * @return {boolean} */ FrequencyTracker.prototype.hasFrequency = function(frequency) { }; /** * Your FrequencyTracker object will be instantiated and called as such: * var obj = new FrequencyTracker() * obj.add(number) * obj.deleteOne(number) * var param_3 = obj.hasFrequency(frequency) */
Design a data structure that keeps track of the values in it and answers some queries regarding their frequencies. Implement the FrequencyTracker class. FrequencyTracker(): Initializes the FrequencyTracker object with an empty array initially. void add(int number): Adds number to the data structure. void deleteOne(int number): Deletes one occurrence of number from the data structure. The data structure may not contain number, and in this case nothing is deleted. bool hasFrequency(int frequency): Returns true if there is a number in the data structure that occurs frequency number of times, otherwise, it returns false.   Example 1: Input ["FrequencyTracker", "add", "add", "hasFrequency"] [[], [3], [3], [2]] Output [null, null, null, true] Explanation FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.add(3); // The data structure now contains [3, 3] frequencyTracker.hasFrequency(2); // Returns true, because 3 occurs twice Example 2: Input ["FrequencyTracker", "add", "deleteOne", "hasFrequency"] [[], [1], [1], [1]] Output [null, null, null, false] Explanation FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(1); // The data structure now contains [1] frequencyTracker.deleteOne(1); // The data structure becomes empty [] frequencyTracker.hasFrequency(1); // Returns false, because the data structure is empty Example 3: Input ["FrequencyTracker", "hasFrequency", "add", "hasFrequency"] [[], [2], [3], [1]] Output [null, false, null, true] Explanation FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.hasFrequency(2); // Returns false, because the data structure is empty frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.hasFrequency(1); // Returns true, because 3 occurs once   Constraints: 1 <= number <= 105 1 <= frequency <= 105 At most, 2 * 105 calls will be made to add, deleteOne, and hasFrequency in total.
Medium
[ "hash-table", "design" ]
[ "let cnt = {}, freq = {} \nvar FrequencyTracker = function() {\n cnt = {}\n freq = {}\n};\n\n\nFrequencyTracker.prototype.add = function(number) {\n const c = cnt[number] ?? 0\n if(cnt[number] == null) cnt[number] = 0\n if(freq[c] == null) freq[c] = 0\n --freq[cnt[number]];\n if(cnt[number] == null) cnt[number] = 0\n ++cnt[number];\n if(freq[cnt[number]] == null) freq[cnt[number]] = 0\n ++freq[cnt[number]];\n};\n\n\nFrequencyTracker.prototype.deleteOne = function(number) {\n if(cnt[number] == null) cnt[number] = 0\n if (cnt[number] > 0) {\n if(freq[cnt[number]] == null) freq[cnt[number]] = 0\n --freq[cnt[number]];\n --cnt[number];\n if(freq[cnt[number]] == null) freq[cnt[number]] = 0\n ++freq[cnt[number]];\n }\n};\n\n\nFrequencyTracker.prototype.hasFrequency = function(frequency) {\n return freq[frequency] > 0;\n};" ]
2,672
number-of-adjacent-elements-with-the-same-color
[ "Since at each query, only one element is being recolored, we just need to focus on its neighbors.", "If an element that is changed on the i-th query had the same color as its right element answer decreases by 1. Similarly contributes its left element too.", "After changing the color, if the element has the same color as its right element answer increases by 1. Similarly contributes its left element too." ]
/** * @param {number} n * @param {number[][]} queries * @return {number[]} */ var colorTheArray = function(n, queries) { };
There is a 0-indexed array nums of length n. Initially, all elements are uncolored (has a value of 0). You are given a 2D integer array queries where queries[i] = [indexi, colori]. For each query, you color the index indexi with the color colori in the array nums. Return an array answer of the same length as queries where answer[i] is the number of adjacent elements with the same color after the ith query. More formally, answer[i] is the number of indices j, such that 0 <= j < n - 1 and nums[j] == nums[j + 1] and nums[j] != 0 after the ith query.   Example 1: Input: n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]] Output: [0,1,1,0,2] Explanation: Initially array nums = [0,0,0,0], where 0 denotes uncolored elements of the array. - After the 1st query nums = [2,0,0,0]. The count of adjacent elements with the same color is 0. - After the 2nd query nums = [2,2,0,0]. The count of adjacent elements with the same color is 1. - After the 3rd query nums = [2,2,0,1]. The count of adjacent elements with the same color is 1. - After the 4th query nums = [2,1,0,1]. The count of adjacent elements with the same color is 0. - After the 5th query nums = [2,1,1,1]. The count of adjacent elements with the same color is 2. Example 2: Input: n = 1, queries = [[0,100000]] Output: [0] Explanation: Initially array nums = [0], where 0 denotes uncolored elements of the array. - After the 1st query nums = [100000]. The count of adjacent elements with the same color is 0.   Constraints: 1 <= n <= 105 1 <= queries.length <= 105 queries[i].length == 2 0 <= indexi <= n - 1 1 <=  colori <= 105
Medium
[ "array" ]
[ "var colorTheArray = function(n, queries) {\n let color = {};\n let ans = [];\n let cnt = 0;\n for (const q of queries) {\n if (get(color, q[0])!=q[1]) {\n if (get(color, q[0])!=0){\n if (get(color, q[0]-1) == get(color, q[0])) --cnt;\n if (get(color, q[0]+1) == get(color, q[0])) --cnt;\n }\n color[q[0]]=q[1];\n if (get(color, q[0]-1) == color[q[0]]) ++cnt;\n if (get(color, q[0]+1) == color[q[0]]) ++cnt;\n }\n ans.push(cnt);\n }\n return ans;\n\n function get(hash, key) {\n return hash[key] == null ? 0 : hash[key]\n }\n};" ]
2,673
make-costs-of-paths-equal-in-a-binary-tree
[ "The path from the root to a leaf that has the maximum cost should not be modified.", "The optimal way is to increase all other paths to make their costs equal to the path with maximum cost." ]
/** * @param {number} n * @param {number[]} cost * @return {number} */ var minIncrements = function(n, cost) { };
You are given an integer n representing the number of nodes in a perfect binary tree consisting of nodes numbered from 1 to n. The root of the tree is node 1 and each node i in the tree has two children where the left child is the node 2 * i and the right child is 2 * i + 1. Each node in the tree also has a cost represented by a given 0-indexed integer array cost of size n where cost[i] is the cost of node i + 1. You are allowed to increment the cost of any node by 1 any number of times. Return the minimum number of increments you need to make the cost of paths from the root to each leaf node equal. Note: A perfect binary tree is a tree where each node, except the leaf nodes, has exactly 2 children. The cost of a path is the sum of costs of nodes in the path.   Example 1: Input: n = 7, cost = [1,5,2,2,3,3,1] Output: 6 Explanation: We can do the following increments: - Increase the cost of node 4 one time. - Increase the cost of node 3 three times. - Increase the cost of node 7 two times. Each path from the root to a leaf will have a total cost of 9. The total increments we did is 1 + 3 + 2 = 6. It can be shown that this is the minimum answer we can achieve. Example 2: Input: n = 3, cost = [5,3,3] Output: 0 Explanation: The two paths already have equal total costs, so no increments are needed.   Constraints: 3 <= n <= 105 n + 1 is a power of 2 cost.length == n 1 <= cost[i] <= 104
Medium
[ "array", "dynamic-programming", "greedy", "tree", "binary-tree" ]
[ "var minIncrements = function(n, cost) {\n let ans = 0;\n const {abs, max} = Math\n for (let i = n >> 1; i > 0; ) {\n let r = i<<1, l = r-1;\n ans += abs(cost[l]-cost[r]);\n cost[--i] += max(cost[l], cost[r]);\n }\n return ans;\n};" ]
2,678
number-of-senior-citizens
[ "Convert the value at index 11 and 12 to a numerical value.", "The age of the person at index i is equal to details[i][11]*10+details[i][12]." ]
/** * @param {string[]} details * @return {number} */ var countSeniors = function(details) { };
You are given a 0-indexed array of strings details. Each element of details provides information about a given passenger compressed into a string of length 15. The system is such that: The first ten characters consist of the phone number of passengers. The next character denotes the gender of the person. The following two characters are used to indicate the age of the person. The last two characters determine the seat allotted to that person. Return the number of passengers who are strictly more than 60 years old.   Example 1: Input: details = ["7868190130M7522","5303914400F9211","9273338290F4010"] Output: 2 Explanation: The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old. Example 2: Input: details = ["1313579440F2036","2921522980M5644"] Output: 0 Explanation: None of the passengers are older than 60.   Constraints: 1 <= details.length <= 100 details[i].length == 15 details[i] consists of digits from '0' to '9'. details[i][10] is either 'M' or 'F' or 'O'. The phone numbers and seat numbers of the passengers are distinct.
Easy
[ "array", "string" ]
null
[]
2,679
sum-in-a-matrix
[ "Sort the numbers in each row in decreasing order.", "The answer is the summation of the max number in every column after sorting the rows." ]
/** * @param {number[][]} nums * @return {number} */ var matrixSum = function(nums) { };
You are given a 0-indexed 2D integer array nums. Initially, your score is 0. Perform the following operations until the matrix becomes empty: From each row in the matrix, select the largest number and remove it. In the case of a tie, it does not matter which number is chosen. Identify the highest number amongst all those removed in step 1. Add that number to your score. Return the final score.   Example 1: Input: nums = [[7,2,1],[6,4,2],[6,5,3],[3,2,1]] Output: 15 Explanation: In the first operation, we remove 7, 6, 6, and 3. We then add 7 to our score. Next, we remove 2, 4, 5, and 2. We add 5 to our score. Lastly, we remove 1, 2, 3, and 1. We add 3 to our score. Thus, our final score is 7 + 5 + 3 = 15. Example 2: Input: nums = [[1]] Output: 1 Explanation: We remove 1 and add it to the answer. We return 1.   Constraints: 1 <= nums.length <= 300 1 <= nums[i].length <= 500 0 <= nums[i][j] <= 103
Medium
[ "array", "sorting", "heap-priority-queue", "matrix", "simulation" ]
null
[]
2,680
maximum-or
[ "The optimal solution should apply all the k operations on a single number.", "Calculate the prefix or and the suffix or and perform k operations over each element, and maximize the answer." ]
/** * @param {number[]} nums * @param {number} k * @return {number} */ var maximumOr = function(nums, k) { };
You are given a 0-indexed integer array nums of length n and an integer k. In an operation, you can choose an element and multiply it by 2. Return the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1] that can be obtained after applying the operation on nums at most k times. Note that a | b denotes the bitwise or between two integers a and b.   Example 1: Input: nums = [12,9], k = 1 Output: 30 Explanation: If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30. Example 2: Input: nums = [8,1,2], k = 2 Output: 35 Explanation: If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109 1 <= k <= 15
Medium
[ "array", "greedy", "bit-manipulation", "prefix-sum" ]
null
[]
2,681
power-of-heroes
[ "Try something with sorting the array.", "For a pair of array elements nums[i] and nums[j] (i < j), the power would be nums[i]*nums[j]^2 regardless of how many elements in between are included.", "The number of subsets with the above as power will correspond to 2^(j-i-1).", "Try collecting the terms for nums[0], nums[1], …, nums[j-1] when computing the power of heroes ending at index j to get the power in a single pass." ]
/** * @param {number[]} nums * @return {number} */ var sumOfPower = function(nums) { };
You are given a 0-indexed integer array nums representing the strength of some heroes. The power of a group of heroes is defined as follows: Let i0, i1, ... ,ik be the indices of the heroes in a group. Then, the power of this group is max(nums[i0], nums[i1], ... ,nums[ik])2 * min(nums[i0], nums[i1], ... ,nums[ik]). Return the sum of the power of all non-empty groups of heroes possible. Since the sum could be very large, return it modulo 109 + 7.   Example 1: Input: nums = [2,1,4] Output: 141 Explanation: 1st group: [2] has power = 22 * 2 = 8. 2nd group: [1] has power = 12 * 1 = 1. 3rd group: [4] has power = 42 * 4 = 64. 4th group: [2,1] has power = 22 * 1 = 4. 5th group: [2,4] has power = 42 * 2 = 32. 6th group: [1,4] has power = 42 * 1 = 16. ​​​​​​​7th group: [2,1,4] has power = 42​​​​​​​ * 1 = 16. The sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141. Example 2: Input: nums = [1,1,1] Output: 7 Explanation: A total of 7 groups are possible, and the power of each group will be 1. Therefore, the sum of the powers of all groups is 7.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109
Hard
[ "array", "math", "sorting", "prefix-sum" ]
[ "const sumOfPower = function(nums) {\n const n = nums.length, mod = BigInt(1e9 + 7)\n let res = 0n, sum = 0n\n nums.sort((a, b) => a - b)\n \n for(let i = 0; i < n; i++) {\n const e = BigInt(nums[i])\n const square = (e * e) % mod\n \n res = (res + sum * square + e * square) % mod\n sum = (sum * 2n + e) % mod \n }\n \n return res\n};" ]
2,682
find-the-losers-of-the-circular-game
[ "Simulate the whole game until a player receives the ball for the second time." ]
/** * @param {number} n * @param {number} k * @return {number[]} */ var circularGameLosers = function(n, k) { };
There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. The rules of the game are as follows: 1st friend receives the ball. After that, 1st friend passes it to the friend who is k steps away from them in the clockwise direction. After that, the friend who receives the ball should pass it to the friend who is 2 * k steps away from them in the clockwise direction. After that, the friend who receives the ball should pass it to the friend who is 3 * k steps away from them in the clockwise direction, and so on and so forth. In other words, on the ith turn, the friend holding the ball should pass it to the friend who is i * k steps away from them in the clockwise direction. The game is finished when some friend receives the ball for the second time. The losers of the game are friends who did not receive the ball in the entire game. Given the number of friends, n, and an integer k, return the array answer, which contains the losers of the game in the ascending order.   Example 1: Input: n = 5, k = 2 Output: [4,5] Explanation: The game goes as follows: 1) Start at 1st friend and pass the ball to the friend who is 2 steps away from them - 3rd friend. 2) 3rd friend passes the ball to the friend who is 4 steps away from them - 2nd friend. 3) 2nd friend passes the ball to the friend who is 6 steps away from them - 3rd friend. 4) The game ends as 3rd friend receives the ball for the second time. Example 2: Input: n = 4, k = 4 Output: [2,3,4] Explanation: The game goes as follows: 1) Start at the 1st friend and pass the ball to the friend who is 4 steps away from them - 1st friend. 2) The game ends as 1st friend receives the ball for the second time.   Constraints: 1 <= k <= n <= 50
Easy
[ "array", "hash-table", "simulation" ]
[ "var circularGameLosers = function(n, k) {\n const set = new Set()\n let i = 0, turn = 1\n while(!set.has(i + 1)) {\n set.add(i + 1)\n i = (i + turn * k) % n\n turn++\n }\n const res = []\n for(let j = 1; j<=n;j++) {\n if(!set.has(j)) res.push(j)\n }\n return res\n};" ]
2,683
neighboring-bitwise-xor
[ "Understand that from the original element, we are using each element twice to construct the derived array", "The xor-sum of the derived array should be 0 since there is always a duplicate occurrence of each element." ]
/** * @param {number[]} derived * @return {boolean} */ var doesValidArrayExist = function(derived) { };
A 0-indexed array derived with length n is derived by computing the bitwise XOR (⊕) of adjacent values in a binary array original of length n. Specifically, for each index i in the range [0, n - 1]: If i = n - 1, then derived[i] = original[i] ⊕ original[0]. Otherwise, derived[i] = original[i] ⊕ original[i + 1]. Given an array derived, your task is to determine whether there exists a valid binary array original that could have formed derived. Return true if such an array exists or false otherwise. A binary array is an array containing only 0's and 1's   Example 1: Input: derived = [1,1,0] Output: true Explanation: A valid original array that gives derived is [0,1,0]. derived[0] = original[0] ⊕ original[1] = 0 ⊕ 1 = 1 derived[1] = original[1] ⊕ original[2] = 1 ⊕ 0 = 1 derived[2] = original[2] ⊕ original[0] = 0 ⊕ 0 = 0 Example 2: Input: derived = [1,1] Output: true Explanation: A valid original array that gives derived is [0,1]. derived[0] = original[0] ⊕ original[1] = 1 derived[1] = original[1] ⊕ original[0] = 1 Example 3: Input: derived = [1,0] Output: false Explanation: There is no valid original array that gives derived.   Constraints: n == derived.length 1 <= n <= 105 The values in derived are either 0's or 1's
Medium
[ "array", "bit-manipulation" ]
[ "var doesValidArrayExist = function(derived) {\n\tlet n = derived.length\n\tlet r1 = Array(n).fill(0)\n\tfor (let i = 0; i < n-1; i++) {\n\t\tr1[i+1] = derived[i] ^ r1[i]\n\t}\n\tif (r1[n-1]^r1[0] == derived[n-1]) {\n\t\treturn true\n\t}\n\tr1[0] = 1\n\tfor (let i = 0; i < n-1; i++) {\n\t\tr1[i+1] = derived[i] ^ r1[i]\n\t}\n\tif (r1[n-1]^r1[0] == derived[n-1]) {\n\t\treturn true\n\t}\n\treturn false\n};" ]
2,684
maximum-number-of-moves-in-a-grid
[ "Consider using dynamic programming to find the maximum number of moves that can be made from each cell.", "The final answer will be the maximum value in cells of the first column." ]
/** * @param {number[][]} grid * @return {number} */ var maxMoves = function(grid) { };
You are given a 0-indexed m x n matrix grid consisting of positive integers. You can start at any cell in the first column of the matrix, and traverse the grid in the following way: From a cell (row, col), you can move to any of the cells: (row - 1, col + 1), (row, col + 1) and (row + 1, col + 1) such that the value of the cell you move to, should be strictly bigger than the value of the current cell. Return the maximum number of moves that you can perform.   Example 1: Input: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] Output: 3 Explanation: We can start at the cell (0, 0) and make the following moves: - (0, 0) -> (0, 1). - (0, 1) -> (1, 2). - (1, 2) -> (2, 3). It can be shown that it is the maximum number of moves that can be made. Example 2: Input: grid = [[3,2,4],[2,1,9],[1,1,7]] Output: 0 Explanation: Starting from any cell in the first column we cannot perform any moves.   Constraints: m == grid.length n == grid[i].length 2 <= m, n <= 1000 4 <= m * n <= 105 1 <= grid[i][j] <= 106
Medium
[ "array", "dynamic-programming", "matrix" ]
[ "var maxMoves = function(g) {\n\tlet dirs = [\n\t\t[-1, 1],\n\t\t[0, 1],\n\t\t[1, 1],\n\t]\n let grid = g\n\tlet m = grid.length, n = grid[0].length\n\tlet cachev1 = Array.from({ length: m }, () => Array(n).fill(null))\n const cache = {}\n // const m = g.length; const n = g[0].length\n const dx = [0, -1, 1]; const dy = [1, 1, 1]\n\n let ans = 0\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n ans = Math.max(ans, dfs(i, j))\n }\n }\n return ans\n\n function dfs (i, j) {\n if (cache[`${i}_${j}`]) return cache[`${i}_${j}`]\n if (j === 0) return cache[`${i}_${j}`] = 0\n let s = -1\n for (let k = 0; k < 3; k++) {\n const x = i - dx[k]; const y = j - dy[k]\n if (x >= 0 && x < m && y >= 0 && y < n && g[i][j] > g[x][y]) {\n s = Math.max(s, dfs(x, y))\n }\n }\n if (s === -1) return cache[`${i}_${j}`] = -1\n return cache[`${i}_${j}`] = s + 1\n }\n};" ]
2,685
count-the-number-of-complete-components
[ "Find the connected components of an undirected graph using depth-first search (DFS) or breadth-first search (BFS).", "For each connected component, count the number of nodes and edges in the component.", "A connected component is complete if and only if the number of edges in the component is equal to m*(m-1)/2, where m is the number of nodes in the component." ]
/** * @param {number} n * @param {number[][]} edges * @return {number} */ var countCompleteComponents = function(n, edges) { };
You are given an integer n. There is an undirected graph with n vertices, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting vertices ai and bi. Return the number of complete connected components of the graph. A connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph. A connected component is said to be complete if there exists an edge between every pair of its vertices.   Example 1: Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4]] Output: 3 Explanation: From the picture above, one can see that all of the components of this graph are complete. Example 2: Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]] Output: 1 Explanation: The component containing vertices 0, 1, and 2 is complete since there is an edge between every pair of two vertices. On the other hand, the component containing vertices 3, 4, and 5 is not complete since there is no edge between vertices 4 and 5. Thus, the number of complete components in this graph is 1.   Constraints: 1 <= n <= 50 0 <= edges.length <= n * (n - 1) / 2 edges[i].length == 2 0 <= ai, bi <= n - 1 ai != bi There are no repeated edges.
Medium
[ "depth-first-search", "breadth-first-search", "graph" ]
[ "var countCompleteComponents = function(n, edges) {\n const ma = Array(n).fill(0).map((_, idx) => idx)\n const e = {}\n for (const [x, y] of edges) {\n e[x] ??= new Set()\n e[x].add(y)\n e[y] ??= new Set()\n e[y].add(x)\n merge(x, y)\n }\n const f = []; const fs = {}\n for (let i = 0; i < n; i++) {\n s = get(i)\n f.push(s)\n fs[s] ??= []\n fs[s].push(i)\n }\n\n let ans = 0\n for (const [_, t] of Object.entries(fs)) {\n let ok = true\n for (let i = 0; i < t.length; i++) {\n if (!ok) break\n for (let j = i + 1; j < t.length; j++) {\n if (!e[t[i]].has(t[j])) {\n ok = false\n break\n }\n }\n }\n ans += ok\n }\n return ans\n \n function get(x) {\n if (ma[x] === x) return x\n return ma[x] = get(ma[x])\n }\n function merge (x, y) {\n const fx = get(x); const fy = get(y)\n ma[fx] = fy\n }\n};" ]
2,696
minimum-string-length-after-removing-substrings
[ "Can we use brute force to solve the problem?", "Repeatedly traverse the string to find and remove the substrings “AB” and “CD” until no more occurrences exist." ]
/** * @param {string} s * @return {number} */ var minLength = function(s) { };
You are given a string s consisting only of uppercase English letters. You can apply some operations to this string where, in one operation, you can remove any occurrence of one of the substrings "AB" or "CD" from s. Return the minimum possible length of the resulting string that you can obtain. Note that the string concatenates after removing the substring and could produce new "AB" or "CD" substrings.   Example 1: Input: s = "ABFCACDB" Output: 2 Explanation: We can do the following operations: - Remove the substring "ABFCACDB", so s = "FCACDB". - Remove the substring "FCACDB", so s = "FCAB". - Remove the substring "FCAB", so s = "FC". So the resulting length of the string is 2. It can be shown that it is the minimum length that we can obtain. Example 2: Input: s = "ACBBD" Output: 5 Explanation: We cannot do any operations on the string so the length remains the same.   Constraints: 1 <= s.length <= 100 s consists only of uppercase English letters.
Easy
[ "string", "stack", "simulation" ]
null
[]
2,697
lexicographically-smallest-palindrome
[ "We can make any string a palindrome, by simply making any character at index i equal to the character at index length - i - 1 (using 0-based indexing).", "To make it lexicographically smallest we can change the character with maximum ASCII value to the one with minimum ASCII value." ]
/** * @param {string} s * @return {string} */ var makeSmallestPalindrome = function(s) { };
You are given a string s consisting of lowercase English letters, and you are allowed to perform operations on it. In one operation, you can replace a character in s with another lowercase English letter. Your task is to make s a palindrome with the minimum number of operations possible. If there are multiple palindromes that can be made using the minimum number of operations, make the lexicographically smallest one. 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. Return the resulting palindrome string.   Example 1: Input: s = "egcfe" Output: "efcfe" Explanation: The minimum number of operations to make "egcfe" a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is "efcfe", by changing 'g'. Example 2: Input: s = "abcd" Output: "abba" Explanation: The minimum number of operations to make "abcd" a palindrome is 2, and the lexicographically smallest palindrome string we can get by modifying two characters is "abba". Example 3: Input: s = "seven" Output: "neven" Explanation: The minimum number of operations to make "seven" a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is "neven".   Constraints: 1 <= s.length <= 1000 s consists of only lowercase English letters.
Easy
[ "two-pointers", "string" ]
null
[]
2,698
find-the-punishment-number-of-an-integer
[ "Can we generate all possible partitions of a number?", "Use a recursive algorithm that splits the number into two parts, generates all possible partitions of each part recursively, and then combines them in all possible ways." ]
/** * @param {number} n * @return {number} */ var punishmentNumber = function(n) { };
Given a positive integer n, return the punishment number of n. The punishment number of n is defined as the sum of the squares of all integers i such that: 1 <= i <= n The decimal representation of i * i can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i.   Example 1: Input: n = 10 Output: 182 Explanation: There are exactly 3 integers i that satisfy the conditions in the statement: - 1 since 1 * 1 = 1 - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. Hence, the punishment number of 10 is 1 + 81 + 100 = 182 Example 2: Input: n = 37 Output: 1478 Explanation: There are exactly 4 integers i that satisfy the conditions in the statement: - 1 since 1 * 1 = 1. - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. - 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6. Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478   Constraints: 1 <= n <= 1000
Medium
[ "math", "backtracking" ]
null
[]
2,699
modify-graph-edge-weights
[ "Firstly, check that it’s actually possible to make the shortest path from source to destination equal to the target.", "If the shortest path from source to destination without the edges to be modified, is less than the target, then it is not possible.", "If the shortest path from source to destination including the edges to be modified and assigning them a temporary weight of 1, is greater than the target, then it is also not possible.", "Suppose we can find a modifiable edge (u, v) such that the length of the shortest path from source to u (dis1) plus the length of the shortest path from v to destination (dis2) is less than target (dis1 + dis2 < target), then we can change its weight to “target - dis1 - dis2”.", "For all the other edges that still have the weight “-1”, change the weights into sufficient large number (target, target + 1 or 200000000 etc.)." ]
/** * @param {number} n * @param {number[][]} edges * @param {number} source * @param {number} destination * @param {number} target * @return {number[][]} */ var modifiedGraphEdges = function(n, edges, source, destination, target) { };
You are given an undirected weighted connected graph containing n nodes labeled from 0 to n - 1, and an integer array edges where edges[i] = [ai, bi, wi] indicates that there is an edge between nodes ai and bi with weight wi. Some edges have a weight of -1 (wi = -1), while others have a positive weight (wi > 0). Your task is to modify all edges with a weight of -1 by assigning them positive integer values in the range [1, 2 * 109] so that the shortest distance between the nodes source and destination becomes equal to an integer target. If there are multiple modifications that make the shortest distance between source and destination equal to target, any of them will be considered correct. Return an array containing all edges (even unmodified ones) in any order if it is possible to make the shortest distance from source to destination equal to target, or an empty array if it's impossible. Note: You are not allowed to modify the weights of edges with initial positive weights.   Example 1: Input: n = 5, edges = [[4,1,-1],[2,0,-1],[0,3,-1],[4,3,-1]], source = 0, destination = 1, target = 5 Output: [[4,1,1],[2,0,1],[0,3,3],[4,3,1]] Explanation: The graph above shows a possible modification to the edges, making the distance from 0 to 1 equal to 5. Example 2: Input: n = 3, edges = [[0,1,-1],[0,2,5]], source = 0, destination = 2, target = 6 Output: [] Explanation: The graph above contains the initial edges. It is not possible to make the distance from 0 to 2 equal to 6 by modifying the edge with weight -1. So, an empty array is returned. Example 3: Input: n = 4, edges = [[1,0,4],[1,2,3],[2,3,5],[0,3,-1]], source = 0, destination = 2, target = 6 Output: [[1,0,4],[1,2,3],[2,3,5],[0,3,1]] Explanation: The graph above shows a modified graph having the shortest distance from 0 to 2 as 6.   Constraints: 1 <= n <= 100 1 <= edges.length <= n * (n - 1) / 2 edges[i].length == 3 0 <= ai, bi < n wi = -1 or 1 <= wi <= 107 ai != bi 0 <= source, destination < n source != destination 1 <= target <= 109 The graph is connected, and there are no self-loops or repeated edges
Hard
[ "graph", "heap-priority-queue", "shortest-path" ]
null
[]
2,706
buy-two-chocolates
[ "Sort the array and check if the money is more than or equal to the sum of the two cheapest elements." ]
/** * @param {number[]} prices * @param {number} money * @return {number} */ var buyChoco = function(prices, money) { };
You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money. You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative.   Example 1: Input: prices = [1,2,2], money = 3 Output: 0 Explanation: Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. Example 2: Input: prices = [3,2,3], money = 3 Output: 3 Explanation: You cannot buy 2 chocolates without going in debt, so we return 3.   Constraints: 2 <= prices.length <= 50 1 <= prices[i] <= 100 1 <= money <= 100
Easy
[ "array", "sorting" ]
null
[]
2,707
extra-characters-in-a-string
[ "Can we use Dynamic Programming here?", "Define DP[i] as the min extra character if breaking up s[0:i] optimally." ]
/** * @param {string} s * @param {string[]} dictionary * @return {number} */ var minExtraChar = function(s, dictionary) { };
You are given a 0-indexed string s and a dictionary of words dictionary. You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary. There may be some extra characters in s which are not present in any of the substrings. Return the minimum number of extra characters left over if you break up s optimally.   Example 1: Input: s = "leetscode", dictionary = ["leet","code","leetcode"] Output: 1 Explanation: We can break s in two substrings: "leet" from index 0 to 3 and "code" from index 5 to 8. There is only 1 unused character (at index 4), so we return 1. Example 2: Input: s = "sayhelloworld", dictionary = ["hello","world"] Output: 3 Explanation: We can break s in two substrings: "hello" from index 3 to 7 and "world" from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3.   Constraints: 1 <= s.length <= 50 1 <= dictionary.length <= 50 1 <= dictionary[i].length <= 50 dictionary[i] and s consists of only lowercase English letters dictionary contains distinct words
Medium
[ "array", "hash-table", "string", "dynamic-programming", "trie" ]
null
[]
2,708
maximum-strength-of-a-group
[ "Try to generate all pairs of subsets and check which group provides maximal strength.", "It can also be solved in O(NlogN) by sorting the array and using all positive integers.", "Use negative integers only in pairs such that their product becomes positive." ]
/** * @param {number[]} nums * @return {number} */ var maxStrength = function(nums) { };
You are given a 0-indexed integer array nums representing the score of students in an exam. The teacher would like to form one non-empty group of students with maximal strength, where the strength of a group of students of indices i0, i1, i2, ... , ik is defined as nums[i0] * nums[i1] * nums[i2] * ... * nums[ik​]. Return the maximum strength of a group the teacher can create.   Example 1: Input: nums = [3,-1,-5,2,5,-9] Output: 1350 Explanation: One way to form a group of maximal strength is to group the students at indices [0,2,3,4,5]. Their strength is 3 * (-5) * 2 * 5 * (-9) = 1350, which we can show is optimal. Example 2: Input: nums = [-4,-5,-4] Output: 20 Explanation: Group the students at indices [0, 1] . Then, we’ll have a resulting strength of 20. We cannot achieve greater strength.   Constraints: 1 <= nums.length <= 13 -9 <= nums[i] <= 9
Medium
[ "array", "backtracking", "greedy", "sorting" ]
null
[]
2,709
greatest-common-divisor-traversal
[ "Create a (prime) factor-numbers list for all the indices.", "Add an edge between the neighbors of the (prime) factor-numbers list. The order of the numbers doesn’t matter. We only need edges between 2 neighbors instead of edges for all pairs.", "The problem is now similar to checking if all the numbers (nodes of the graph) are in the same connected component.", "Any algorithm (i.e., BFS, DFS, or Union-Find Set) should work to find or check connected components" ]
/** * @param {number[]} nums * @return {boolean} */ var canTraverseAllPairs = function(nums) { };
You are given a 0-indexed integer array nums, and you are allowed to traverse between its indices. You can traverse between index i and index j, i != j, if and only if gcd(nums[i], nums[j]) > 1, where gcd is the greatest common divisor. Your task is to determine if for every pair of indices i and j in nums, where i < j, there exists a sequence of traversals that can take us from i to j. Return true if it is possible to traverse between all such pairs of indices, or false otherwise.   Example 1: Input: nums = [2,3,6] Output: true Explanation: In this example, there are 3 possible pairs of indices: (0, 1), (0, 2), and (1, 2). To go from index 0 to index 1, we can use the sequence of traversals 0 -> 2 -> 1, where we move from index 0 to index 2 because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 > 1. To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = gcd(3, 6) = 3 > 1. Example 2: Input: nums = [3,9,5] Output: false Explanation: No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false. Example 3: Input: nums = [4,3,12,8] Output: true Explanation: There are 6 possible pairs of indices to traverse between: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). A valid sequence of traversals exists for each pair, so we return true.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105
Hard
[ "array", "math", "union-find", "number-theory" ]
null
[]
2,710
remove-trailing-zeros-from-a-string
[ "Find the last non-zero digit in num." ]
/** * @param {string} num * @return {string} */ var removeTrailingZeros = function(num) { };
Given a positive integer num represented as a string, return the integer num without trailing zeros as a string.   Example 1: Input: num = "51230100" Output: "512301" Explanation: Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301". Example 2: Input: num = "123" Output: "123" Explanation: Integer "123" has no trailing zeros, we return integer "123".   Constraints: 1 <= num.length <= 1000 num consists of only digits. num doesn't have any leading zeros.
Easy
[ "string" ]
[ "var removeTrailingZeros = function(num) {\n const n = num.length\n let idx = n\n for(let i = n - 1; i >= 0; i--) {\n if(num[i] === '0') idx = i\n else break\n }\n \n return num.slice(0, idx)\n};" ]
2,711
difference-of-number-of-distinct-values-on-diagonals
[ "Use the set to count the number of distinct elements on diagonals." ]
/** * @param {number[][]} grid * @return {number[][]} */ var differenceOfDistinctValues = function(grid) { };
Given a 0-indexed 2D grid of size m x n, you should find the matrix answer of size m x n. The value of each cell (r, c) of the matrix answer is calculated in the following way: Let topLeft[r][c] be the number of distinct values in the top-left diagonal of the cell (r, c) in the matrix grid. Let bottomRight[r][c] be the number of distinct values in the bottom-right diagonal of the cell (r, c) in the matrix grid. Then answer[r][c] = |topLeft[r][c] - bottomRight[r][c]|. Return the matrix answer. A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. A cell (r1, c1) belongs to the top-left diagonal of the cell (r, c), if both belong to the same diagonal and r1 < r. Similarly is defined bottom-right diagonal.   Example 1: Input: grid = [[1,2,3],[3,1,5],[3,2,1]] Output: [[1,1,0],[1,0,1],[0,1,1]] Explanation: The 1st diagram denotes the initial grid.  The 2nd diagram denotes a grid for cell (0,0), where blue-colored cells are cells on its bottom-right diagonal. The 3rd diagram denotes a grid for cell (1,2), where red-colored cells are cells on its top-left diagonal. The 4th diagram denotes a grid for cell (1,1), where blue-colored cells are cells on its bottom-right diagonal and red-colored cells are cells on its top-left diagonal. - The cell (0,0) contains [1,1] on its bottom-right diagonal and [] on its top-left diagonal. The answer is |1 - 0| = 1. - The cell (1,2) contains [] on its bottom-right diagonal and [2] on its top-left diagonal. The answer is |0 - 1| = 1. - The cell (1,1) contains [1] on its bottom-right diagonal and [1] on its top-left diagonal. The answer is |1 - 1| = 0. The answers of other cells are similarly calculated. Example 2: Input: grid = [[1]] Output: [[0]] Explanation: - The cell (0,0) contains [] on its bottom-right diagonal and [] on its top-left diagonal. The answer is |0 - 0| = 0.   Constraints: m == grid.length n == grid[i].length 1 <= m, n, grid[i][j] <= 50
Medium
[ "array", "hash-table", "matrix" ]
[ "const differenceOfDistinctValues = function (grid) {\n const m = grid.length,\n n = grid[0].length,\n { abs } = Math\n const res = Array.from({ length: m }, () => Array(n).fill(0))\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n const bottomRight = new Set()\n const topLeft = new Set()\n let x = i + 1\n let y = j + 1\n while (x >= 0 && x < m && y >= 0 && y < n) {\n bottomRight.add(grid[x][y])\n x++\n y++\n }\n x = i - 1\n y = j - 1\n while (x >= 0 && x < m && y >= 0 && y < n) {\n topLeft.add(grid[x][y])\n x--\n y--\n }\n\n res[i][j] = abs(bottomRight.size - topLeft.size)\n }\n }\n return res\n}" ]
2,712
minimum-cost-to-make-all-characters-equal
[ "For every index i, calculate the number of operations required to make the prefix [0, i - 1] equal to the character at index i, denoted prefix[i].", "For every index i, calculate the number of operations required to make the suffix [i + 1, n - 1] equal to the character at index i, denoted suffix[i].", "The final string will contain at least one character that is left unchanged; Therefore, the answer is the minimum of prefix[i] + suffix[i] for every i in [0, n - 1]." ]
/** * @param {string} s * @return {number} */ var minimumCost = function(s) { };
You are given a 0-indexed binary string s of length n on which you can apply two types of operations: Choose an index i and invert all characters from index 0 to index i (both inclusive), with a cost of i + 1 Choose an index i and invert all characters from index i to index n - 1 (both inclusive), with a cost of n - i Return the minimum cost to make all characters of the string equal. Invert a character means if its value is '0' it becomes '1' and vice-versa.   Example 1: Input: s = "0011" Output: 2 Explanation: Apply the second operation with i = 2 to obtain s = "0000" for a cost of 2. It can be shown that 2 is the minimum cost to make all characters equal. Example 2: Input: s = "010101" Output: 9 Explanation: Apply the first operation with i = 2 to obtain s = "101101" for a cost of 3. Apply the first operation with i = 1 to obtain s = "011101" for a cost of 2. Apply the first operation with i = 0 to obtain s = "111101" for a cost of 1. Apply the second operation with i = 4 to obtain s = "111110" for a cost of 2. Apply the second operation with i = 5 to obtain s = "111111" for a cost of 1. The total cost to make all characters equal is 9. It can be shown that 9 is the minimum cost to make all characters equal.   Constraints: 1 <= s.length == n <= 105 s[i] is either '0' or '1'
Medium
[ "string", "dynamic-programming", "greedy" ]
[ "const minimumCost = function (s) {\n const n = s.length,\n { min } = Math\n let res = Infinity\n const dp = Array.from({ length: n + 1 }, () => Array(2).fill(0))\n const dp1 = Array.from({ length: n + 1 }, () => Array(2).fill(0))\n for (let i = 0; i < n; i++) {\n if (s[i] === '0') {\n dp[i + 1][0] = dp[i][0]\n dp[i + 1][1] = dp[i][0] + (i + 1)\n } else {\n dp[i + 1][0] = dp[i][1] + (i + 1)\n dp[i + 1][1] = dp[i][1]\n }\n }\n\n for (let i = n - 1; i >= 0; i--) {\n if (s[i] === '0') {\n dp1[i][0] = dp1[i + 1][0]\n dp1[i][1] = dp1[i + 1][0] + (n - i)\n } else {\n dp1[i][0] = dp1[i + 1][1] + (n - i)\n dp1[i][1] = dp1[i + 1][1]\n }\n }\n for (let i = 0; i <= n; i++) {\n res = min(res, dp[i][0] + dp1[i][0], dp[i][1] + dp1[i][1])\n }\n return res\n}" ]
2,713
maximum-strictly-increasing-cells-in-a-matrix
[ "We can try to build the answer in a bottom-up fashion, starting from the smallest values and increasing to the larger values.", "Going through the values in sorted order, we can store the maximum path we have seen so far for a row/column.", "When we are at a cell, we check its row and column to find out the best previous smaller value that we’ve got so far, and we use it to increment the current value of the row and column." ]
/** * @param {number[][]} mat * @return {number} */ var maxIncreasingCells = function(mat) { };
Given a 1-indexed m x n integer matrix mat, you can select any cell in the matrix as your starting cell. From the starting cell, you can move to any other cell in the same row or column, but only if the value of the destination cell is strictly greater than the value of the current cell. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves. Your task is to find the maximum number of cells that you can visit in the matrix by starting from some cell. Return an integer denoting the maximum number of cells that can be visited.   Example 1: Input: mat = [[3,1],[3,4]] Output: 2 Explanation: The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2. Example 2: Input: mat = [[1,1],[1,1]] Output: 1 Explanation: Since the cells must be strictly increasing, we can only visit one cell in this example. Example 3: Input: mat = [[3,1,6],[-9,5,7]] Output: 4 Explanation: The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4.   Constraints: m == mat.length  n == mat[i].length  1 <= m, n <= 105 1 <= m * n <= 105 -105 <= mat[i][j] <= 105
Hard
[ "array", "binary-search", "dynamic-programming", "memoization", "sorting", "matrix" ]
[ "const maxIncreasingCells = function (mat) {\n let m = mat.length\n let n = mat[0].length\n\n const p = Array.from({ length: m * n }, () => Array(2).fill(0))\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n p[i * n + j][0] = i\n p[i * n + j][1] = j\n }\n }\n p.sort((a, b) => mat[a[0]][a[1]] - mat[b[0]][b[1]])\n\n let rmax = new Array(m).fill(0)\n\n let cmax = new Array(n).fill(0)\n let ans = 0\n let start = 0,\n end = 0\n for (; start < m * n; start = end) {\n let sv = mat[p[start][0]][p[start][1]]\n\n for (end = start + 1; end < m * n; end++) {\n if (sv != mat[p[end][0]][p[end][1]]) {\n break\n }\n }\n\n let list = []\n for (let t = start; t < end; t++) {\n let i = p[t][0],\n j = p[t][1]\n let max = Math.max(rmax[i], cmax[j]) + 1\n list.push([i, j, max])\n ans = Math.max(ans, max)\n }\n for (let ints of list) {\n let i = ints[0],\n j = ints[1],\n max = ints[2]\n rmax[i] = Math.max(rmax[i], max)\n cmax[j] = Math.max(cmax[j], max)\n }\n }\n return ans\n}" ]
2,716
minimize-string-length
[ "The minimized string will not contain duplicate characters.", "The minimized string will contain all distinct characters of the original string." ]
/** * @param {string} s * @return {number} */ var minimizedStringLength = function(s) { };
Given a 0-indexed string s, repeatedly perform the following operation any number of times: Choose an index i in the string, and let c be the character in position i. Delete the closest occurrence of c to the left of i (if any) and the closest occurrence of c to the right of i (if any). Your task is to minimize the length of s by performing the above operation any number of times. Return an integer denoting the length of the minimized string.   Example 1: Input: s = "aaabc" Output: 3 Explanation: In this example, s is "aaabc". We can start by selecting the character 'a' at index 1. We then remove the closest 'a' to the left of index 1, which is at index 0, and the closest 'a' to the right of index 1, which is at index 2. After this operation, the string becomes "abc". Any further operation we perform on the string will leave it unchanged. Therefore, the length of the minimized string is 3. Example 2: Input: s = "cbbd" Output: 3 Explanation: For this we can start with character 'b' at index 1. There is no occurrence of 'b' to the left of index 1, but there is one to the right at index 2, so we delete the 'b' at index 2. The string becomes "cbd" and further operations will leave it unchanged. Hence, the minimized length is 3.  Example 3: Input: s = "dddaaa" Output: 2 Explanation: For this, we can start with the character 'd' at index 1. The closest occurrence of a 'd' to its left is at index 0, and the closest occurrence of a 'd' to its right is at index 2. We delete both index 0 and 2, so the string becomes "daaa". In the new string, we can select the character 'a' at index 2. The closest occurrence of an 'a' to its left is at index 1, and the closest occurrence of an 'a' to its right is at index 3. We delete both of them, and the string becomes "da". We cannot minimize this further, so the minimized length is 2.     Constraints: 1 <= s.length <= 100 s contains only lowercase English letters
Easy
[ "hash-table", "string" ]
null
[]
2,717
semi-ordered-permutation
[ "Find the index of elements 1 and n.", "Let x be the position of 1 and y be the position of n. the answer is x + (n-y-1) if x < y and x + (n-y-1) - 1 if x > y." ]
/** * @param {number[]} nums * @return {number} */ var semiOrderedPermutation = function(nums) { };
You are given a 0-indexed permutation of n integers nums. A permutation is called semi-ordered if the first number equals 1 and the last number equals n. You can perform the below operation as many times as you want until you make nums a semi-ordered permutation: Pick two adjacent elements in nums, then swap them. Return the minimum number of operations to make nums a semi-ordered permutation. A permutation is a sequence of integers from 1 to n of length n containing each number exactly once.   Example 1: Input: nums = [2,1,4,3] Output: 2 Explanation: We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 2 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than two operations that make nums a semi-ordered permutation. Example 2: Input: nums = [2,4,1,3] Output: 3 Explanation: We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 1 and j = 2. The permutation becomes [2,1,4,3]. 2 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 3 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than three operations that make nums a semi-ordered permutation. Example 3: Input: nums = [1,3,4,2,5] Output: 0 Explanation: The permutation is already a semi-ordered permutation.   Constraints: 2 <= nums.length == n <= 50 1 <= nums[i] <= 50 nums is a permutation.
Easy
[ "array", "simulation" ]
null
[]
2,718
sum-of-matrix-after-queries
[ "Process queries in reversed order, as the latest queries represent the most recent changes in the matrix.", "Once you encounter an operation on some row/column, no further operations will affect the values in this row/column. Keep track of seen rows and columns with a set.", "When operating on an unseen row/column, the number of affected cells is the number of columns/rows you haven’t previously seen." ]
/** * @param {number} n * @param {number[][]} queries * @return {number} */ var matrixSumQueries = function(n, queries) { };
You are given an integer n and a 0-indexed 2D array queries where queries[i] = [typei, indexi, vali]. Initially, there is a 0-indexed n x n matrix filled with 0's. For each query, you must apply one of the following changes: if typei == 0, set the values in the row with indexi to vali, overwriting any previous values. if typei == 1, set the values in the column with indexi to vali, overwriting any previous values. Return the sum of integers in the matrix after all queries are applied.   Example 1: Input: n = 3, queries = [[0,0,1],[1,2,2],[0,2,3],[1,0,4]] Output: 23 Explanation: The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 23. Example 2: Input: n = 3, queries = [[0,0,4],[0,1,2],[1,0,1],[0,2,3],[1,2,1]] Output: 17 Explanation: The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 17.   Constraints: 1 <= n <= 104 1 <= queries.length <= 5 * 104 queries[i].length == 3 0 <= typei <= 1 0 <= indexi < n 0 <= vali <= 105
Medium
[ "array", "hash-table" ]
null
[]
2,719
count-of-integers
[ "Let f(n, l, r) denotes the number of integers from 1 to n with the sum of digits between l and r.", "The answer is f(num2, min_sum, max_sum) - f(num-1, min_sum, max_sum).", "You can calculate f(n, l, r) using digit dp." ]
/** * @param {string} num1 * @param {string} num2 * @param {number} min_sum * @param {number} max_sum * @return {number} */ var count = function(num1, num2, min_sum, max_sum) { };
You are given two numeric strings num1 and num2 and two integers max_sum and min_sum. We denote an integer x to be good if: num1 <= x <= num2 min_sum <= digit_sum(x) <= max_sum. Return the number of good integers. Since the answer may be large, return it modulo 109 + 7. Note that digit_sum(x) denotes the sum of the digits of x.   Example 1: Input: num1 = "1", num2 = "12", min_sum = 1, max_sum = 8 Output: 11 Explanation: There are 11 integers whose sum of digits lies between 1 and 8 are 1,2,3,4,5,6,7,8,10,11, and 12. Thus, we return 11. Example 2: Input: num1 = "1", num2 = "5", min_sum = 1, max_sum = 5 Output: 5 Explanation: The 5 integers whose sum of digits lies between 1 and 5 are 1,2,3,4, and 5. Thus, we return 5.   Constraints: 1 <= num1 <= num2 <= 1022 1 <= min_sum <= max_sum <= 400
Hard
[ "math", "string", "dynamic-programming" ]
null
[]
2,729
check-if-the-number-is-fascinating
[ "Consider changing the number to the way it is described in the statement.", "Check if the resulting number contains all the digits from 1 to 9 exactly once." ]
/** * @param {number} n * @return {boolean} */ var isFascinating = function(n) { };
You are given an integer n that consists of exactly 3 digits. We call the number n fascinating if, after the following modification, the resulting number contains all the digits from 1 to 9 exactly once and does not contain any 0's: Concatenate n with the numbers 2 * n and 3 * n. Return true if n is fascinating, or false otherwise. Concatenating two numbers means joining them together. For example, the concatenation of 121 and 371 is 121371.   Example 1: Input: n = 192 Output: true Explanation: We concatenate the numbers n = 192 and 2 * n = 384 and 3 * n = 576. The resulting number is 192384576. This number contains all the digits from 1 to 9 exactly once. Example 2: Input: n = 100 Output: false Explanation: We concatenate the numbers n = 100 and 2 * n = 200 and 3 * n = 300. The resulting number is 100200300. This number does not satisfy any of the conditions.   Constraints: 100 <= n <= 999
Easy
[ "hash-table", "math" ]
null
[]
2,730
find-the-longest-semi-repetitive-substring
[ "Since n is small, we can just check every substring, and if the substring is semi-repetitive, maximize the answer with its length." ]
/** * @param {string} s * @return {number} */ var longestSemiRepetitiveSubstring = function(s) { };
You are given a 0-indexed string s that consists of digits from 0 to 9. A string t is called a semi-repetitive if there is at most one consecutive pair of the same digits inside t. For example, 0010, 002020, 0123, 2002, and 54944 are semi-repetitive while 00101022, and 1101234883 are not. Return the length of the longest semi-repetitive substring inside s. A substring is a contiguous non-empty sequence of characters within a string.   Example 1: Input: s = "52233" Output: 4 Explanation: The longest semi-repetitive substring is "5223", which starts at i = 0 and ends at j = 3. Example 2: Input: s = "5494" Output: 4 Explanation: s is a semi-reptitive string, so the answer is 4. Example 3: Input: s = "1111111" Output: 2 Explanation: The longest semi-repetitive substring is "11", which starts at i = 0 and ends at j = 1.   Constraints: 1 <= s.length <= 50 '0' <= s[i] <= '9'
Medium
[ "string", "sliding-window" ]
null
[]
2,731
movement-of-robots
[ "Observe that if you ignore collisions, the resultant positions of robots after d seconds would be the same.", "After d seconds, sort the ending positions and use prefix sum to calculate the distance sum." ]
/** * @param {number[]} nums * @param {string} s * @param {number} d * @return {number} */ var sumDistance = function(nums, s, d) { };
Some robots are standing on an infinite number line with their initial coordinates given by a 0-indexed integer array nums and will start moving once given the command to move. The robots will move a unit distance each second. You are given a string s denoting the direction in which robots will move on command. 'L' means the robot will move towards the left side or negative side of the number line, whereas 'R' means the robot will move towards the right side or positive side of the number line. If two robots collide, they will start moving in opposite directions. Return the sum of distances between all the pairs of robots d seconds after the command. Since the sum can be very large, return it modulo 109 + 7. Note: For two robots at the index i and j, pair (i,j) and pair (j,i) are considered the same pair. When robots collide, they instantly change their directions without wasting any time. Collision happens when two robots share the same place in a moment. For example, if a robot is positioned in 0 going to the right and another is positioned in 2 going to the left, the next second they'll be both in 1 and they will change direction and the next second the first one will be in 0, heading left, and another will be in 2, heading right. For example, if a robot is positioned in 0 going to the right and another is positioned in 1 going to the left, the next second the first one will be in 0, heading left, and another will be in 1, heading right.   Example 1: Input: nums = [-2,0,2], s = "RLL", d = 3 Output: 8 Explanation: After 1 second, the positions are [-1,-1,1]. Now, the robot at index 0 will move left, and the robot at index 1 will move right. After 2 seconds, the positions are [-2,0,0]. Now, the robot at index 1 will move left, and the robot at index 2 will move right. After 3 seconds, the positions are [-3,-1,1]. The distance between the robot at index 0 and 1 is abs(-3 - (-1)) = 2. The distance between the robot at index 0 and 2 is abs(-3 - 1) = 4. The distance between the robot at index 1 and 2 is abs(-1 - 1) = 2. The sum of the pairs of all distances = 2 + 4 + 2 = 8. Example 2: Input: nums = [1,0], s = "RL", d = 2 Output: 5 Explanation: After 1 second, the positions are [2,-1]. After 2 seconds, the positions are [3,-2]. The distance between the two robots is abs(-2 - 3) = 5.   Constraints: 2 <= nums.length <= 105 -2 * 109 <= nums[i] <= 2 * 109 0 <= d <= 109 nums.length == s.length  s consists of 'L' and 'R' only nums[i] will be unique.
Medium
[ "array", "brainteaser", "sorting", "prefix-sum" ]
null
[]
2,732
find-a-good-subset-of-the-matrix
[ "It can be proven, that if there exists a good subset of rows then there exists a good subset of rows with the size of either 1 or 2.", "To check if there exists a good subset of rows of size 1, we check if there exists a row containing only zeros, if it does, we return its index as a good subset.", "To check if there exists a good subset of rows of size 2, we iterate over two bit-masks, check if both are presented in the array and if they form a good subset, if they do, return their indices as a good subset." ]
/** * @param {number[][]} grid * @return {number[]} */ var goodSubsetofBinaryMatrix = function(grid) { };
You are given a 0-indexed m x n binary matrix grid. Let us call a non-empty subset of rows good if the sum of each column of the subset is at most half of the length of the subset. More formally, if the length of the chosen subset of rows is k, then the sum of each column should be at most floor(k / 2). Return an integer array that contains row indices of a good subset sorted in ascending order. If there are multiple good subsets, you can return any of them. If there are no good subsets, return an empty array. A subset of rows of the matrix grid is any matrix that can be obtained by deleting some (possibly none or all) rows from grid.   Example 1: Input: grid = [[0,1,1,0],[0,0,0,1],[1,1,1,1]] Output: [0,1] Explanation: We can choose the 0th and 1st rows to create a good subset of rows. The length of the chosen subset is 2. - The sum of the 0th column is 0 + 0 = 0, which is at most half of the length of the subset. - The sum of the 1st column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 2nd column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 3rd column is 0 + 1 = 1, which is at most half of the length of the subset. Example 2: Input: grid = [[0]] Output: [0] Explanation: We can choose the 0th row to create a good subset of rows. The length of the chosen subset is 1. - The sum of the 0th column is 0, which is at most half of the length of the subset. Example 3: Input: grid = [[1,1,1],[1,1,1]] Output: [] Explanation: It is impossible to choose any subset of rows to create a good subset.   Constraints: m == grid.length n == grid[i].length 1 <= m <= 104 1 <= n <= 5 grid[i][j] is either 0 or 1.
Hard
[ "array", "greedy", "bit-manipulation", "matrix" ]
null
[]
2,733
neither-minimum-nor-maximum
[ "Find any value in the array that is not the minimum or the maximum value." ]
/** * @param {number[]} nums * @return {number} */ var findNonMinOrMax = function(nums) { };
Given an integer array nums containing distinct positive integers, find and return any number from the array that is neither the minimum nor the maximum value in the array, or -1 if there is no such number. Return the selected integer.   Example 1: Input: nums = [3,2,1,4] Output: 2 Explanation: In this example, the minimum value is 1 and the maximum value is 4. Therefore, either 2 or 3 can be valid answers. Example 2: Input: nums = [1,2] Output: -1 Explanation: Since there is no number in nums that is neither the maximum nor the minimum, we cannot select a number that satisfies the given condition. Therefore, there is no answer. Example 3: Input: nums = [2,1,3] Output: 2 Explanation: Since 2 is neither the maximum nor the minimum value in nums, it is the only valid answer.   Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100 All values in nums are distinct
Easy
[ "array", "sorting" ]
null
[]
2,734
lexicographically-smallest-string-after-substring-operation
[ "When a character is replaced by the one that comes before it on the alphabet, it makes the string lexicographically smaller, except for ‘a'.", "Find the leftmost substring that doesn’t contain the character 'a' and change all characters in it." ]
/** * @param {string} s * @return {string} */ var smallestString = function(s) { };
You are given a string s consisting of only lowercase English letters. In one operation, you can do the following: Select any non-empty substring of s, possibly the entire string, then replace each one of its characters with the previous character of the English alphabet. For example, 'b' is converted to 'a', and 'a' is converted to 'z'. Return the lexicographically smallest string you can obtain after performing the above operation exactly once. A substring is a contiguous sequence of characters in a string. A string x is lexicographically smaller than a string y of the same length if x[i] comes before y[i] in alphabetic order for the first position i such that x[i] != y[i].   Example 1: Input: s = "cbabc" Output: "baabc" Explanation: We apply the operation on the substring starting at index 0, and ending at index 1 inclusive. It can be proven that the resulting string is the lexicographically smallest. Example 2: Input: s = "acbbc" Output: "abaab" Explanation: We apply the operation on the substring starting at index 1, and ending at index 4 inclusive. It can be proven that the resulting string is the lexicographically smallest. Example 3: Input: s = "leetcode" Output: "kddsbncd" Explanation: We apply the operation on the entire string. It can be proven that the resulting string is the lexicographically smallest.   Constraints: 1 <= s.length <= 3 * 105 s consists of lowercase English letters
Medium
[ "string", "greedy" ]
null
[]
2,735
collecting-chocolates
[ "How many maximum rotations will be needed?", "The array will be rotated for a max of N times, so try all possibilities as N = 1000." ]
/** * @param {number[]} nums * @param {number} x * @return {number} */ var minCost = function(nums, x) { };
You are given a 0-indexed integer array nums of size n representing the cost of collecting different chocolates. The cost of collecting the chocolate at the index i is nums[i]. Each chocolate is of a different type, and initially, the chocolate at the index i is of ith type. In one operation, you can do the following with an incurred cost of x: Simultaneously change the chocolate of ith type to ((i + 1) mod n)th type for all chocolates. Return the minimum cost to collect chocolates of all types, given that you can perform as many operations as you would like.   Example 1: Input: nums = [20,1,15], x = 5 Output: 13 Explanation: Initially, the chocolate types are [0,1,2]. We will buy the 1st type of chocolate at a cost of 1. Now, we will perform the operation at a cost of 5, and the types of chocolates will become [1,2,0]. We will buy the 2nd type of chocolate at a cost of 1. Now, we will again perform the operation at a cost of 5, and the chocolate types will become [2,0,1]. We will buy the 0th type of chocolate at a cost of 1. Thus, the total cost will become (1 + 5 + 1 + 5 + 1) = 13. We can prove that this is optimal. Example 2: Input: nums = [1,2,3], x = 4 Output: 6 Explanation: We will collect all three types of chocolates at their own price without performing any operations. Therefore, the total cost is 1 + 2 + 3 = 6.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 109 1 <= x <= 109
Medium
[ "array", "enumeration" ]
null
[]
2,736
maximum-sum-queries
[ "Sort (x, y) tuples and queries by x-coordinate descending. Don’t forget to index queries before sorting so that you can answer them in the correct order.", "Before answering a query (min_x, min_y), add all (x, y) pairs with x >= min_x to some data structure.", "Use a monotone descending map to store (y, x + y) pairs. A monotone map has ascending keys and descending values. When inserting a pair (y, x + y), remove all pairs (y', x' + y') with y' < y and x' + y' <= x + y.", "To find the insertion position use binary search (built-in in many languages).", "When querying for max (x + y) over y >= y', use binary search to find the first pair (y, x + y) with y >= y'. It will have the maximum value of x + y because the map has monotone descending values." ]
/** * @param {number[]} nums1 * @param {number[]} nums2 * @param {number[][]} queries * @return {number[]} */ var maximumSumQueries = function(nums1, nums2, queries) { };
You are given two 0-indexed integer arrays nums1 and nums2, each of length n, and a 1-indexed 2D array queries where queries[i] = [xi, yi]. For the ith query, find the maximum value of nums1[j] + nums2[j] among all indices j (0 <= j < n), where nums1[j] >= xi and nums2[j] >= yi, or -1 if there is no j satisfying the constraints. Return an array answer where answer[i] is the answer to the ith query.   Example 1: Input: nums1 = [4,3,1,2], nums2 = [2,4,9,5], queries = [[4,1],[1,3],[2,5]] Output: [6,10,7] Explanation: For the 1st query xi = 4 and yi = 1, we can select index j = 0 since nums1[j] >= 4 and nums2[j] >= 1. The sum nums1[j] + nums2[j] is 6, and we can show that 6 is the maximum we can obtain. For the 2nd query xi = 1 and yi = 3, we can select index j = 2 since nums1[j] >= 1 and nums2[j] >= 3. The sum nums1[j] + nums2[j] is 10, and we can show that 10 is the maximum we can obtain. For the 3rd query xi = 2 and yi = 5, we can select index j = 3 since nums1[j] >= 2 and nums2[j] >= 5. The sum nums1[j] + nums2[j] is 7, and we can show that 7 is the maximum we can obtain. Therefore, we return [6,10,7]. Example 2: Input: nums1 = [3,2,5], nums2 = [2,3,4], queries = [[4,4],[3,2],[1,1]] Output: [9,9,9] Explanation: For this example, we can use index j = 2 for all the queries since it satisfies the constraints for each query. Example 3: Input: nums1 = [2,1], nums2 = [2,3], queries = [[3,3]] Output: [-1] Explanation: There is one query in this example with xi = 3 and yi = 3. For every index, j, either nums1[j] < xi or nums2[j] < yi. Hence, there is no solution.   Constraints: nums1.length == nums2.length  n == nums1.length  1 <= n <= 105 1 <= nums1[i], nums2[i] <= 109  1 <= queries.length <= 105 queries[i].length == 2 xi == queries[i][1] yi == queries[i][2] 1 <= xi, yi <= 109
Hard
[ "array", "binary-search", "stack", "binary-indexed-tree", "segment-tree", "sorting", "monotonic-stack" ]
null
[]
2,739
total-distance-traveled
[ "Avoid calculations in decimal to prevent precision errors." ]
/** * @param {number} mainTank * @param {number} additionalTank * @return {number} */ var distanceTraveled = function(mainTank, additionalTank) { };
A truck has two fuel tanks. You are given two integers, mainTank representing the fuel present in the main tank in liters and additionalTank representing the fuel present in the additional tank in liters. The truck has a mileage of 10 km per liter. Whenever 5 liters of fuel get used up in the main tank, if the additional tank has at least 1 liters of fuel, 1 liters of fuel will be transferred from the additional tank to the main tank. Return the maximum distance which can be traveled. Note: Injection from the additional tank is not continuous. It happens suddenly and immediately for every 5 liters consumed.   Example 1: Input: mainTank = 5, additionalTank = 10 Output: 60 Explanation: After spending 5 litre of fuel, fuel remaining is (5 - 5 + 1) = 1 litre and distance traveled is 50km. After spending another 1 litre of fuel, no fuel gets injected in the main tank and the main tank becomes empty. Total distance traveled is 60km. Example 2: Input: mainTank = 1, additionalTank = 2 Output: 10 Explanation: After spending 1 litre of fuel, the main tank becomes empty. Total distance traveled is 10km.   Constraints: 1 <= mainTank, additionalTank <= 100
Easy
[ "math", "simulation" ]
null
[]
2,740
find-the-value-of-the-partition
[ "Sort the array.", "The answer is min(nums[i+1] - nums[i]) for all i in the range [0, n-2]." ]
/** * @param {number[]} nums * @return {number} */ var findValueOfPartition = function(nums) { };
You are given a positive integer array nums. Partition nums into two arrays, nums1 and nums2, such that: Each element of the array nums belongs to either the array nums1 or the array nums2. Both arrays are non-empty. The value of the partition is minimized. The value of the partition is |max(nums1) - min(nums2)|. Here, max(nums1) denotes the maximum element of the array nums1, and min(nums2) denotes the minimum element of the array nums2. Return the integer denoting the value of such partition.   Example 1: Input: nums = [1,3,2,4] Output: 1 Explanation: We can partition the array nums into nums1 = [1,2] and nums2 = [3,4]. - The maximum element of the array nums1 is equal to 2. - The minimum element of the array nums2 is equal to 3. The value of the partition is |2 - 3| = 1. It can be proven that 1 is the minimum value out of all partitions. Example 2: Input: nums = [100,1,10] Output: 9 Explanation: We can partition the array nums into nums1 = [10] and nums2 = [100,1]. - The maximum element of the array nums1 is equal to 10. - The minimum element of the array nums2 is equal to 1. The value of the partition is |10 - 1| = 9. It can be proven that 9 is the minimum value out of all partitions.   Constraints: 2 <= nums.length <= 105 1 <= nums[i] <= 109
Medium
[ "array", "sorting" ]
null
[]
2,741
special-permutations
[ "Can we solve this problem using DP with bit masking?", "You just need two states in DP which are last_ind in the permutation and the mask of numbers already used." ]
/** * @param {number[]} nums * @return {number} */ var specialPerm = function(nums) { };
You are given a 0-indexed integer array nums containing n distinct positive integers. A permutation of nums is called special if: For all indexes 0 <= i < n - 1, either nums[i] % nums[i+1] == 0 or nums[i+1] % nums[i] == 0. Return the total number of special permutations. As the answer could be large, return it modulo 109 + 7.   Example 1: Input: nums = [2,3,6] Output: 2 Explanation: [3,6,2] and [2,6,3] are the two special permutations of nums. Example 2: Input: nums = [1,4,3] Output: 2 Explanation: [3,1,4] and [4,1,3] are the two special permutations of nums.   Constraints: 2 <= nums.length <= 14 1 <= nums[i] <= 109
Medium
[ "array", "dynamic-programming", "bit-manipulation", "bitmask" ]
null
[]
2,742
painting-the-walls
[ "Can we break the problem down into smaller subproblems and use DP?", "Paid painters will be used for a maximum of N/2 units of time. There is no need to use paid painter for a time greater than this." ]
/** * @param {number[]} cost * @param {number[]} time * @return {number} */ var paintWalls = function(cost, time) { };
You are given two 0-indexed integer arrays, cost and time, of size n representing the costs and the time taken to paint n different walls respectively. There are two painters available: A paid painter that paints the ith wall in time[i] units of time and takes cost[i] units of money. A free painter that paints any wall in 1 unit of time at a cost of 0. But the free painter can only be used if the paid painter is already occupied. Return the minimum amount of money required to paint the n walls.   Example 1: Input: cost = [1,2,3,2], time = [1,2,3,2] Output: 3 Explanation: The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3. Example 2: Input: cost = [2,3,4,2], time = [1,1,1,1] Output: 4 Explanation: The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.   Constraints: 1 <= cost.length <= 500 cost.length == time.length 1 <= cost[i] <= 106 1 <= time[i] <= 500
Hard
[ "array", "dynamic-programming" ]
null
[]
2,744
find-maximum-number-of-string-pairs
[ "Notice that array words consist of distinct strings.", "Iterate over all indices (i, j) and check if they can be paired." ]
/** * @param {string[]} words * @return {number} */ var maximumNumberOfStringPairs = function(words) { };
You are given a 0-indexed array words consisting of distinct strings. The string words[i] can be paired with the string words[j] if: The string words[i] is equal to the reversed string of words[j]. 0 <= i < j < words.length. Return the maximum number of pairs that can be formed from the array words. Note that each string can belong in at most one pair.   Example 1: Input: words = ["cd","ac","dc","ca","zz"] Output: 2 Explanation: In this example, we can form 2 pair of strings in the following way: - We pair the 0th string with the 2nd string, as the reversed string of word[0] is "dc" and is equal to words[2]. - We pair the 1st string with the 3rd string, as the reversed string of word[1] is "ca" and is equal to words[3]. It can be proven that 2 is the maximum number of pairs that can be formed. Example 2: Input: words = ["ab","ba","cc"] Output: 1 Explanation: In this example, we can form 1 pair of strings in the following way: - We pair the 0th string with the 1st string, as the reversed string of words[1] is "ab" and is equal to words[0]. It can be proven that 1 is the maximum number of pairs that can be formed. Example 3: Input: words = ["aa","ab"] Output: 0 Explanation: In this example, we are unable to form any pair of strings.   Constraints: 1 <= words.length <= 50 words[i].length == 2 words consists of distinct strings. words[i] contains only lowercase English letters.
Easy
[ "array", "hash-table", "string", "simulation" ]
null
[]
2,745
construct-the-longest-new-string
[ "It can be proved that ALL “AB”s can be used in the optimal solution.\r\n(1) If the final string starts with 'A', we can put all unused “AB”s at the very beginning.\r\n(2) If the final string starts with 'B' (meaning) it starts with “BB”, we can put all unused “AB”s after the 2nd 'B'.", "Using “AB” doesn’t increase the number of “AA”s or “BB”s we can use.\r\nIf we put an “AB” after “BB”, then we still need to append “AA” as before, so it doesn’t change the state.", "We only need to consider strings “AA” and “BB”; we can either use the pattern “AABBAABB…” or the pattern “BBAABBAA…”, depending on which one of x and y is larger." ]
/** * @param {number} x * @param {number} y * @param {number} z * @return {number} */ var longestString = function(x, y, z) { };
You are given three integers x, y, and z. You have x strings equal to "AA", y strings equal to "BB", and z strings equal to "AB". You want to choose some (possibly all or none) of these strings and concactenate them in some order to form a new string. This new string must not contain "AAA" or "BBB" as a substring. Return the maximum possible length of the new string. A substring is a contiguous non-empty sequence of characters within a string.   Example 1: Input: x = 2, y = 5, z = 1 Output: 12 Explanation: We can concactenate the strings "BB", "AA", "BB", "AA", "BB", and "AB" in that order. Then, our new string is "BBAABBAABBAB". That string has length 12, and we can show that it is impossible to construct a string of longer length. Example 2: Input: x = 3, y = 2, z = 2 Output: 14 Explanation: We can concactenate the strings "AB", "AB", "AA", "BB", "AA", "BB", and "AA" in that order. Then, our new string is "ABABAABBAABBAA". That string has length 14, and we can show that it is impossible to construct a string of longer length.   Constraints: 1 <= x, y, z <= 50
Medium
[ "math", "greedy", "brainteaser" ]
null
[]
2,746
decremental-string-concatenation
[ "Use dynamic programming with memoization.", "Notice that the first and last characters of a string are sufficient to determine the length of its concatenation with any other string.", "Define dp[i][first][last] as the shortest concatenation length of the first i words starting with a character first and ending with a character last. Convert characters to their ASCII codes if your programming language cannot implicitly convert them to array indices." ]
/** * @param {string[]} words * @return {number} */ var minimizeConcatenatedLength = function(words) { };
You are given a 0-indexed array words containing n strings. Let's define a join operation join(x, y) between two strings x and y as concatenating them into xy. However, if the last character of x is equal to the first character of y, one of them is deleted. For example join("ab", "ba") = "aba" and join("ab", "cde") = "abcde". You are to perform n - 1 join operations. Let str0 = words[0]. Starting from i = 1 up to i = n - 1, for the ith operation, you can do one of the following: Make stri = join(stri - 1, words[i]) Make stri = join(words[i], stri - 1) Your task is to minimize the length of strn - 1. Return an integer denoting the minimum possible length of strn - 1.   Example 1: Input: words = ["aa","ab","bc"] Output: 4 Explanation: In this example, we can perform join operations in the following order to minimize the length of str2: str0 = "aa" str1 = join(str0, "ab") = "aab" str2 = join(str1, "bc") = "aabc" It can be shown that the minimum possible length of str2 is 4. Example 2: Input: words = ["ab","b"] Output: 2 Explanation: In this example, str0 = "ab", there are two ways to get str1: join(str0, "b") = "ab" or join("b", str0) = "bab". The first string, "ab", has the minimum length. Hence, the answer is 2. Example 3: Input: words = ["aaa","c","aba"] Output: 6 Explanation: In this example, we can perform join operations in the following order to minimize the length of str2: str0 = "aaa" str1 = join(str0, "c") = "aaac" str2 = join("aba", str1) = "abaaac" It can be shown that the minimum possible length of str2 is 6.     Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 50 Each character in words[i] is an English lowercase letter
Medium
[ "array", "string", "dynamic-programming" ]
null
[]
2,747
count-zero-request-servers
[ "Can we use sorting and two-pointer approach here?", "Sort the queries array and logs array based on time in increasing order.", "For every window of size x, use sliding window and two-pointer approach to find the answer to the queries." ]
/** * @param {number} n * @param {number[][]} logs * @param {number} x * @param {number[]} queries * @return {number[]} */ var countServers = function(n, logs, x, queries) { };
You are given an integer n denoting the total number of servers and a 2D 0-indexed integer array logs, where logs[i] = [server_id, time] denotes that the server with id server_id received a request at time time. You are also given an integer x and a 0-indexed integer array queries. Return a 0-indexed integer array arr of length queries.length where arr[i] represents the number of servers that did not receive any requests during the time interval [queries[i] - x, queries[i]]. Note that the time intervals are inclusive.   Example 1: Input: n = 3, logs = [[1,3],[2,6],[1,5]], x = 5, queries = [10,11] Output: [1,2] Explanation: For queries[0]: The servers with ids 1 and 2 get requests in the duration of [5, 10]. Hence, only server 3 gets zero requests. For queries[1]: Only the server with id 2 gets a request in duration of [6,11]. Hence, the servers with ids 1 and 3 are the only servers that do not receive any requests during that time period. Example 2: Input: n = 3, logs = [[2,4],[2,1],[1,2],[3,1]], x = 2, queries = [3,4] Output: [0,1] Explanation: For queries[0]: All servers get at least one request in the duration of [1, 3]. For queries[1]: Only server with id 3 gets no request in the duration [2,4].   Constraints: 1 <= n <= 105 1 <= logs.length <= 105 1 <= queries.length <= 105 logs[i].length == 2 1 <= logs[i][0] <= n 1 <= logs[i][1] <= 106 1 <= x <= 105 x < queries[i] <= 106
Medium
[ "array", "hash-table", "sliding-window", "sorting" ]
null
[]
2,748
number-of-beautiful-pairs
[ "Since nums.length is small, you can find all pairs of indices and check if each pair is beautiful.", "Use integer to string conversion to get the first and last digit of each number." ]
/** * @param {number[]} nums * @return {number} */ var countBeautifulPairs = function(nums) { };
You are given a 0-indexed integer array nums. A pair of indices i, j where 0 <= i < j < nums.length is called beautiful if the first digit of nums[i] and the last digit of nums[j] are coprime. Return the total number of beautiful pairs in nums. Two integers x and y are coprime if there is no integer greater than 1 that divides both of them. In other words, x and y are coprime if gcd(x, y) == 1, where gcd(x, y) is the greatest common divisor of x and y.   Example 1: Input: nums = [2,5,1,4] Output: 5 Explanation: There are 5 beautiful pairs in nums: When i = 0 and j = 1: the first digit of nums[0] is 2, and the last digit of nums[1] is 5. We can confirm that 2 and 5 are coprime, since gcd(2,5) == 1. When i = 0 and j = 2: the first digit of nums[0] is 2, and the last digit of nums[2] is 1. Indeed, gcd(2,1) == 1. When i = 1 and j = 2: the first digit of nums[1] is 5, and the last digit of nums[2] is 1. Indeed, gcd(5,1) == 1. When i = 1 and j = 3: the first digit of nums[1] is 5, and the last digit of nums[3] is 4. Indeed, gcd(5,4) == 1. When i = 2 and j = 3: the first digit of nums[2] is 1, and the last digit of nums[3] is 4. Indeed, gcd(1,4) == 1. Thus, we return 5. Example 2: Input: nums = [11,21,12] Output: 2 Explanation: There are 2 beautiful pairs: When i = 0 and j = 1: the first digit of nums[0] is 1, and the last digit of nums[1] is 1. Indeed, gcd(1,1) == 1. When i = 0 and j = 2: the first digit of nums[0] is 1, and the last digit of nums[2] is 2. Indeed, gcd(1,2) == 1. Thus, we return 2.   Constraints: 2 <= nums.length <= 100 1 <= nums[i] <= 9999 nums[i] % 10 != 0
Easy
[ "array", "math", "number-theory" ]
null
[]
2,749
minimum-operations-to-make-the-integer-zero
[ "If we want to make integer n equal to 0 by only subtracting powers of 2 from n, in how many operations can we achieve it?", "We need at least - the number of bits in the binary representation of n, and at most - n.", "Notice that, if it is possible to make num1 equal to 0, then we need at most 60 operations.", "Iterate on the number of operations." ]
/** * @param {number} num1 * @param {number} num2 * @return {number} */ var makeTheIntegerZero = function(num1, num2) { };
You are given two integers num1 and num2. In one operation, you can choose integer i in the range [0, 60] and subtract 2i + num2 from num1. Return the integer denoting the minimum number of operations needed to make num1 equal to 0. If it is impossible to make num1 equal to 0, return -1.   Example 1: Input: num1 = 3, num2 = -2 Output: 3 Explanation: We can make 3 equal to 0 with the following operations: - We choose i = 2 and substract 22 + (-2) from 3, 3 - (4 + (-2)) = 1. - We choose i = 2 and substract 22 + (-2) from 1, 1 - (4 + (-2)) = -1. - We choose i = 0 and substract 20 + (-2) from -1, (-1) - (1 + (-2)) = 0. It can be proven, that 3 is the minimum number of operations that we need to perform. Example 2: Input: num1 = 5, num2 = 7 Output: -1 Explanation: It can be proven, that it is impossible to make 5 equal to 0 with the given operation.   Constraints: 1 <= num1 <= 109 -109 <= num2 <= 109
Medium
[ "bit-manipulation", "brainteaser" ]
null
[]
2,750
ways-to-split-array-into-good-subarrays
[ "If the array consists of only 0s answer is 0.", "In the final split, exactly one separation point exists between two consecutive 1s.", "In how many ways can separation points be put?" ]
/** * @param {number[]} nums * @return {number} */ var numberOfGoodSubarraySplits = function(nums) { };
You are given a binary array nums. A subarray of an array is good if it contains exactly one element with the value 1. Return an integer denoting the number of ways to split the array nums into good subarrays. As the number may be too large, return it modulo 109 + 7. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [0,1,0,0,1] Output: 3 Explanation: There are 3 ways to split nums into good subarrays: - [0,1] [0,0,1] - [0,1,0] [0,1] - [0,1,0,0] [1] Example 2: Input: nums = [0,1,0] Output: 1 Explanation: There is 1 way to split nums into good subarrays: - [0,1,0]   Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 1
Medium
[ "array", "math", "dynamic-programming" ]
null
[]
2,751
robot-collisions
[ "Process the robots in the order of their positions to ensure that we process the collisions correctly.", "To optimize the solution, use a stack to keep track of the surviving robots as we iterate through the positions.", "Instead of simulating each collision, check the current robot against the top of the stack (if it exists) to determine if a collision occurs." ]
/** * @param {number[]} positions * @param {number[]} healths * @param {string} directions * @return {number[]} */ var survivedRobotsHealths = function(positions, healths, directions) { };
There are n 1-indexed robots, each having a position on a line, health, and movement direction. You are given 0-indexed integer arrays positions, healths, and a string directions (directions[i] is either 'L' for left or 'R' for right). All integers in positions are unique. All robots start moving on the line simultaneously at the same speed in their given directions. If two robots ever share the same position while moving, they will collide. If two robots collide, the robot with lower health is removed from the line, and the health of the other robot decreases by one. The surviving robot continues in the same direction it was going. If both robots have the same health, they are both removed from the line. Your task is to determine the health of the robots that survive the collisions, in the same order that the robots were given, i.e. final heath of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array. Return an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur. Note: The positions may be unsorted.     Example 1: Input: positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR" Output: [2,17,9,15,10] Explanation: No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10]. Example 2: Input: positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL" Output: [14] Explanation: There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14]. Example 3: Input: positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL" Output: [] Explanation: Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, [].   Constraints: 1 <= positions.length == healths.length == directions.length == n <= 105 1 <= positions[i], healths[i] <= 109 directions[i] == 'L' or directions[i] == 'R' All values in positions are distinct
Hard
[ "array", "stack", "sorting", "simulation" ]
null
[]
2,760
longest-even-odd-subarray-with-threshold
[ "Brute force all the possible subarrays and find the longest that satisfies the conditions." ]
/** * @param {number[]} nums * @param {number} threshold * @return {number} */ var longestAlternatingSubarray = function(nums, threshold) { };
You are given a 0-indexed integer array nums and an integer threshold. Find the length of the longest subarray of nums starting at index l and ending at index r (0 <= l <= r < nums.length) that satisfies the following conditions: nums[l] % 2 == 0 For all indices i in the range [l, r - 1], nums[i] % 2 != nums[i + 1] % 2 For all indices i in the range [l, r], nums[i] <= threshold Return an integer denoting the length of the longest such subarray. Note: A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [3,2,5,4], threshold = 5 Output: 3 Explanation: In this example, we can select the subarray that starts at l = 1 and ends at r = 3 => [2,5,4]. This subarray satisfies the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length. Example 2: Input: nums = [1,2], threshold = 2 Output: 1 Explanation: In this example, we can select the subarray that starts at l = 1 and ends at r = 1 => [2]. It satisfies all the conditions and we can show that 1 is the maximum possible achievable length. Example 3: Input: nums = [2,3,4,5], threshold = 4 Output: 3 Explanation: In this example, we can select the subarray that starts at l = 0 and ends at r = 2 => [2,3,4]. It satisfies all the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length.   Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100 1 <= threshold <= 100
Easy
[ "array", "sliding-window" ]
null
[]
2,761
prime-pairs-with-target-sum
[ "Pre-compute all the prime numbers in the range [1, n] using a sieve, and store them in a data structure where they can be accessed in O(1) time.", "For x in the range [2, n/2], we can use the pre-computed list of prime numbers to check if both x and n - x are primes. If they are, we add them to the result." ]
/** * @param {number} n * @return {number[][]} */ var findPrimePairs = function(n) { };
You are given an integer n. We say that two integers x and y form a prime number pair if: 1 <= x <= y <= n x + y == n x and y are prime numbers Return the 2D sorted list of prime number pairs [xi, yi]. The list should be sorted in increasing order of xi. If there are no prime number pairs at all, return an empty array. Note: A prime number is a natural number greater than 1 with only two factors, itself and 1.   Example 1: Input: n = 10 Output: [[3,7],[5,5]] Explanation: In this example, there are two prime pairs that satisfy the criteria. These pairs are [3,7] and [5,5], and we return them in the sorted order as described in the problem statement. Example 2: Input: n = 2 Output: [] Explanation: We can show that there is no prime number pair that gives a sum of 2, so we return an empty array.   Constraints: 1 <= n <= 106
Medium
[ "array", "math", "enumeration", "number-theory" ]
null
[]
2,762
continuous-subarrays
[ "Try using the sliding window technique.", "Use a set or map to keep track of the maximum and minimum of subarrays." ]
/** * @param {number[]} nums * @return {number} */ var continuousSubarrays = function(nums) { };
You are given a 0-indexed integer array nums. A subarray of nums is called continuous if: Let i, i + 1, ..., j be the indices in the subarray. Then, for each pair of indices i <= i1, i2 <= j, 0 <= |nums[i1] - nums[i2]| <= 2. Return the total number of continuous subarrays. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [5,4,2,4] Output: 8 Explanation: Continuous subarray of size 1: [5], [4], [2], [4]. Continuous subarray of size 2: [5,4], [4,2], [2,4]. Continuous subarray of size 3: [4,2,4]. Thereare no subarrys of size 4. Total continuous subarrays = 4 + 3 + 1 = 8. It can be shown that there are no more continuous subarrays.   Example 2: Input: nums = [1,2,3] Output: 6 Explanation: Continuous subarray of size 1: [1], [2], [3]. Continuous subarray of size 2: [1,2], [2,3]. Continuous subarray of size 3: [1,2,3]. Total continuous subarrays = 3 + 2 + 1 = 6.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109
Medium
[ "array", "queue", "sliding-window", "heap-priority-queue", "ordered-set", "monotonic-queue" ]
null
[]
2,763
sum-of-imbalance-numbers-of-all-subarrays
[ "Iterate over all subarrays in a nested fashion. Namely, for each left endpoint, start from nums[left] and add elements nums[left + 1], nums[left + 2], etc.", "To keep track of the imbalance value, maintain a set of added elements.", "Increment the imbalance value whenever a new number is not adjacent (+/- 1) to other old numbers. For example, when you add 3 to [1, 5], or when you add 5 to [1, 3]. For a formal proof, consider three cases: new value is (i) largest, (ii) smallest, (iii) between two old numbers.", "Decrement the imbalance value whenever a new number is adjacent (+/- 1) to two old numbers. For example, when you add 3 to [2, 4]. The imbalance value does not change in the case of one adjacent old number." ]
/** * @param {number[]} nums * @return {number} */ var sumImbalanceNumbers = function(nums) { };
The imbalance number of a 0-indexed integer array arr of length n is defined as the number of indices in sarr = sorted(arr) such that: 0 <= i < n - 1, and sarr[i+1] - sarr[i] > 1 Here, sorted(arr) is the function that returns the sorted version of arr. Given a 0-indexed integer array nums, return the sum of imbalance numbers of all its subarrays. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [2,3,1,4] Output: 3 Explanation: There are 3 subarrays with non-zero imbalance numbers: - Subarray [3, 1] with an imbalance number of 1. - Subarray [3, 1, 4] with an imbalance number of 1. - Subarray [1, 4] with an imbalance number of 1. The imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 3. Example 2: Input: nums = [1,3,3,3,5] Output: 8 Explanation: There are 7 subarrays with non-zero imbalance numbers: - Subarray [1, 3] with an imbalance number of 1. - Subarray [1, 3, 3] with an imbalance number of 1. - Subarray [1, 3, 3, 3] with an imbalance number of 1. - Subarray [1, 3, 3, 3, 5] with an imbalance number of 2. - Subarray [3, 3, 3, 5] with an imbalance number of 1. - Subarray [3, 3, 5] with an imbalance number of 1. - Subarray [3, 5] with an imbalance number of 1. The imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 8.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= nums.length
Hard
[ "array", "hash-table", "ordered-set" ]
null
[]
2,765
longest-alternating-subarray
[ "As the constraints are low, you can check each subarray for the given condition." ]
/** * @param {number[]} nums * @return {number} */ var alternatingSubarray = function(nums) { };
You are given a 0-indexed integer array nums. A subarray s of length m is called alternating if: m is greater than 1. s1 = s0 + 1. The 0-indexed subarray s looks like [s0, s1, s0, s1,...,s(m-1) % 2]. In other words, s1 - s0 = 1, s2 - s1 = -1, s3 - s2 = 1, s4 - s3 = -1, and so on up to s[m - 1] - s[m - 2] = (-1)m. Return the maximum length of all alternating subarrays present in nums or -1 if no such subarray exists. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [2,3,4,3,4] Output: 4 Explanation: The alternating subarrays are [3,4], [3,4,3], and [3,4,3,4]. The longest of these is [3,4,3,4], which is of length 4. Example 2: Input: nums = [4,5,6] Output: 2 Explanation: [4,5] and [5,6] are the only two alternating subarrays. They are both of length 2.   Constraints: 2 <= nums.length <= 100 1 <= nums[i] <= 104
Easy
[ "array", "enumeration" ]
null
[]