id
int64 1
2.39k
| title
stringlengths 3
79
| title_slug
stringlengths 3
79
| question_content
stringlengths 38
1.55k
⌀ | tag
stringlengths 4
122
⌀ | level
stringclasses 3
values | success_rate
float64 14.2
95.5
| total_submission
int64 186
13.2M
| total_accepted
int64 153
6.4M
| question_likes
int64 4
31.2k
| question_dislikes
int64 0
11.5k
| question_hints
stringlengths 19
3.98k
⌀ | similar_question_ids
stringlengths 1
51
⌀ |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2,204 | Find Subsequence of Length K With the Largest Sum | find-subsequence-of-length-k-with-the-largest-sum | You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum. Return any such subsequence as an integer array of length k. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. | Array,Hash Table,Sorting,Heap (Priority Queue) | Easy | 43.6 | 34,727 | 15,145 | 412 | 39 | From a greedy perspective, what k elements should you pick? Could you sort the array while maintaining the index? | 215,1047,1458,2267 |
2,205 | Find Good Days to Rob the Bank | find-good-days-to-rob-the-bank | You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security, where security[i] is the number of guards on duty on the ith day. The days are numbered starting from 0. You are also given an integer time. The ith day is a good day to rob the bank if: More formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time]. Return a list of all days (0-indexed) that are good days to rob the bank. The order that the days are returned in does not matter. | Array,Dynamic Programming,Prefix Sum | Medium | 46.5 | 20,196 | 9,388 | 312 | 15 | The trivial solution is to check the time days before and after each day. There are a lot of repeated operations using this solution. How could we optimize this solution? We can use precomputation to make the solution faster. Use an array to store the number of days before the ith day that is non-increasing, and another array to store the number of days after the ith day that is non-decreasing. | 665,875,1185,1927 |
2,206 | Detonate the Maximum Bombs | detonate-the-maximum-bombs | You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb. The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range. You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges. Given the list of bombs, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb. | Array,Math,Depth-First Search,Breadth-First Search,Graph,Geometry | Medium | 39.9 | 25,051 | 9,999 | 374 | 42 | How can we model the relationship between different bombs? Can "graphs" help us? Bombs are nodes and are connected to other bombs in their range by directed edges. If we know which bombs will be affected when any bomb is detonated, how can we find the total number of bombs that will be detonated if we start from a fixed bomb? Run a Depth First Search (DFS) from every node, and all the nodes it reaches are the bombs that will be detonated. | 529,547,695,1036 |
2,207 | Sequentially Ordinal Rank Tracker | sequentially-ordinal-rank-tracker | A scenic location is represented by its name and attractiveness score, where name is a unique string among all locations and score is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better. You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports: Note that the test data are generated so that at any time, the number of queries does not exceed the number of locations added to the system. Implement the SORTracker class: | Design,Heap (Priority Queue),Data Stream,Ordered Set | Hard | 62.3 | 6,722 | 4,189 | 126 | 25 | If the problem were to find the median of a stream of scenery locations while they are being added, can you solve it? We can use a similar approach as an optimization to avoid repeated sorting. Employ two heaps: left heap and right heap. The left heap is a max-heap, and the right heap is a min-heap. The size of the left heap is k + 1 (best locations), where k is the number of times the get method was invoked. The other locations are maintained in the right heap. Every time when add is being called, we add it to the left heap. If the size of the left heap exceeds k + 1, we move the head element to the right heap. When the get method is invoked again (the k + 1 time it is invoked), we can return the head element of the left heap. But before returning it, if the right heap is not empty, we maintain the left heap to have the best k + 2 items by moving the best location from the right heap to the left heap. | 295,789,1953 |
2,208 | Account Balance | account-balance | null | Database | Medium | 85.3 | 3,515 | 2,997 | 28 | 1 | null | null |
2,209 | Number of Equal Count Substrings | number-of-equal-count-substrings | null | String,Counting,Prefix Sum | Medium | 50.7 | 1,998 | 1,012 | 49 | 4 | The brute force solution is to check every substring, which would TLE. How can we improve this solution? In an equal count substring, the first character appears count times, the second character appears count times, and so on. The length of an equal count substring is the number of unique characters multiplied by count. The length of all equal count substrings are multiples of count. | 3,395,2303 |
2,210 | Find Target Indices After Sorting Array | find-target-indices-after-sorting-array | You are given a 0-indexed integer array nums and a target element target. A target index is an index i such that nums[i] == target. Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order. | Array,Binary Search,Sorting | Easy | 79.1 | 63,516 | 50,251 | 568 | 28 | Try "sorting" the array first. Now find all indices in the array whose values are equal to target. | 34,1256 |
2,211 | K Radius Subarray Averages | k-radius-subarray-averages | You are given a 0-indexed array nums of n integers, and an integer k. The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-radius average is -1. Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i. The average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part. | Array,Sliding Window | Medium | 40.6 | 34,633 | 14,048 | 260 | 10 | To calculate the average of a subarray, you need the sum and the K. K is already given. How could you quickly calculate the sum of a subarray? Use the Prefix Sums method to calculate the subarray sums. It is possible that the sum of all the elements does not fit in a 32-bit integer type. Be sure to use a 64-bit integer type for the prefix sum array. | 209,346,560,643,1445 |
2,212 | Removing Minimum and Maximum From Array | removing-minimum-and-maximum-from-array | You are given a 0-indexed array of distinct integers nums. There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array. | Array,Greedy | Medium | 57.6 | 28,027 | 16,157 | 314 | 16 | There can only be three scenarios for deletions such that both minimum and maximum elements are removed: Scenario 1: Both elements are removed by only deleting from the front. Scenario 2: Both elements are removed by only deleting from the back. Scenario 3: Delete from the front to remove one of the elements, and delete from the back to remove the other element. Compare which of the three scenarios results in the minimum number of moves. | 1538,1770 |
2,213 | Find All People With Secret | find-all-people-with-secret | You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order. | Depth-First Search,Breadth-First Search,Union Find,Graph,Sorting | Hard | 32.8 | 38,441 | 12,595 | 423 | 20 | Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret. | 918 |
2,214 | The Winner University | the-winner-university | null | Database | Easy | 73.2 | 4,926 | 3,604 | 29 | 2 | null | 2223 |
2,215 | Finding 3-Digit Even Numbers | finding-3-digit-even-numbers | You are given an integer array digits, where each element is a digit. The array may contain duplicates. You need to find all the unique integers that follow the given requirements: For example, if the given digits were [1, 2, 3], integers 132 and 312 follow the requirements. Return a sorted array of the unique integers. | Array,Hash Table,Sorting,Enumeration | Easy | 56.4 | 26,389 | 14,880 | 207 | 171 | The range of possible answers includes all even numbers between 100 and 999 inclusive. Could you check each possible answer to see if it could be formed from the digits in the array? | 1421 |
2,216 | Delete the Middle Node of a Linked List | delete-the-middle-node-of-a-linked-list | You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list. The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x. | Linked List,Two Pointers | Medium | 57.2 | 72,447 | 41,449 | 693 | 22 | If a point with a speed s moves n units in a given time, a point with speed 2 * s will move 2 * n units at the same time. Can you use this to find the middle node of a linked list? If you are given the middle node, the node before it, and the node after it, how can you modify the linked list? | 19,143,203,908 |
2,217 | Step-By-Step Directions From a Binary Tree Node to Another | step-by-step-directions-from-a-binary-tree-node-to-another | You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: Return the step-by-step directions of the shortest path from node s to node t. | String,Tree,Depth-First Search,Binary Tree | Medium | 48.3 | 60,129 | 29,023 | 783 | 57 | The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root → s, and root → t. Can you use these two strings to prepare the final answer? Remove the longest common prefix of the two path strings to get the path LCA → s, and LCA → t. Each step in the path of LCA → s should be reversed as 'U'. | 113,236,257,1883 |
2,218 | Paths in Maze That Lead to Same Room | paths-in-maze-that-lead-to-same-room | null | Graph | Medium | 57.9 | 2,785 | 1,612 | 47 | 4 | If the path starts at room i, what properties must the other two rooms in the cycle have? The other two rooms must be connected to room i, and must be connected to each other. | 323,918,1347,2121 |
2,219 | Maximum Number of Words Found in Sentences | maximum-number-of-words-found-in-sentences | A sentence is a list of words that are separated by a single space with no leading or trailing spaces. You are given an array of strings sentences, where each sentences[i] represents a single sentence. Return the maximum number of words that appear in a single sentence. | Array,String | Easy | 89 | 68,223 | 60,728 | 485 | 17 | Process each sentence separately and count the number of words by looking for the number of space characters in the sentence and adding it by 1. | 2173 |
2,220 | Find All Possible Recipes from Given Supplies | find-all-possible-recipes-from-given-supplies | You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients. | Array,Hash Table,String,Graph,Topological Sort | Medium | 42.7 | 49,865 | 21,290 | 600 | 46 | Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this. | 210,1830 |
2,221 | Check if a Parentheses String Can Be Valid | check-if-a-parentheses-string-can-be-valid | A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked, Return true if you can make s a valid parentheses string. Otherwise, return false. | String,Stack,Greedy | Medium | 31.4 | 26,241 | 8,247 | 468 | 18 | Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(' and additional unlocked indices. How can you balance out the locked '(' now? What if you cannot balance any locked '('? | 20,22,678,1371 |
2,222 | Abbreviating the Product of a Range | abbreviating-the-product-of-a-range | You are given two positive integers left and right with left <= right. Calculate the product of all integers in the inclusive range [left, right]. Since the product may be very large, you will abbreviate it following these steps: Return a string denoting the abbreviated product of all integers in the inclusive range [left, right]. | Math | Hard | 28.4 | 6,615 | 1,876 | 52 | 92 | Calculating the number of trailing zeros, the last five digits, and the first five digits can all be done separately. Use a prime factorization property to find the number of trailing zeros. Use modulo to find the last 5 digits. Use a logarithm property to find the first 5 digits. The number of trailing zeros C is nothing but the number of times the product is completely divisible by 10. Since 2 and 5 are the only prime factors of 10, C will be equal to the minimum number of times 2 or 5 appear in the prime factorization of the product. Iterate through the integers from left to right. For every integer, keep dividing it by 2 as long as it is divisible by 2 and C occurrences of 2 haven't been removed in total. Repeat this process for 5. Finally, multiply the integer under modulo of 10^5 with the product obtained till now to obtain the last five digits. The product P can be represented as P=10^(x+y) where x is the integral part and y is the fractional part of x+y. Using the property "if S = A * B, then log(S) = log(A) + log(B)", we can write x+y = log_10(P) = sum(log_10(i)) for each integer i in [left, right]. Once we obtain the sum, the first five digits can be represented as floor(10^(y+4)). | 172 |
2,223 | The Number of Rich Customers | the-number-of-rich-customers | null | Database | Easy | 80.9 | 4,616 | 3,733 | 14 | 11 | null | 2214 |
2,224 | Drop Type 1 Orders for Customers With Type 0 Orders | drop-type-1-orders-for-customers-with-type-0-orders | null | Database | Medium | 90.7 | 3,328 | 3,017 | 26 | 6 | null | null |
2,225 | Substrings That Begin and End With the Same Letter | substrings-that-begin-and-end-with-the-same-letter | null | Hash Table,Math,String,Counting,Prefix Sum | Medium | 68.6 | 4,554 | 3,123 | 62 | 2 | In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") and 1 substring begins with the third "a" ("a"). There is a total of 3 + 2 + 1 = 6 substrings that begin and end with "a". If a character appears i times in the string, there are i * (i + 1) / 2 substrings that begin and end with that character. | 1635,1890,2036,2303 |
2,226 | Rings and Rods | rings-and-rods | There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9. You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where: For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1. Return the number of rods that have all three colors of rings on them. | Hash Table,String | Easy | 81.7 | 34,578 | 28,264 | 355 | 10 | For every rod, look through ‘rings’ to see if the rod contains all colors. Create 3 booleans, 1 for each color, to store if that color is present for the current rod. If all 3 are true after looking through the string, then the rod contains all the colors. | 2053 |
2,227 | Sum of Subarray Ranges | sum-of-subarray-ranges | You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array. | Array,Stack,Monotonic Stack | Medium | 60.3 | 39,464 | 23,805 | 626 | 29 | Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j]. | 496,943,1305,1885 |
2,228 | Watering Plants II | watering-plants-ii | Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way: Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants. | Array,Two Pointers,Simulation | Medium | 51.3 | 20,814 | 10,674 | 116 | 120 | Try "simulating" the process. Since watering each plant takes the same amount of time, where will Alice and Bob meet if they start watering the plants simultaneously? How can you use this to optimize your solution? What will you do when both Alice and Bob have to water the same plant? | 1310 |
2,229 | Maximum Fruits Harvested After at Most K Steps | maximum-fruits-harvested-after-at-most-k-steps | Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique. You are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest. | Array,Binary Search,Sliding Window,Prefix Sum | Hard | 35.1 | 17,447 | 6,129 | 253 | 15 | Does an optimal path have very few patterns? For example, could a path that goes left, turns and goes right, then turns again and goes left be any better than a path that simply goes left, turns, and goes right? The optimal path turns at most once. That is, the optimal path is one of these: to go left only; to go right only; to go left, turn and go right; or to go right, turn and go left. Moving x steps left then k-x steps right gives you a range of positions that you can reach. Use prefix sums to get the sum of all fruits for each possible range. Use a similar strategy for all the paths that go right, then turn and go left. | 1499 |
2,230 | Minimum Cost to Reach City With Discounts | minimum-cost-to-reach-city-with-discounts | null | Graph,Shortest Path | Medium | 56.7 | 3,514 | 1,991 | 82 | 6 | Try to construct a graph out of highways. What type of graph is this? We essentially need to find the minimum distance to get from node 0 to node n - 1 in an undirected weighted graph. What algorithm should we use to do this? Use Dijkstra's algorithm to find the minimum weight path. Keep track of the minimum distance to each vertex with d discounts left | 803,1100,2040 |
2,231 | Find First Palindromic String in the Array | find-first-palindromic-string-in-the-array | Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "". A string is palindromic if it reads the same forward and backward. | Array,Two Pointers,String | Easy | 79.5 | 50,602 | 40,250 | 347 | 12 | Iterate through the elements in order. As soon as the current element is a palindrome, return it. To check if an element is a palindrome, can you reverse the string? | 125 |
2,232 | Adding Spaces to a String | adding-spaces-to-a-string | You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. Return the modified string after the spaces have been added. | Array,String,Simulation | Medium | 56 | 36,845 | 20,644 | 248 | 26 | Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for the space locations is sorted, use a pointer to keep track of the next index to place a space. Only increment the pointer once a space has been appended. Ensure that your append operation can be done in O(1). | null |
2,233 | Number of Smooth Descent Periods of a Stock | number-of-smooth-descent-periods-of-a-stock | You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day. A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule. Return the number of smooth descent periods. | Array,Math,Dynamic Programming | Medium | 55.3 | 32,528 | 17,988 | 326 | 12 | Any array is a series of adjacent longest possible smooth descent periods. For example, [5,3,2,1,7,6] is [5] + [3,2,1] + [7,6]. Think of a 2-pointer approach to traverse the array and find each longest possible period. Suppose you found the longest possible period with a length of k. How many periods are within that period? How can you count them quickly? Think of the formula to calculate the sum of 1, 2, 3, ..., k. | 713,1061 |
2,234 | Minimum Operations to Make the Array K-Increasing | minimum-operations-to-make-the-array-k-increasing | You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1. In one operation, you can choose an index i and change arr[i] into any positive integer. Return the minimum number of operations required to make the array K-increasing for the given k. | Array,Binary Search | Hard | 36.4 | 23,198 | 8,433 | 467 | 8 | Can we divide the array into non-overlapping subsequences and simplify the problem? In the final array, arr[i-k] ≤ arr[i] should hold. We can use this to divide the array into at most k non-overlapping sequences, where arr[i] will belong to the (i%k)th sequence. Now our problem boils down to performing the minimum operations on each sequence such that it becomes non-decreasing. Our answer will be the sum of operations on each sequence. Which indices of a sequence should we not change in order to count the minimum operations? Can finding the longest non-decreasing subsequence of the sequence help? | 300,819 |
2,235 | Capitalize the Title | capitalize-the-title | You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: Return the capitalized title. | String | Easy | 59.6 | 36,662 | 21,853 | 253 | 26 | Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem. | 520,742 |
2,236 | Maximum Twin Sum of a Linked List | maximum-twin-sum-of-a-linked-list | In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list. | Linked List,Two Pointers,Stack | Medium | 82.2 | 34,349 | 28,247 | 485 | 21 | How can "reversing" a part of the linked list help find the answer? We know that the nodes of the first half are twins of nodes in the second half, so try dividing the linked list in half and reverse the second half. How can two pointers be used to find every twin sum optimally? Use two different pointers pointing to the first nodes of the two halves of the linked list. The second pointer will point to the first node of the reversed half, which is the (n-1-i)th node in the original linked list. By moving both pointers forward at the same time, we find all twin sums. | 206,234,908 |
2,237 | Longest Palindrome by Concatenating Two Letter Words | longest-palindrome-by-concatenating-two-letter-words | You are given an array of strings words. Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once. Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0. A palindrome is a string that reads the same forward and backward. | Array,Hash Table,String,Greedy,Counting | Medium | 38.3 | 33,870 | 12,956 | 381 | 8 | A palindrome must be mirrored over the center. Suppose we have a palindrome. If we prepend the word "ab" on the left, what must we append on the right to keep it a palindrome? We must append "ba" on the right. The number of times we can do this is the minimum of (occurrences of "ab") and (occurrences of "ba"). For words that are already palindromes, e.g. "aa", we can prepend and append these in pairs as described in the previous hint. We can also use exactly one in the middle to form an even longer palindrome. | 336,409 |
2,238 | A Number After a Double Reversal | a-number-after-a-double-reversal | Reversing an integer means to reverse all its digits. Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false. | Math | Easy | 76.9 | 34,908 | 26,859 | 224 | 14 | Other than the number 0 itself, any number that ends with 0 would lose some digits permanently when reversed. | 7,190 |
2,239 | Execution of All Suffix Instructions Staying in a Grid | execution-of-all-suffix-instructions-staying-in-a-grid | There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol). You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down). The robot can begin executing from any ith instruction in s. It executes the instructions one by one towards the end of s but it stops if either of these conditions is met: Return an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the ith instruction in s. | String,Simulation | Medium | 83.2 | 17,397 | 14,480 | 239 | 23 | The constraints are not very large. Can we simulate the execution by starting from each index of s? Before any of the stopping conditions is met, stop the simulation for that index and set the answer for that index. | 576,657 |
2,240 | Intervals Between Identical Elements | intervals-between-identical-elements | You are given a 0-indexed array of n integers arr. The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|. Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i]. Note: |x| is the absolute value of x. | Array,Hash Table,Prefix Sum | Medium | 42.1 | 25,891 | 10,906 | 471 | 20 | For each unique value found in the array, store a sorted list of indices of elements that have this value in the array. One way of doing this is to use a HashMap that maps the values to their list of indices. Update this mapping as you iterate through the array. Process each list of indices separately and get the sum of intervals for the elements of that value by utilizing prefix sums. For each element, keep track of the sum of indices of the identical elements that have come before and that will come after respectively. Use this to calculate the sum of intervals for that element to the rest of the elements with identical values. | 523 |
2,241 | Recover the Original Array | recover-the-original-array | Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher, but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher, return the original array arr. In case the answer is not unique, return any valid array. Note: The test cases are generated such that there exists at least one valid array arr. | Array,Hash Table,Sorting,Enumeration | Hard | 37.5 | 16,890 | 6,340 | 215 | 26 | If we fix the value of k, how can we check if an original array exists for the fixed k? The smallest value of nums is obtained by subtracting k from the smallest value of the original array. How can we use this to reduce the search space for finding a valid k? You can compute every possible k by using the smallest value of nums (as lower[i]) against every other value in nums (as the corresponding higher[i]). For every computed k, greedily pair up the values in nums. This can be done sorting nums, then using a map to store previous values and searching that map for a corresponding lower[i] for the current nums[j] (as higher[i]). | 2109,2117 |
2,242 | Subsequence of Size K With the Largest Even Sum | subsequence-of-size-k-with-the-largest-even-sum | null | Array,Greedy,Sorting | Medium | 39.1 | 2,823 | 1,105 | 30 | 1 | Is the sum of two even numbers even or odd? How about two odd numbers? One odd number and one even number? If there is an even number of odd numbers, the sum will be even and vice versa. Create an integer array to store all the even numbers in nums and another array to store all the odd numbers in nums. Sort both arrays. | 410,1121,1631 |
2,243 | Check if All A's Appears Before All B's | check-if-all-as-appears-before-all-bs | Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false. | String | Easy | 72.5 | 38,380 | 27,813 | 283 | 3 | You can check the opposite: check if there is a ‘b’ before an ‘a’. Then, negate and return that answer. s should not have any occurrences of “ba” as a substring. | 1756,1878,2168 |
2,244 | Number of Laser Beams in a Bank | number-of-laser-beams-in-a-bank | Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank. | Array,Math,String,Matrix | Medium | 83.3 | 29,234 | 24,343 | 326 | 29 | What is the commonality between security devices on the same row? Each device on the same row has the same number of beams pointing towards the devices on the next row with devices. If you were given an integer array where each element is the number of security devices on each row, can you solve it? Convert the input to such an array, skip any row with no security device, then find the sum of the product between adjacent elements. | 73 |
2,245 | Destroying Asteroids | destroying-asteroids | You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed. Return true if all asteroids can be destroyed. Otherwise, return false. | Array,Greedy,Sorting | Medium | 48.4 | 37,728 | 18,243 | 198 | 106 | Choosing the asteroid to collide with can be done greedily. If an asteroid will destroy the planet, then every bigger asteroid will also destroy the planet. You only need to check the smallest asteroid at each collision. If it will destroy the planet, then every other asteroid will also destroy the planet. Sort the asteroids in non-decreasing order by mass, then greedily try to collide with the asteroids in that order. | 735 |
2,246 | Maximum Employees to Be Invited to a Meeting | maximum-employees-to-be-invited-to-a-meeting | A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting. | Depth-First Search,Graph,Topological Sort | Hard | 29.9 | 15,292 | 4,578 | 471 | 6 | From the given array favorite, create a graph where for every index i, there is a directed edge from favorite[i] to i. The graph will be a combination of cycles and chains of acyclic edges. Now, what are the ways in which we can choose employees to sit at the table? The first way by which we can choose employees is by selecting a cycle of the graph. It can be proven that in this case, the employees that do not lie in the cycle can never be seated at the table. The second way is by combining acyclic chains. At most two chains can be combined by a cycle of length 2, where each chain ends on one of the employees in the cycle. | 684,2176,2198 |
2,247 | Number of Unique Flavors After Sharing K Candies | number-of-unique-flavors-after-sharing-k-candies | null | Array,Hash Table,Sliding Window | Medium | 57.8 | 2,194 | 1,268 | 42 | 1 | For every group of k consecutive candies, count the number of unique flavors not inside that group. Return the largest number of unique flavors. When calculating an adjacent group of k consecutive candies, can you use some of your previous calculations? Use a sliding window where the window is the group of k consecutive candies you are sharing. Use a hash map to store the number of candies of each type you can keep. | 546,1034 |
2,248 | Minimum Cost of Buying Candies With Discount | minimum-cost-of-buying-candies-with-discount | A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies. | Array,Greedy,Sorting | Easy | 60.6 | 34,300 | 20,777 | 224 | 8 | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? | 561,1306 |
2,249 | Count the Hidden Sequences | count-the-hidden-sequences | You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i]. You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0. | Array,Prefix Sum | Medium | 35.1 | 32,252 | 11,334 | 356 | 37 | Fix the first element of the hidden sequence to any value x and ignore the given bounds. Notice that we can then determine all the other elements of the sequence by using the differences array. We will also be able to determine the difference between the minimum and maximum elements of the sequence. Notice that the value of x does not affect this. We now have the ‘range’ of the sequence (difference between min and max element), we can then calculate how many ways there are to fit this range into the given range of lower to upper. Answer is (upper - lower + 1) - (range of sequence) | null |
2,250 | K Highest Ranked Items Within a Price Range | k-highest-ranked-items-within-a-price-range | You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following: It takes 1 step to travel between adjacent grid cells. You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] (inclusive). You are further given an integer k. You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: Return the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k reachable items within the price range, return all of them. | Array,Breadth-First Search,Sorting,Heap (Priority Queue),Matrix | Medium | 39.8 | 20,424 | 8,134 | 249 | 110 | Could you determine the rank of every item efficiently? We can perform a breadth-first search from the starting position and know the length of the shortest path from start to every item. Sort all the items according to the conditions listed in the problem, and return the first k (or all if less than k exist) items as the answer. | 215,1117 |
2,251 | Number of Ways to Divide a Long Corridor | number-of-ways-to-divide-a-long-corridor | Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7. If there is no way, return 0. | Math,String,Dynamic Programming | Hard | 40 | 16,228 | 6,485 | 178 | 17 | Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k plants between two adjacent segments, there are k + 1 positions (ways) you could install the divider you must install. The problem now becomes: Find the product of all possible positions between every two adjacent segments. | 639,1669,1831 |
2,252 | The Airport With the Most Traffic | the-airport-with-the-most-traffic | null | Database | Medium | 69.2 | 3,271 | 2,264 | 17 | 5 | null | null |
2,253 | Build the Equation | build-the-equation | null | Database | Hard | 58 | 1,084 | 629 | 10 | 19 | null | null |
2,254 | Check if Every Row and Column Contains All Numbers | check-if-every-row-and-column-contains-all-numbers | An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false. | Array,Hash Table,Matrix | Easy | 52.2 | 49,781 | 25,978 | 309 | 19 | Use for loops to check each row for every number from 1 to n. Similarly, do the same for each column. For each check, you can keep a set of the unique elements in the checked row/col. By the end of the check, the size of the set should be n. | 36,1677 |
2,255 | Minimum Swaps to Group All 1's Together II | minimum-swaps-to-group-all-1s-together-ii | A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location. | Array,Sliding Window | Medium | 47.6 | 27,620 | 13,137 | 547 | 6 | Notice that the number of 1’s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1’s. The number of swaps required is the number of 0’s in the subarray. To eliminate the circular property of the array, we can append the original array to itself. Then, we check each subarray of length total. How do we avoid recounting the number of 0’s in the subarray each time? The Sliding Window technique can help. | 1107 |
2,256 | Count Words Obtained After Adding a Letter | count-words-obtained-after-adding-a-letter | You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only. For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords. The conversion operation is described in the following two steps: Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords. Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process. | Array,Hash Table,String,Bit Manipulation,Sorting | Medium | 38.1 | 37,384 | 14,252 | 336 | 70 | Which data structure can be used to efficiently check if a string exists in startWords? After appending a letter, all letters of a string can be rearranged in any possible way. How can we use this to reduce our search space while checking if a string in targetWords can be obtained from a string in startWords? | 1697,1743,1818 |
2,257 | Earliest Possible Day of Full Bloom | earliest-possible-day-of-full-bloom | You have n flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed integer arrays plantTime and growTime, of length n each: From the beginning of day 0, you can plant the seeds in any order. Return the earliest possible day where all seeds are blooming. | Array,Greedy,Sorting | Hard | 67.5 | 10,030 | 6,771 | 243 | 12 | List the planting like the diagram above shows, where a row represents the timeline of a seed. A row i is above another row j if the last day planting seed i is ahead of the last day for seed j. Does it have any advantage to spend some days to plant seed j before completely planting seed i? No. It does not help seed j but could potentially delay the completion of seed i, resulting in a worse final answer. Remaining focused is a part of the optimal solution. Sort the seeds by their growTime in descending order. Can you prove why this strategy is the other part of the optimal solution? Note the bloom time of a seed is the sum of plantTime of all seeds preceding this seed plus the growTime of this seed. There is no way to improve this strategy. The seed to bloom last dominates the final answer. Exchanging the planting of this seed with another seed with either a larger or smaller growTime will result in a potentially worse answer. | 1605 |
2,258 | Elements in Array After Removing and Replacing Elements | elements-in-array-after-removing-and-replacing-elements | null | Array | Medium | 73.9 | 1,201 | 887 | 35 | 5 | Try to find a pattern in how nums changes. Let m be the original length of nums. If time_i / m (integer division) is even, then nums is at its original size or decreasing in size. If it is odd, then it is empty, or increasing in size. time_i % m can be used to find how many elements are in nums at minute time_i. | null |
2,259 | Minimum Operations to Remove Adjacent Ones in Matrix | minimum-operations-to-remove-adjacent-ones-in-matrix | null | Array,Graph,Matrix | Hard | 41 | 1,016 | 417 | 25 | 4 | Consider each cell containing a 1 as a vertex whose neighbors are the cells 4-directionally connected to it. The grid then becomes a bipartite graph. You want to find the smallest set of vertices such that every edge in the graph has an endpoint in this set. If you remove every vertex in this set from the graph, then all the 1’s will be disconnected. Are there any well-known algorithms for finding this set? This set of vertices is called a minimum vertex cover. You can find the size of a minimum vertex cover by finding the size of a maximum matching (Konig’s theorem). There are well-known algorithms such as Kuhn’s algorithm and Hopcroft-Karp-Karzanov algorithm which can find a maximum matching in a bipartite graph quickly. | 73,542,1409,2268 |
2,260 | Divide a String Into Groups of Size k | divide-a-string-into-groups-of-size-k | A string s can be partitioned into groups of size k using the following procedure: Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s. Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure. | String,Simulation | Easy | 65.5 | 36,797 | 24,114 | 238 | 10 | Using the length of the string and k, can you count the number of groups the string can be divided into? Try completing each group using characters from the string. If there aren’t enough characters for the last group, use the fill character to complete the group. | 68,857 |
2,261 | All Divisions With the Highest Score of a Binary Array | all-divisions-with-the-highest-score-of-a-binary-array | You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) numsleft and numsright: The division score of an index i is the sum of the number of 0's in numsleft and the number of 1's in numsright. Return all distinct indices that have the highest possible division score. You may return the answer in any order. | Array | Medium | 62 | 30,874 | 19,132 | 302 | 8 | When you iterate the array, maintain the number of zeros and ones on the left side. Can you quickly calculate the number of ones on the right side? The number of ones on the right side equals the number of ones in the whole array minus the number of ones on the left side. Alternatively, you can quickly calculate it by using a prefix sum array. | 474,487,510,561,1422 |
2,262 | Solving Questions With Brainpower | solving-questions-with-brainpower | You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri]. The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0) and make a decision whether to solve or skip each question. Solving question i will earn you pointsi points but you will be unable to solve each of the next brainpoweri questions. If you skip question i, you get to make the decision on the next question. Return the maximum points you can earn for the exam. | Array,Dynamic Programming | Medium | 44.3 | 40,097 | 17,782 | 532 | 7 | For each question, we can either solve it or skip it. How can we use Dynamic Programming to decide the most optimal option for each problem? We store for each question the maximum points we can earn if we started the exam on that question. If we skip a question, then the answer for it will be the same as the answer for the next question. If we solve a question, then the answer for it will be the points of the current question plus the answer for the next solvable question. The maximum of these two values will be the answer to the current question. | 198,403 |
2,263 | Maximum Running Time of N Computers | maximum-running-time-of-n-computers | You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously. | Array,Binary Search,Greedy,Sorting | Hard | 37.5 | 20,733 | 7,779 | 437 | 10 | For a given running time, can you determine if it is possible to run all n computers simultaneously? Try to use Binary Search to find the maximal running time | 453,1771,2180,2294 |
2,264 | Minimum Sum of Four Digit Number After Splitting Digits | minimum-sum-of-four-digit-number-after-splitting-digits | You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. Return the minimum possible sum of new1 and new2. | Math,Greedy,Sorting | Easy | 88 | 30,322 | 26,673 | 295 | 36 | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. | 258 |
2,265 | Partition Array According to Given Pivot | partition-array-according-to-given-pivot | You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied: Return nums after the rearrangement. | Array,Two Pointers,Simulation | Medium | 82.3 | 22,767 | 18,738 | 232 | 19 | Could you put the elements smaller than the pivot and greater than the pivot in a separate list as in the sequence that they occur? With the separate lists generated, could you then generate the result? | 86,2271 |
2,266 | Minimum Cost to Set Cooking Time | minimum-cost-to-set-cooking-time | A generic microwave supports cooking times for: To set the cooking time, you push at most four digits. The microwave normalizes what you push as four digits by prepending zeroes. It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example, You are given integers startAt, moveCost, pushCost, and targetSeconds. Initially, your finger is on the digit startAt. Moving the finger above any specific digit costs moveCost units of fatigue. Pushing the digit below the finger once costs pushCost units of fatigue. There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost. Return the minimum cost to set targetSeconds seconds of cooking time. Remember that one minute consists of 60 seconds. | Math,Enumeration | Medium | 33.7 | 20,187 | 6,810 | 128 | 397 | Define a separate function Cost(mm, ss) where 0 <= mm <= 99 and 0 <= ss <= 99. This function should calculate the cost of setting the cocking time to mm minutes and ss seconds The range of the minutes is small (i.e., [0, 99]), how can you use that? For every mm in [0, 99], calculate the needed ss to make mm:ss equal to targetSeconds and minimize the cost of setting the cocking time to mm:ss Be careful in some cases when ss is not in the valid range [0, 99]. | 539 |
2,267 | Minimum Difference in Sums After Removal of Elements | minimum-difference-in-sums-after-removal-of-elements | You are given a 0-indexed integer array nums consisting of 3 * n elements. You are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts: The difference in sums of the two parts is denoted as sumfirst - sumsecond. Return the minimum difference possible between the sums of the two parts after the removal of n elements. | Array,Dynamic Programming,Heap (Priority Queue) | Hard | 45.7 | 10,058 | 4,592 | 321 | 5 | The lowest possible difference can be obtained when the sum of the first n elements in the resultant array is minimum, and the sum of the next n elements is maximum. For every index i, think about how you can find the minimum possible sum of n elements with indices lesser or equal to i, if possible. Similarly, for every index i, try to find the maximum possible sum of n elements with indices greater or equal to i, if possible. Now for all indices, check if we can consider it as the partitioning index and hence find the answer. | 238,2204 |
2,268 | Remove All Ones With Row and Column Flips | remove-all-ones-with-row-and-column-flips | null | Array,Math,Bit Manipulation,Matrix | Medium | 76.7 | 15,251 | 11,695 | 225 | 59 | Does the order, in which you do the operations, matter? No, it does not. An element will keep its original value if the number of operations done on it is even and vice versa. This also means that doing more than 1 operation on the same row or column is unproductive. Try working backward, start with a matrix of all zeros and try to construct grid using operations. Start with operations on columns, after doing them what do you notice about each row? Each row is the exact same. If we then flip some rows, that leaves only two possible arrangements for each row: the same as the original or the opposite. | 891,1409,2259,2314 |
2,269 | Count Elements With Strictly Smaller and Greater Elements | count-elements-with-strictly-smaller-and-greater-elements | Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums. | Array,Sorting | Easy | 60.5 | 42,268 | 25,577 | 243 | 7 | All the elements in the array should be counted except for the minimum and maximum elements. If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums)) This formula will not work in case the array has all the elements equal, why? | 745 |
2,270 | Find All Lonely Numbers in the Array | find-all-lonely-numbers-in-the-array | You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums. You may return the answer in any order. | Array,Hash Table,Counting | Medium | 60.6 | 37,637 | 22,804 | 212 | 31 | For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map. | 1966 |
2,271 | Rearrange Array Elements by Sign | rearrange-array-elements-by-sign | You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers. You should rearrange the elements of nums such that the modified array follows the given conditions: Return the modified array after rearranging the elements to satisfy the aforementioned conditions. | Array,Two Pointers,Simulation | Medium | 82.1 | 33,087 | 27,171 | 362 | 23 | Divide the array into two parts- one comprising of only positive integers and the other of negative integers. Merge the two parts to get the resultant array. | 376,958,2265,2327 |
2,272 | Maximum Good People Based on Statements | maximum-good-people-based-on-statements | There are two types of persons: You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following: Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n. Return the maximum number of people who can be good based on the statements made by the n people. | Array,Backtracking,Bit Manipulation,Enumeration | Hard | 46.2 | 17,765 | 8,200 | 305 | 66 | You should test every possible assignment of good and bad people, using a bitmask. In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid. If the assignment is valid, count how many people are good and keep track of the maximum. | 1381 |
2,273 | Pour Water Between Buckets to Make Water Levels Equal | pour-water-between-buckets-to-make-water-levels-equal | null | Array,Binary Search | Medium | 68.5 | 1,262 | 864 | 44 | 3 | What is the range that the answer must fall into? The answer has to be in the range [0, max(buckets)] (inclusive). For a number x, is there an efficient way to check if it is possible to make the amount of water in each bucket x. Let in be the total amount of water that needs to be poured into buckets and out be the total amount of water that needs to be poured out of buckets to make the amount of water in each bucket x. If out - (out * loss) >= in, then it is possible. | 33,162,453 |
2,274 | Keep Multiplying Found Values by Two | keep-multiplying-found-values-by-two | You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums. You then do the following steps: Return the final value of original. | Array,Hash Table,Sorting,Simulation | Easy | 73.7 | 44,673 | 32,921 | 254 | 11 | Repeatedly iterate through the array and check if the current value of original is in the array. If original is not found, stop and return its current value. Otherwise, multiply original by 2 and repeat the process. Use set data structure to check the existence faster. | 748,1468 |
2,275 | Find Substring With Given Hash Value | find-substring-with-given-hash-value | The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function: Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue. The test cases will be generated such that an answer always exists. A substring is a contiguous non-empty sequence of characters within a string. | String,Sliding Window,Rolling Hash,Hash Function | Hard | 20.9 | 42,682 | 8,917 | 295 | 338 | How can we update the hash value efficiently while iterating instead of recalculating it each time? Use the rolling hash method. | 1244 |
2,276 | Groups of Strings | groups-of-strings | You are given a 0-indexed array of strings words. Each string consists of lowercase English letters only. No letter occurs more than once in any string of words. Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations: The array words can be divided into one or more non-intersecting groups. A string belongs to a group if any one of the following is true: Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. Return an array ans of size 2 where: | String,Bit Manipulation,Union Find | Hard | 24.6 | 21,927 | 5,391 | 241 | 35 | Can we build a graph from words, where there exists an edge between nodes i and j if words[i] and words[j] are connected? The problem now boils down to finding the total number of components and the size of the largest component in the graph. How can we use bit masking to reduce the search space while adding edges to node i? | 126,869,989 |
2,277 | Count Equal and Divisible Pairs in an Array | count-equal-and-divisible-pairs-in-an-array | null | Array | Easy | 80.4 | 27,658 | 22,227 | 176 | 5 | For every possible pair of indices (i, j) where i < j, check if it satisfies the given conditions. | 2116 |
2,278 | Find Three Consecutive Integers That Sum to a Given Number | find-three-consecutive-integers-that-sum-to-a-given-number | Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array. | Math,Simulation | Medium | 60.4 | 30,561 | 18,456 | 234 | 60 | Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number? Notice the sum of the numbers will be 3x. Can you solve for x? | 128 |
2,279 | Maximum Split of Positive Even Integers | maximum-split-of-positive-even-integers | You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order. | Math,Greedy | Medium | 54.6 | 26,382 | 14,415 | 331 | 38 | First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the first k - 1 even elements which is less than finalSum. We then add the difference over to the kth element. | null |
2,280 | Count Good Triplets in an Array | count-good-triplets-in-an-array | You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. Return the total number of good triplets. | Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set | Hard | 34 | 10,057 | 3,422 | 257 | 10 | For every value y, how can you find the number of values x (0 ≤ x, y ≤ n - 1) such that x appears before y in both of the arrays? Similarly, for every value y, try finding the number of values z (0 ≤ y, z ≤ n - 1) such that z appears after y in both of the arrays. Now, for every value y, count the number of good triplets that can be formed if y is considered as the middle element. | 315,334,1772 |
2,281 | The Number of Passengers in Each Bus I | the-number-of-passengers-in-each-bus-i | null | Database | Medium | 50.6 | 3,590 | 1,818 | 30 | 4 | null | null |
2,282 | Choose Numbers From Two Arrays in Range | choose-numbers-from-two-arrays-in-range | null | Array,Dynamic Programming | Hard | 54 | 810 | 437 | 15 | 2 | If you know the possible sums you can get for a range [l, r], how can you use this information to calculate the possible sums you can get for a range [l, r + 1]? For the range [l, r], if it is possible to choose elements such that the sum of elements you picked from nums1 is x and the sum of elements you picked from nums2 is y, then (x + nums1[r + 1], y) and (x, y + nums2[r + 1]) are possible sums you can get in the range [l, r + 1]. How can we save the possible sums obtainable at a given index so that we can reuse this information later? | 349,350,1989,2029 |
2,283 | Sort Even and Odd Indices Independently | sort-even-and-odd-indices-independently | You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules: Return the array formed after rearranging the values of nums. | Array,Sorting | Easy | 67.5 | 36,017 | 24,326 | 256 | 12 | Try to separate the elements at odd indices from the elements at even indices. Sort the two groups of elements individually. Combine them to form the resultant array. | 941,958 |
2,284 | Smallest Value of the Rearranged Number | smallest-value-of-the-rearranged-number | You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value. Note that the sign of the number does not change after rearranging the digits. | Math,Sorting | Medium | 50.7 | 39,260 | 19,915 | 287 | 9 | For positive numbers, the leading digit should be the smallest nonzero digit. Then the remaining digits follow in ascending order. For negative numbers, the digits should be arranged in descending order. | 179 |
2,285 | Design Bitset | design-bitset | A Bitset is a data structure that compactly stores bits. Implement the Bitset class: | Array,Hash Table,Design | Medium | 29.2 | 44,455 | 12,986 | 349 | 34 | Note that flipping a bit twice does nothing. In order to determine the value of a bit, consider how you can efficiently count the number of flips made on the bit since its latest update. | 1512 |
2,286 | Minimum Time to Remove All Cars Containing Illegal Goods | minimum-time-to-remove-all-cars-containing-illegal-goods | You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times: Return the minimum time to remove all the cars containing illegal goods. Note that an empty sequence of cars is considered to have no cars containing illegal goods. | String,Dynamic Programming | Hard | 39 | 19,883 | 7,745 | 467 | 7 | Build an array withoutFirst where withoutFirst[i] stores the minimum time to remove all the cars containing illegal goods from the ‘suffix’ of the sequence starting from the ith car without using any type 1 operations. Next, build an array onlyFirst where onlyFirst[i] stores the minimum time to remove all the cars containing illegal goods from the ‘prefix’ of the sequence ending on the ith car using only type 1 operations. Finally, we can compare the best way to split the operations amongst these two types by finding the minimum time across all onlyFirst[i] + withoutFirst[i + 1]. | 1037 |
2,287 | Minimum Number of Lines to Cover Points | minimum-number-of-lines-to-cover-points | null | Array,Hash Table,Math,Dynamic Programming,Backtracking,Bit Manipulation,Geometry,Bitmask | Medium | 46.7 | 1,534 | 716 | 23 | 6 | What is the highest possible answer for a set of n points? The highest possible answer is n / 2 (rounded up). This is because you can cover at least two points with a line, and if n is odd, you need to add one extra line to cover the last point. Suppose you have a line covering two points, how can you quickly check if a third point is also covered by that line? Calculate the slope from the first point to the second point. If the slope from the first point to the third point is the same, then it is also covered by that line. | 149,1706 |
2,288 | Count Operations to Obtain Zero | count-operations-to-obtain-zero | You are given two non-negative integers num1 and num2. In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2. Return the number of operations required to make either num1 = 0 or num2 = 0. | Math,Simulation | Easy | 75.3 | 36,407 | 27,423 | 200 | 5 | Try simulating the process until either of the two integers is zero. Count the number of operations done. | 1444 |
2,289 | Minimum Operations to Make the Array Alternating | minimum-operations-to-make-the-array-alternating | You are given a 0-indexed array nums consisting of n positive integers. The array nums is called alternating if: In one operation, you can choose an index i and change nums[i] into any positive integer. Return the minimum number of operations required to make the array alternating. | Array,Hash Table,Greedy,Counting | Medium | 32.8 | 46,488 | 15,235 | 349 | 256 | Count the frequency of each element in odd positions in the array. Do the same for elements in even positions. To minimize the number of operations we need to maximize the number of elements we keep from the original array. What are the possible combinations of elements we can choose from odd indices and even indices so that the number of unchanged elements is maximized? | 1355,2017 |
2,290 | Removing Minimum Number of Magic Beans | removing-minimum-number-of-magic-beans | You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags. Return the minimum number of magic beans that you have to remove. | Array,Sorting,Prefix Sum | Medium | 40.9 | 34,492 | 14,124 | 456 | 26 | Notice that if we choose to make x bags of beans empty, we should choose the x bags with the least amount of beans. Notice that if the minimum number of beans in a non-empty bag is m, then the best way to make all bags have an equal amount of beans is to reduce all the bags to have m beans. Can we iterate over how many bags we should remove and choose the one that minimizes the total amount of beans to remove? Sort the bags of beans first. | 462,1776 |
2,291 | Maximum AND Sum of Array | maximum-and-sum-of-array | You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots. You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. Return the maximum possible AND sum of nums given numSlots slots. | Array,Dynamic Programming,Bit Manipulation,Bitmask | Hard | 43.1 | 12,204 | 5,263 | 220 | 11 | Can you think of a dynamic programming solution to this problem? Can you use a bitmask to represent the state of the slots? | 1989 |
2,292 | Counting Words With a Given Prefix | counting-words-with-a-given-prefix | You are given an array of strings words and a string pref. Return the number of strings in words that contain pref as a prefix. A prefix of a string s is any leading contiguous substring of s. | Array,String | Easy | 77.7 | 35,648 | 27,707 | 190 | 3 | Go through each word in words and increment the answer if pref is a prefix of the word. | 1566 |
2,293 | Minimum Number of Steps to Make Two Strings Anagram II | minimum-number-of-steps-to-make-two-strings-anagram-ii | You are given two strings s and t. In one step, you can append any character to either s or t. Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering. | Hash Table,String,Counting | Medium | 70.4 | 29,879 | 21,044 | 223 | 4 | Notice that for anagrams, the order of the letters is irrelevant. For each letter, we can count its frequency in s and t. For each letter, its contribution to the answer is the absolute difference between its frequency in s and t. | 1469 |
2,294 | Minimum Time to Complete Trips | minimum-time-to-complete-trips | You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip. Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus. You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips. | Array,Binary Search | Medium | 29.6 | 64,231 | 19,043 | 517 | 24 | For a given amount of time, how can we count the total number of trips completed by all buses within that time? Consider using binary search. | 1335,2000,2188,2263 |
2,295 | Minimum Time to Finish the Race | minimum-time-to-finish-the-race | You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race. | Array,Dynamic Programming | Hard | 40.4 | 14,102 | 5,697 | 315 | 9 | What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values? | 2013 |
2,296 | The Number of Passengers in Each Bus II | the-number-of-passengers-in-each-bus-ii | null | Database | Hard | 49.9 | 817 | 408 | 16 | 7 | null | null |
2,297 | Amount of New Area Painted Each Day | amount-of-new-area-painted-each-day | null | Array,Segment Tree,Ordered Set | Hard | 60.4 | 5,584 | 3,372 | 69 | 9 | What’s a good way to keep track of intervals that you have already painted? Create an array of all 1’s, and when you have painted an interval, set the values in that interval to 0. Using this array, how can you quickly calculate the amount of new area that you paint on a given day? Calculate the sum of the new array in the interval that you paint. | 56,2055,2142 |
2,298 | Count Integers With Even Digit Sum | count-integers-with-even-digit-sum | Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits. | Math,Simulation | Easy | 64.8 | 36,506 | 23,649 | 220 | 12 | Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even. | 2076 |
2,299 | Merge Nodes in Between Zeros | merge-nodes-in-between-zeros | You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list. | Linked List,Simulation | Medium | 87.1 | 31,121 | 27,114 | 380 | 9 | How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a ‘0’. In that case, the modifying pointer is incremented to modify the next node. Do not forget to have the next pointer of the final node of the modified list point to null. | 835 |
2,300 | Construct String With Repeat Limit | construct-string-with-repeat-limit | You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s. Return the lexicographically largest repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one. | String,Greedy,Heap (Priority Queue),Counting | Medium | 51 | 24,894 | 12,699 | 367 | 20 | Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character. | 358 |
2,301 | Count Array Pairs Divisible by K | count-array-pairs-divisible-by-k | Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that: | Array,Math,Number Theory | Hard | 26.5 | 28,735 | 7,606 | 392 | 21 | For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently. | 1383,1620 |
2,302 | Order Two Columns Independently | order-two-columns-independently | null | Database | Medium | 63.7 | 1,948 | 1,241 | 12 | 9 | null | null |
2,303 | Unique Substrings With Equal Digit Frequency | unique-substrings-with-equal-digit-frequency | null | Hash Table,String,Rolling Hash,Counting,Hash Function | Medium | 60.3 | 1,433 | 864 | 27 | 3 | With the constraints, could we try every substring? Yes, checking every substring has runtime O(n^2), which will pass. How can we make sure we only count unique substrings? Use a set to store previously counted substrings. Hashing a string s of length m takes O(m) time. Is there a fast way to compute the hash of s if we know the hash of s[0..m - 2]? Use a rolling hash. | 2209,2225 |