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,001
Jump Game VII
jump-game-vii
You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled: Return true if you can reach index s.length - 1 in s, or false otherwise.
Two Pointers,String,Prefix Sum
Medium
24.9
88,800
22,086
826
50
Consider for each reachable index i the interval [i + a, i + b]. Use partial sums to mark the intervals as reachable.
45,55,1428,1447,1466,1814,2001
2,002
Stone Game VIII
stone-game-viii
Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following: The game stops when only one stone is left in the row. The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference. Given an integer array stones of length n where stones[i] represents the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimally.
Array,Math,Dynamic Programming,Prefix Sum,Game Theory
Hard
52.4
10,309
5,403
262
11
Let's note that the only thing that matters is how many stones were removed so we can maintain dp[numberOfRemovedStones] dp[x] = max(sum of all elements up to y - dp[y]) for all y > x
909,1240,1522,1617,1685,1788,1808,2002,2156
2,003
Distinct Numbers in Each Subarray
distinct-numbers-in-each-subarray
null
Array,Hash Table,Sliding Window
Medium
72.6
5,116
3,712
73
3
Keep a frequency map of the elements in each window. When the frequency of the element is 0, remove it from the map. The answer to each window is the size of the map.
null
2,004
Convert Date Format
convert-date-format
null
Database
Easy
87.8
7,506
6,589
28
31
null
null
2,005
Check if All the Integers in a Range Are Covered
check-if-all-the-integers-in-a-range-are-covered
You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi. Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise. An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi.
Array,Hash Table,Prefix Sum
Easy
50.7
40,622
20,609
252
56
Iterate over every integer point in the range [left, right]. For each of these points check if it is included in one of the ranges.
null
2,006
Find the Student that Will Replace the Chalk
find-the-student-that-will-replace-the-chalk
There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again. You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk. Return the index of the student that will replace the chalk.
Array,Binary Search,Simulation,Prefix Sum
Medium
41.3
40,798
16,834
248
36
Subtract the sum of chalk[i] from k until k is less than that sum Now just iterate over the array if chalk[i] is less thank k this is your answer otherwise this i is the answer
null
2,008
Minimum Cost to Change the Final Value of Expression
minimum-cost-to-change-the-final-value-of-expression
You are given a valid boolean expression as a string expression consisting of the characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'. Return the minimum cost to change the final value of the expression. The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows: Note: '&' does not take precedence over '|' in the order of calculation. Evaluate parentheses first, then in left-to-right order.
Math,String,Dynamic Programming,Stack
Hard
53.9
4,767
2,568
155
34
How many possible states are there for a given expression? Is there a data structure that we can use to solve the problem optimally?
null
2,009
Longest Word With All Prefixes
longest-word-with-all-prefixes
null
Depth-First Search,Trie
Medium
66.6
5,553
3,700
101
3
Add all the words to a trie. Check the longest path where all the nodes are words.
720
2,010
Check if Word Equals Summation of Two Words
check-if-word-equals-summation-of-two-words
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer. You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive. Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.
String
Easy
73.2
53,107
38,861
321
20
Convert each character of each word to its numerical value. Check if the numerical values satisfies the condition.
null
2,011
Maximum Value after Insertion
maximum-value-after-insertion
You are given a very large integer n, represented as a string,​​​​​​ and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number. You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n​​​​​​. You cannot insert x to the left of the negative sign. Return a string representing the maximum value of n​​​​​​ after the insertion.
String,Greedy
Medium
35.8
49,400
17,697
238
41
Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].
null
2,012
Process Tasks Using Servers
process-tasks-using-servers
You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds. Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty. At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index. If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j]. Build an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to. Return the array ans​​​​.
Array,Heap (Priority Queue)
Medium
37.4
44,636
16,674
551
165
You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules
2176
2,013
Minimum Skips to Arrive at Meeting On Time
minimum-skips-to-arrive-at-meeting-on-time
You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at. After you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting. However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks. Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.
Array,Dynamic Programming
Hard
38.6
11,818
4,559
210
39
Is there something you can keep track of from one road to another? How would knowing the start time for each state help us solve the problem?
2000,2295
2,014
Orders With Maximum Quantity Above Average
orders-with-maximum-quantity-above-average
null
Database
Medium
76.1
8,640
6,579
31
117
null
null
2,015
Determine Whether Matrix Can Be Obtained By Rotation
determine-whether-matrix-can-be-obtained-by-rotation
Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.
Array,Matrix
Easy
55.2
52,447
28,970
571
52
What is the maximum number of rotations you have to check? Is there a formula you can use to rotate a matrix 90 degrees?
48
2,016
Reduction Operations to Make the Array Elements Equal
reduction-operations-to-make-the-array-elements-equal
Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps: Return the number of operations to make all elements in nums equal.
Array,Sorting
Medium
61.5
26,754
16,464
326
12
Sort the array. Try to reduce all elements with maximum value to the next maximum value in one operation.
null
2,017
Minimum Number of Flips to Make the Binary String Alternating
minimum-number-of-flips-to-make-the-binary-string-alternating
You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Return the minimum number of type-2 operations you need to perform such that s becomes alternating. The string is called alternating if no two adjacent characters are equal.
String,Greedy
Medium
37
32,001
11,843
628
19
Note what actually matters is how many 0s and 1s are in odd and even positions For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity
2289
2,018
Minimum Space Wasted From Packaging
minimum-space-wasted-from-packaging
You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces. You want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes. Return the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7.
Array,Binary Search,Sorting,Prefix Sum
Hard
30
25,170
7,560
239
27
Given a fixed size box, is there a way to quickly query which packages (i.e., count and sizes) should end up in that box size? Do we have to order the boxes a certain way to allow us to answer the query quickly?
null
2,019
Product of Two Run-Length Encoded Arrays
product-of-two-run-length-encoded-arrays
null
Array,Two Pointers
Medium
58.2
32,535
18,945
218
34
Keep track of the indices on both RLE arrays and join the parts together. What is the maximum number of segments if we took the minimum number of elements left on both the current segments every time?
null
2,020
Remove One Element to Make the Array Strictly Increasing
remove-one-element-to-make-the-array-strictly-increasing
Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Array
Easy
27.3
92,517
25,295
484
195
For each index i in nums remove this index. If the array becomes sorted return true, otherwise revert to the original array and try different index.
null
2,021
Remove All Occurrences of a Substring
remove-all-occurrences-of-a-substring
Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: Return s after removing all occurrences of part. A substring is a contiguous sequence of characters in a string.
String
Medium
71.9
36,357
26,149
571
32
Note that a new occurrence of pattern can appear if you remove an old one, For example, s = "ababcc" and pattern = "abc". You can maintain a stack of characters and if the last character of the pattern size in the stack match the pattern remove them
null
2,022
Maximum Alternating Subsequence Sum
maximum-alternating-subsequence-sum
The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices. Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence). A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.
Array,Dynamic Programming
Medium
59.1
25,840
15,277
635
11
Is only tracking a single sum enough to solve the problem? How does tracking an odd sum and an even sum reduce the number of states?
512
2,023
Design Movie Rental System
design-movie-rental-system
You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies. Each movie is given as a 2D integer array entries where entries[i] = [shopi, moviei, pricei] indicates that there is a copy of movie moviei at shop shopi with a rental price of pricei. Each shop carries at most one copy of a movie moviei. The system should support the following functions: Implement the MovieRentingSystem class: Note: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie.
Array,Hash Table,Design,Heap (Priority Queue),Ordered Set
Hard
42
9,164
3,845
141
28
You need to maintain a sorted list for each movie and a sorted list for rented movies When renting a movie remove it from its movies sorted list and added it to the rented list and vice versa in the case of dropping a movie
null
2,024
Calculate Special Bonus
calculate-special-bonus
Table: Employees Write an SQL query to calculate the bonus of each employee. The bonus of an employee is 100% of their salary if the ID of the employee is an odd number and the employee name does not start with the character 'M'. The bonus of an employee is 0 otherwise. Return the result table ordered by employee_id. The query result format is in the following example.
Database
Easy
90.2
15,090
13,617
112
3
null
null
2,025
Redistribute Characters to Make All Strings Equal
redistribute-characters-to-make-all-strings-equal
You are given an array of strings words (0-indexed). In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j]. Return true if you can make every string in words equal using any number of operations, and false otherwise.
Hash Table,String,Counting
Easy
60.1
35,911
21,568
256
32
Characters are independentβ€”only the frequency of characters matters. It is possible to distribute characters if all characters can be divided equally among all strings.
null
2,026
Merge Triplets to Form Target Triplet
merge-triplets-to-form-target-triplet
A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain. To obtain target, you may apply the following operation on triplets any number of times (possibly zero): Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.
Array,Greedy
Medium
61.1
21,802
13,327
293
23
Which triplets do you actually care about? What property of max can you use to solve the problem?
null
2,027
Maximum Number of Removable Characters
maximum-number-of-removable-characters
You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed). You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence. Return the maximum k you can choose such that p is still a subsequence of s after the removals. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Array,String,Binary Search
Medium
35.9
34,885
12,511
544
63
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
1335
2,028
The Earliest and Latest Rounds Where Players Compete
the-earliest-and-latest-rounds-where-players-compete
There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round. Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and theΒ latest possible round number in which these two players will compete against each other, respectively.
Dynamic Programming,Memoization
Hard
51.6
7,437
3,834
162
15
Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.
null
2,029
Minimize Product Sum of Two Arrays
minimize-product-sum-of-two-arrays
null
Array,Greedy,Sorting
Medium
91.4
12,019
10,982
149
19
Is there a particular way we should order the arrays such that the product sum is minimized? Would you want to multiply two numbers that are closer to one another or further?
2282
2,030
Group Employees of the Same Salary
group-employees-of-the-same-salary
null
Database
Medium
75.7
6,905
5,226
37
3
null
null
2,031
Egg Drop With 2 Eggs and N Floors
egg-drop-with-2-eggs-and-n-floors
You are given two identical eggs and you have access to a building with n floors labeled from 1 to n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is.
Math,Dynamic Programming
Medium
70.3
27,756
19,517
694
61
Is it really optimal to always drop the egg on the middle floor for each move? Can we create states based on the number of unbroken eggs and floors to build our solution?
923
2,032
Largest Odd Number in String
largest-odd-number-in-string
You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists. A substring is a contiguous sequence of characters within a string.
Math,String,Greedy
Easy
56.9
54,918
31,242
353
29
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
null
2,033
The Number of Full Rounds You Have Played
the-number-of-full-rounds-you-have-played
You are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00, and after every 15 minutes, a new round starts. You are given two strings loginTime and logoutTime where: If logoutTime is earlier than loginTime, this means you have played from loginTime to midnight and from midnight to logoutTime. Return the number of full chess rounds you have played in the tournament. Note:Β All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00 and the last round of the day starts at 23:45.
Math,String
Medium
47.2
33,617
15,852
147
202
Consider the day as 48 hours instead of 24. For each round check if you were playing.
null
2,034
Minimum Absolute Difference Queries
minimum-absolute-difference-queries
The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1. You are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive). Return an array ans where ans[i] is the answer to the ith query. A subarray is a contiguous sequence of elements in an array. The value of |x| is defined as:
Array,Hash Table
Medium
42.8
17,374
7,431
351
28
How does the maximum value being 100 help us? How can we tell if a number exists in a given range?
null
2,035
Count Sub Islands
count-sub-islands
You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
65.7
45,218
29,705
876
27
Let's use floodfill to iterate over the islands of the second grid Let's note that if all the cells in an island in the second grid if they are represented by land in the first grid then they are connected hence making that island a sub-island
200,694,2103
2,036
Count Pairs in Two Arrays
count-pairs-in-two-arrays
null
Array,Binary Search,Sorting
Medium
57.9
3,386
1,960
74
5
We can write it as nums1[i] - nums2[i] > nums2[j] - nums1[j] instead of nums1[i] + nums1[j] > nums2[i] + nums2[j]. Store nums1[idx] - nums2[idx] in a data structure. Store nums2[idx] - nums1[idx] in a different data structure. For each integer in the first data structure, count the number of the strictly smaller integers in the second data structure with a larger index in the original array.
1622,2225
2,037
Count Square Sum Triples
count-square-sum-triples
A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2. Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.
Math,Enumeration
Easy
67.4
30,768
20,742
179
19
Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt
null
2,038
Nearest Exit from Entrance in Maze
nearest-exit-from-entrance-in-maze
You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at. In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit. Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.
Array,Breadth-First Search,Matrix
Medium
40.1
43,797
17,564
450
19
Which type of traversal lets you find the distance from a point? Try using a Breadth First Search.
null
2,039
Sum Game
sum-game
Alice and Bob take turns playing a game, with AliceΒ starting first. You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num: The game ends when there are no more '?' characters in num. For BobΒ to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For AliceΒ to win, the sums must not be equal. Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.
Math,Greedy,Game Theory
Medium
46.9
13,599
6,382
312
44
Bob can always make the total sum of both sides equal in mod 9. Why does the difference between the number of question marks on the left and right side matter?
null
2,040
Minimum Cost to Reach Destination in Time
minimum-cost-to-reach-destination-in-time
There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j. In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities). Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes.
Dynamic Programming,Graph
Hard
37.2
26,465
9,844
435
6
Consider a new graph where each node is one of the old nodes at a specific time. For example, node 0 at time 5. You need to find the shortest path in the new graph.
2189,2230
2,041
The Latest Login in 2020
the-latest-login-in-2020
Table: Logins Write an SQL query to report the latest login for all users in the year 2020. Do not include the users who did not login in 2020. Return the result table in any order. The query result format is in the following example.
Database
Easy
83.8
9,989
8,372
47
0
null
null
2,042
Maximum Product Difference Between Two Pairs
maximum-product-difference-between-two-pairs
The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized. Return the maximum such product difference.
Array,Sorting
Easy
81.3
58,929
47,905
401
20
If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array.
null
2,043
Cyclically Rotating a Grid
cyclically-rotating-a-grid
You are given an m x n integer matrix grid​​​, where m and n are both even integers, and an integer k. The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below: Return the matrix after applying k cyclic rotations to it.
Array,Matrix,Simulation
Medium
46.8
19,659
9,204
168
228
First, you need to consider each layer separately as an array. Just cycle this array and then re-assign it.
null
2,044
Number of Wonderful Substrings
number-of-wonderful-substrings
A wonderful string is a string where at most one letter appears an odd number of times. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately. A substring is a contiguous sequence of characters in a string.
Hash Table,String,Bit Manipulation,Prefix Sum
Medium
43.4
19,348
8,405
598
43
For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit.
null
2,045
Cutting Ribbons
cutting-ribbons
null
Array,Binary Search
Medium
48.1
76,097
36,601
362
23
Use binary search on the answer. You can get l/m branches of length m from a branch with length l.
1056,2066
2,046
Page Recommendations II
page-recommendations-ii
null
Database
Hard
44.3
7,958
3,524
48
13
null
1399,2097
2,047
Find a Peak Element II
find-a-peak-element-ii
A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom. Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j]. You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell. You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.
Array,Binary Search,Divide and Conquer,Matrix
Medium
53.5
34,416
18,416
681
54
Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If it's on the left side, run this algorithm on subarray left_side + central_column. If it's on the right side, run this algorithm on subarray right_side + central_column
162
2,048
Build Array from Permutation
build-array-from-permutation
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).
Array,Simulation
Easy
91.6
160,267
146,876
1,157
156
Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application
null
2,049
Eliminate Maximum Number of Monsters
eliminate-maximum-number-of-monsters
You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city. The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon. Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.
Array,Greedy,Sorting
Medium
37.6
42,275
15,880
306
48
Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive.
2354
2,050
Count Good Numbers
count-good-numbers
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7. A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.
Math,Recursion
Medium
38.2
38,945
14,887
316
217
Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n.
null
2,051
Longest Common Subpath
longest-common-subpath
There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities. There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively. Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all. A subpath of a path is a contiguous sequence of cities within that path.
Array,Binary Search,Rolling Hash,Suffix Array,Hash Function
Hard
28.3
16,630
4,707
267
24
If there is a common path with length x, there is for sure a common path of length y where y < x. We can use binary search over the answer with the range [0, min(path[i].length)]. Using binary search, we want to verify if we have a common path of length m. We can achieve this using hashing.
332,718
2,052
Depth of BST Given Insertion Order
depth-of-bst-given-insertion-order
null
Tree,Binary Search Tree,Binary Tree,Ordered Set
Medium
46.1
2,925
1,348
60
6
There are at most 2 possible places where a new node can be inserted? How can we keep track of the depth of each node?
null
2,053
Check if All Characters Have Equal Number of Occurrences
check-if-all-characters-have-equal-number-of-occurrences
Given a string s, return true if s is a good string, or false otherwise. A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).
Hash Table,String,Counting
Easy
77.1
43,486
33,510
328
11
Build a dictionary containing the frequency of each character appearing in s Check if all values in the dictionary are the same.
2226
2,054
The Number of the Smallest Unoccupied Chair
the-number-of-the-smallest-unoccupied-chair
There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number. When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct. Return the chair number that the friend numbered targetFriend will sit on.
Array,Heap (Priority Queue),Ordered Set
Medium
38.9
27,895
10,846
371
18
Sort times by arrival time. for each arrival_i find the smallest unoccupied chair and mark it as occupied until leaving_i.
null
2,055
Describe the Painting
describe-the-painting
There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj. Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order. A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.
Array,Prefix Sum
Medium
46.5
15,676
7,288
275
16
Can we sort the segments in a way to help solve the problem? How can we dynamically keep track of the sum of the current segment(s)?
2142,2297
2,057
Count Salary Categories
count-salary-categories
null
Database
Medium
66.4
7,538
5,008
32
13
null
1564
2,058
Concatenation of Array
concatenation-of-array
Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). Specifically, ans is the concatenation of two nums arrays. Return the array ans.
Array
Easy
91.6
184,207
168,811
908
181
Build an array of size 2 * n and assign num[i] to ans[i] and ans[i + n]
null
2,059
Unique Length-3 Palindromic Subsequences
unique-length-3-palindromic-subsequences
Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Hash Table,String,Prefix Sum
Medium
51.1
30,682
15,670
409
11
What is the maximum number of length-3 palindromic strings? How can we keep track of the characters that appeared to the left of a given position?
null
2,060
Merge BSTs to Create Single BST
merge-bsts-to-create-single-bst
You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can: Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST. A BST (binary search tree) is a binary tree where each node satisfies the following property: A leaf is a node that has no children.
Hash Table,Binary Search,Tree,Depth-First Search,Binary Tree
Hard
34.9
12,211
4,257
234
22
Is it possible to have multiple leaf nodes with the same values? How many possible positions are there for each tree? The root value of the final tree does not occur as a value in any of the leaves of the original tree.
null
2,061
Painting a Grid With Three Different Colors
painting-a-grid-with-three-different-colors
You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted. Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.
Dynamic Programming
Hard
57
10,825
6,171
297
16
Represent each colored column by a bitmask based on each cell color. Use bitmasks DP with state (currentCell, prevColumn).
1527
2,062
Game of Nim
game-of-nim
null
Array,Math,Dynamic Programming,Bit Manipulation,Brainteaser,Game Theory
Medium
57.9
1,606
930
25
12
Simulate the game and try all possible moves for each player.
2153
2,063
Leetcodify Friends Recommendations
leetcodify-friends-recommendations
null
Database
Hard
30.2
10,884
3,290
34
20
null
2064,2097
2,064
Leetcodify Similar Friends
leetcodify-similar-friends
null
Database
Hard
42.4
6,010
2,550
29
4
null
2063
2,066
Add Minimum Number of Rungs
add-minimum-number-of-rungs
You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung. You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there. Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.
Array,Greedy
Medium
42.4
43,557
18,474
220
18
Go as far as you can on the available rungs before adding new rungs. If you have to add a new rung, add it as high up as possible. Try using division to decrease the number of computations.
2045
2,067
Maximum Number of Points with Cost
maximum-number-of-points-with-cost
You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score. Return the maximum number of points you can achieve. abs(x) is defined as:
Array,Dynamic Programming
Medium
35.2
97,548
34,351
1,399
78
Try using dynamic programming. dp[i][j] is the maximum number of points you can have if points[i][j] is the most recent cell you picked.
64,2108
2,068
Maximum Genetic Difference Query
maximum-genetic-difference-query
There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes its unique genetic value (i.e. the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1. You are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi. Return an array ans where ans[i] is the answer to the ith query.
Array,Bit Manipulation,Trie
Hard
39.2
8,253
3,234
218
11
How can we use a trie to store all the XOR values in the path from a node to the root? How can we dynamically add the XOR values with a DFS search?
1826
2,069
Kth Smallest Subarray Sum
kth-smallest-subarray-sum
null
Array,Binary Search,Sliding Window
Medium
54
3,766
2,033
105
4
How can you compute the number of subarrays with a sum less than a given value? Can we use binary search to help find the answer?
null
2,070
Check if String Is Decomposable Into Value-Equal Substrings
check-if-string-is-decomposable-into-value-equal-substrings
null
String
Easy
51.3
3,893
1,997
30
7
Keep looking for 3-equals, if you find a 3-equal, keep going. If you don't find a 3-equal, check if it is a 2-equal. Make sure that it is the only 2-equal. If it is neither a 3-equal nor a 2-equal, then it is impossible.
null
2,071
Longest Common Subsequence Between Sorted Arrays
longest-common-subsequence-between-sorted-arrays
null
Array,Hash Table,Counting
Medium
79.6
4,217
3,355
91
3
Fix one array. Choose the next array and get the common elements. Use the common elements as the new fixed array and keep merging with the rest of the arrays.
21
2,072
Maximum of Minimum Values in All Subarrays
maximum-of-minimum-values-in-all-subarrays
null
Array,Stack,Monotonic Stack
Medium
51
2,510
1,280
84
21
Imagine the array is empty, and each element is coming to its index one by one, starting with the smallest element. For each coming element nums[i], calculate L and R, the indices of the first smallest elements on the left and the right respectively. The answer of the queries from 1 to R-L+1 will be at least this element.
null
2,073
Minimum Time For K Virus Variants to Spread
minimum-time-for-k-virus-variants-to-spread
null
Array,Math,Binary Search,Geometry,Enumeration
Hard
43.5
974
424
16
5
n is very small, how can we use that? What shape is the region when two viruses intersect?
null
2,074
Erect the Fence II
erect-the-fence-ii
null
Array,Math,Geometry
Hard
57.6
741
427
8
33
First, we need to note that this is a classic problem given n points you need to find the minimum enclosing circle to bind them Second, we need to apply a well known algorithm called welzls algorithm to help us find the minimum enclosing circle
587
2,075
Brightest Position on Street
brightest-position-on-street
null
Array,Prefix Sum,Ordered Set
Medium
62.7
4,109
2,575
84
2
Convert lights into an array of ranges representing the range where each street light can light up and sort the start and end points of the ranges. Do we need to traverse all possible positions on the street? No, we don't, we only need to go to the start and end points of the ranges for each streetlight.
2191,2385
2,076
Sum of Digits of String After Convert
sum-of-digits-of-string-after-convert
You are given a string s consisting of lowercase English letters, and an integer k. First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total. For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations: Return the resulting integer after performing the operations described above.
String,Simulation
Easy
61.4
40,801
25,037
267
30
First, let's note that after the first transform the value will be at most 100 * 9 which is not much After The first transform, we can just do the rest of the transforms by brute force
202,258,2298
2,077
Largest Number After Mutating Substring
largest-number-after-mutating-substring
You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d]. You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]). Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num. A substring is a contiguous sequence of characters within the string.
Array,String,Greedy
Medium
33.9
41,615
14,112
139
163
Should you change a digit if the new digit is smaller than the original? If changing the first digit and the last digit both make the number bigger, but you can only change one of them; which one should you change? Changing numbers closer to the front is always better
null
2,078
Maximum Compatibility Score Sum
maximum-compatibility-score-sum
There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores. Given students and mentors, return the maximum compatibility score sum that can be achieved.
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
60
23,285
13,971
442
9
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
null
2,079
Delete Duplicate Folders in System
delete-duplicate-folders-in-system
Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system. Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical, then mark the folders as well as all their subfolders. Once all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted. Return the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order.
Array,Hash Table,String,Trie,Hash Function
Hard
58.6
7,699
4,513
166
48
Can we use a trie to build the folder structure? Can we utilize hashing to hash the folder structures?
609,652
2,080
Check if Move is Legal
check-if-move-is-legal
You are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.', white cells are represented by 'W', and black cells are represented by 'B'. Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal). A good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color, and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below: Given two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal.
Array,Matrix,Enumeration
Medium
43.4
16,035
6,962
84
171
For each line starting at the given cell check if it's a good line To do that iterate over all directions horizontal, vertical, and diagonals then check good lines naively
null
2,081
Minimum Total Space Wasted With K Resizing Operations
minimum-total-space-wasted-with-k-resizing-operations
You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size). The size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted atΒ time t is defined as sizet - nums[t], and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length. Return the minimum total space wasted if you can resize the array at most k times. Note: The array can have any size at the start and does not count towards the number of resizing operations.
Array,Dynamic Programming
Medium
41.7
12,405
5,171
383
32
Given a range, how can you find the minimum waste if you can't perform any resize operations? Can we build our solution using dynamic programming using the current index and the number of resizing operations performed as the states?
null
2,082
Minimum Cost to Separate Sentence Into Rows
minimum-cost-to-separate-sentence-into-rows
null
Array,Dynamic Programming
Medium
53
1,733
919
23
8
Create an array storing all of the words in sentence separated. Try dynamic programming. Build a dp array where dp[i] represents the minimum total cost for the first i + 1 words.
418
2,083
Three Divisors
three-divisors
Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false. An integer m is a divisor of n if there exists an integer k such that n = k * m.
Math
Easy
56.5
45,242
25,550
218
15
You can count the number of divisors and just check that they are 3 Beware of the case of n equal 1 as some solutions might fail in it
2106
2,084
Maximum Number of Weeks for Which You Can Work
maximum-number-of-weeks-for-which-you-can-work
There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has. You can work on the projects following these two rules: Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints. Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.
Array,Greedy
Medium
37.5
38,006
14,250
387
98
Work on the project with the largest number of milestones as long as it is possible. Does the project with the largest number of milestones affect the number of weeks?
621
2,085
Array With Elements Not Equal to Average of Neighbors
array-with-elements-not-equal-to-average-of-neighbors
You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors. More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i]. Return any rearrangement of nums that meets the requirements.
Array,Greedy,Sorting
Medium
48.5
33,552
16,267
256
17
A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number. We can put numbers smaller than the median on odd indices and the rest on even indices.
280,324
2,086
Count Number of Special Subsequences
count-number-of-special-subsequences
A sequence is special if it consists of a positive number of 0s, followed by a positive number of 1s, then a positive number of 2s. Given an array nums (consisting of only integers 0, 1, and 2), return the number of different subsequences that are special. Since the answer may be very large, return it modulo 109 + 7. A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different.
Array,Dynamic Programming
Hard
50.9
14,394
7,326
341
6
Can we first solve a simpler problem? Counting the number of subsequences with 1s followed by 0s. How can we keep track of the partially matched subsequences to help us find the answer?
null
2,087
Confirmation Rate
confirmation-rate
null
Database
Medium
77.4
7,915
6,124
29
9
null
null
2,088
Minimum Time to Type Word Using Special Typewriter
minimum-time-to-type-word-using-special-typewriter
There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'. Each second, you may perform one of the following operations: Given a string word, return the minimum number of seconds to type out the characters in word.
String,Greedy
Easy
71.5
26,640
19,051
329
14
There are only two possible directions you can go when you move to the next letter. When moving to the next letter, you will always go in the direction that takes the least amount of time.
1443
2,089
Maximum Matrix Sum
maximum-matrix-sum
You are given an n x n integer matrix. You can do the following operation any number of times: Two elements are considered adjacent if and only if they share a border. Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.
Array,Greedy,Matrix
Medium
44.7
22,050
9,860
291
11
Try to use the operation so that each row has only one negative number. If you have only one negative element you cannot convert it to positive.
null
2,090
Number of Ways to Arrive at Destination
number-of-ways-to-arrive-at-destination
You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time. Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.
Dynamic Programming,Graph,Topological Sort,Shortest Path
Medium
32.9
41,803
13,760
795
23
First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp
813,1325,2171
2,091
Number of Ways to Separate Numbers
number-of-ways-to-separate-numbers
You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros. Return the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo 109 + 7.
String,Dynamic Programming,Suffix Array
Hard
22.3
12,191
2,715
223
29
If we know the current number has d digits, how many digits can the previous number have? Is there a quick way of calculating the number of possibilities for the previous number if we know that it must have less than or equal to d digits? Try to do some pre-processing.
91,639,1517
2,092
Users That Actively Request Confirmation Messages
users-that-actively-request-confirmation-messages
null
Database
Easy
61.6
7,710
4,750
26
23
null
null
2,093
Check If String Is a Prefix of Array
check-if-string-is-a-prefix-of-array
Given a string s and an array of strings words, determine whether s is a prefix string of words. A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length. Return true if s is a prefix string of words, or false otherwise.
Array,String
Easy
54.7
45,019
24,606
212
31
There are only words.length prefix strings. Create all of them and see if s is one of them.
null
2,094
Remove Stones to Minimize the Total
remove-stones-to-minimize-the-total
You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times: Notice that you can apply the operation on the same pile more than once. Return the minimum possible total number of stones remaining after applying the k operations. floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).
Array,Heap (Priority Queue)
Medium
56.5
31,539
17,804
290
14
Choose the pile with the maximum number of stones each time. Use a data structure that helps you find the mentioned pile each time efficiently. One such data structure is a Priority Queue.
2310
2,095
Minimum Number of Swaps to Make the String Balanced
minimum-number-of-swaps-to-make-the-string-balanced
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'. A string is called balanced if and only if: You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced.
Two Pointers,String,Stack,Greedy
Medium
67.2
38,067
25,595
736
29
Iterate over the string and keep track of the number of opening and closing brackets on each step. If the number of closing brackets is ever larger, you need to make a swap. Swap it with the opening bracket closest to the end of s.
301,957,1371,1648
2,096
Find the Longest Valid Obstacle Course at Each Position
find-the-longest-valid-obstacle-course-at-each-position
You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle. For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that: Return an array ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above.
Array,Binary Search,Binary Indexed Tree
Hard
45.3
18,062
8,190
351
5
Can you keep track of the minimum height for each obstacle course length? You can use binary search to find the longest previous obstacle course length that satisfies the conditions.
300
2,097
Strong Friendship
strong-friendship
null
Database
Medium
59.7
7,590
4,533
74
33
null
1399,2046,2063
2,098
All the Pairs With the Maximum Number of Common Followers
all-the-pairs-with-the-maximum-number-of-common-followers
null
Database
Medium
72.2
4,817
3,480
28
3
null
null
2,099
Number of Strings That Appear as Substrings in Word
number-of-strings-that-appear-as-substrings-in-word
Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word. A substring is a contiguous sequence of characters within a string.
String
Easy
79.4
34,760
27,602
276
12
Deal with each of the patterns individually. Use the built-in function in the language you are using to find if the pattern exists as a substring in word.
null
2,100
Minimum Non-Zero Product of the Array Elements
minimum-non-zero-product-of-the-array-elements
You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times: For example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001. Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 109 + 7. Note: The answer should be the minimum product before the modulo operation is done.
Math,Greedy,Recursion
Medium
32.3
21,092
6,819
113
278
Try to minimize each element by swapping bits with any of the elements after it. If you swap out all the 1s in some element, this will lead to a product of zero.
null
2,101
Last Day Where You Can Still Cross
last-day-where-you-can-still-cross
There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.
Array,Binary Search,Depth-First Search,Breadth-First Search,Union Find,Matrix
Hard
48.5
16,843
8,176
419
8
What graph algorithm allows us to find whether a path exists? Can we use binary search to help us solve the problem?
821
2,102
Find the Middle Index in Array
find-the-middle-index-in-array
Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0. Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.
Array,Prefix Sum
Easy
66.2
39,296
26,017
390
18
Could we go from left to right and check to see if an index is a middle index? Do we need to sum every number to the left and right of an index each time? Use a prefix sum array where prefix[i] = nums[0] + nums[1] + ... + nums[i].
724,1062,2369
2,103
Find All Groups of Farmland
find-all-groups-of-farmland
You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2]. Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
67.2
19,741
13,260
345
17
Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group. Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group. Use DFS to traverse through different groups of farmlands and keep track of the smallest and largest x-coordinate and y-coordinates you have seen in each group.
200,2035