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,104
Operations on Tree
operations-on-tree
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the ith node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree. The data structure should support the following functions: Implement the LockingTree class:
Hash Table,Tree,Breadth-First Search,Design
Medium
42.1
15,834
6,664
206
37
How can we use the small constraints to help us solve the problem? How can we traverse the ancestors and descendants of a node?
1722
2,105
The Number of Good Subsets
the-number-of-good-subsets
You are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers. Return the number of different good subsets in nums modulo 109 + 7. A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.
Array,Math,Dynamic Programming,Bit Manipulation,Bitmask
Hard
33.9
10,566
3,587
208
7
Consider only the numbers which have a good prime factorization. Use brute force to find all possible good subsets and then calculate its frequency in nums.
1220,1531
2,106
Find Greatest Common Divisor of Array
find-greatest-common-divisor-of-array
Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums. The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
Array,Math,Number Theory
Easy
77.9
50,222
39,136
355
14
Find the minimum and maximum in one iteration. Let them be mn and mx. Try all the numbers in the range [1, mn] and check the largest number which divides both of them.
1146,1947,2083
2,107
Find Unique Binary String
find-unique-binary-string
Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
Array,String,Backtracking
Medium
63.2
34,802
21,982
487
24
We can convert the given strings into base 10 integers. Can we use recursion to generate all possible strings?
268,448,894
2,108
Minimize the Difference Between Target and Chosen Elements
minimize-the-difference-between-target-and-chosen-elements
You are given an m x n integer matrix mat and an integer target. Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized. Return the minimum absolute difference. The absolute difference between two numbers a and b is the absolute value of a - b.
Array,Dynamic Programming,Matrix
Medium
32.7
44,943
14,696
478
89
The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much.
416,1881,2067
2,109
Find Array Given Subset Sums
find-array-given-subset-sums
You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order). Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them. An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0. Note: Test cases are generated such that there will always be at least one correct answer.
Array,Divide and Conquer
Hard
48.4
6,225
3,014
254
19
What information do the two largest elements tell us? Can we use recursion to check all possible states?
78,90,2241
2,110
Employees With Missing Information
employees-with-missing-information
Table: Employees Table: Salaries Write an SQL query to report the IDs of all the employees with missing information. The information of an employee is missing if: Return the result table ordered by employee_id in ascending order. The query result format is in the following example.
Database
Easy
80.7
9,639
7,777
66
2
null
null
2,111
Binary Searchable Numbers in an Unsorted Array
binary-searchable-numbers-in-an-unsorted-array
null
Array,Binary Search
Medium
66.8
2,183
1,458
40
5
The target will not be found if it is removed from the sequence. When does this occur? If a pivot is to the left of and is greater than the target, then the target will be removed. The same occurs when the pivot is to the right of and is less than the target. Since any element can be chosen as the pivot, for any target NOT to be removed, the condition described in the previous hint must never occur.
null
2,112
Minimum Difference Between Highest and Lowest of K Scores
minimum-difference-between-highest-and-lowest-of-k-scores
You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k. Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized. Return the minimum possible difference.
Array,Sliding Window,Sorting
Easy
53.7
39,714
21,342
295
42
For the difference between the highest and lowest element to be minimized, the k chosen scores need to be as close to each other as possible. What if the array was sorted? After sorting the scores, any contiguous k scores are as close to each other as possible. Apply a sliding window solution to iterate over each contiguous k scores, and find the minimum of the differences of all windows.
561
2,113
Find the Kth Largest Integer in the Array
find-the-kth-largest-integer-in-the-array
You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros. Return the string that represents the kth largest integer in nums. Note: Duplicate numbers should be counted distinctly. For example, if nums is ["1","2","2"], "2" is the first largest integer, "2" is the second-largest integer, and "1" is the third-largest integer.
Array,String,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
44.7
61,463
27,479
444
73
If two numbers have different lengths, which one will be larger? The longer number is the larger number. If two numbers have the same length, which one will be larger? Compare the two numbers starting from the most significant digit. Once you have found the first digit that differs, the one with the larger digit is the larger number.
215
2,114
Minimum Number of Work Sessions to Finish the Tasks
minimum-number-of-work-sessions-to-finish-the-tasks
There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break. You should finish the given tasks in a way that satisfies the following conditions: Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above. The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
31.5
36,261
11,436
502
32
Try all possible ways of assignment. If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way.
1220,1825
2,115
Number of Unique Good Subsequences
number-of-unique-good-subsequences
You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of "0"). Find the number of unique good subsequences of binary. Return the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 109 + 7. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
String,Dynamic Programming
Hard
51.9
13,193
6,850
369
7
The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers.
115,977
2,116
Count Number of Pairs With Absolute Difference K
count-number-of-pairs-with-absolute-difference-k
Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k. The value of |x| is defined as:
Array,Hash Table,Counting
Easy
82.9
55,274
45,814
591
13
Can we check every possible pair? Can we use a nested for loop to solve this problem?
1,532,1995,2277
2,117
Find Original Array From Doubled Array
find-original-array-from-doubled-array
An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array. Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.
Array,Hash Table,Greedy,Sorting
Medium
38
105,116
39,908
571
44
If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be a doubled value?
991,2241
2,118
Maximum Earnings From Taxi
maximum-earnings-from-taxi
There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi. The passengers are represented by a 0-indexed 2D integer array rides, where rides[i] = [starti, endi, tipi] denotes the ith passenger requesting a ride from point starti to point endi who is willing to give a tipi dollar tip. For each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive at most one passenger at a time. Given n and rides, return the maximum number of dollars you can earn by picking up the passengers optimally. Note: You may drop off a passenger and pick up a different passenger at the same point.
Array,Binary Search,Dynamic Programming,Sorting
Medium
42.6
28,249
12,041
553
11
Can we sort the array to help us solve the problem? We can use dynamic programming to keep track of the maximum at each position.
1352,1478,1851
2,119
Minimum Number of Operations to Make Array Continuous
minimum-number-of-operations-to-make-array-continuous
You are given an integer array nums. In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous. Return the minimum number of operations to make nums continuous.
Array,Binary Search
Hard
46
13,913
6,403
406
4
Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer.
424,523,1113,1732,1805
2,120
First and Last Call On the Same Day
first-and-last-call-on-the-same-day
null
Database
Hard
51.7
5,826
3,010
48
11
null
null
2,121
Find if Path Exists in Graph
find-if-path-exists-in-graph
There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. You want to determine if there is a valid path that exists from vertex source to vertex destination. Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.
Depth-First Search,Breadth-First Search,Graph
Easy
50.2
164,420
82,591
888
51
null
2201,2218
2,122
Count Special Quadruplets
count-special-quadruplets
Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:
Array,Enumeration
Easy
57.9
32,992
19,090
261
132
N is very small, how can we use that? Can we check every possible quadruplet?
18,334,1656
2,123
The Number of Weak Characters in the Game
the-number-of-weak-characters-in-the-game
You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game. A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei. Return the number of weak characters.
Array,Stack,Greedy,Sorting,Monotonic Stack
Medium
33.1
49,143
16,261
595
20
Sort the array on the basis of the attack values and group characters with the same attack together. How can you use these groups? Characters in one group will always have a lesser attack value than the characters of the next group. Hence, we will only need to check if there is a higher defense value present in the next groups.
354,1367
2,124
First Day Where You Have Been in All the Rooms
first-day-where-you-have-been-in-all-the-rooms
There are n rooms you need to visit, labeled from 0 to n - 1. Each day is labeled, starting from 0. You will go in and visit one room a day. Initially on day 0, you visit room 0. The order you visit the rooms for the coming days is determined by the following rules and a given 0-indexed array nextVisit of length n: Return the label of the first day where you have been in all the rooms. It can be shown that such a day exists. Since the answer may be very large, return it modulo 109 + 7.
Array,Dynamic Programming
Medium
35.3
15,891
5,616
318
53
The only way to get to room i+1 is when you are visiting room i and room i has been visited an even number of times. After visiting room i an odd number of times, you are required to visit room nextVisit[i] where nextVisit[i] <= i. It takes a fixed amount of days for you to come back from room nextVisit[i] to room i. Then, you have visited room i even number of times.nextVisit[i] Can you use Dynamic Programming to avoid recomputing the number of days it takes to visit room i from room nextVisit[i]?
null
2,125
GCD Sort of an Array
gcd-sort-of-an-array
You are given an integer array nums, and you can perform the following operation any number of times on nums: Return true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise.
Array,Math,Union Find,Sorting
Hard
45.5
10,126
4,606
251
5
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
1257
2,126
Count Nodes Equal to Sum of Descendants
count-nodes-equal-to-sum-of-descendants
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
75.3
6,772
5,101
92
2
Can we reuse previously calculated information? How can we calculate the sum of the current subtree using the sum of the child's subtree?
508,1091
2,127
Employees Whose Manager Left the Company
employees-whose-manager-left-the-company
null
Database
Easy
50.3
9,339
4,697
27
5
null
null
2,128
Reverse Prefix of Word
reverse-prefix-of-word
Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. Return the resulting string.
Two Pointers,String
Easy
78
41,520
32,378
310
6
Find the first index where ch appears. Find a way to reverse a substring of word.
null
2,129
Number of Pairs of Interchangeable Rectangles
number-of-pairs-of-interchangeable-rectangles
You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle. Two rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division). Return the number of pairs of interchangeable rectangles in rectangles.
Array,Hash Table,Math,Counting,Number Theory
Medium
43
36,412
15,645
212
20
Store the rectangle height and width ratio in a hashmap. Traverse the ratios, and for each ratio, use the frequency of the ratio to add to the total pair count.
1635,1925,2307
2,130
Maximum Product of the Length of Two Palindromic Subsequences
maximum-product-of-the-length-of-two-palindromic-subsequences
Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindromic subsequences. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.
String,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
52.8
21,493
11,339
436
30
Could you generate all possible pairs of disjoint subsequences? Could you find the maximum length palindrome in each subsequence for a pair of disjoint subsequences?
125,516,1336,2318
2,131
Smallest Missing Genetic Value in Each Subtree
smallest-missing-genetic-value-in-each-subtree
There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1. There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i. Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i. The subtree rooted at a node x contains node x and all of its descendant nodes.
Dynamic Programming,Tree,Depth-First Search,Union Find
Hard
42.3
11,335
4,799
266
16
If the subtree doesn't contain 1, then the missing value will always be 1. What data structure allows us to dynamically update the values that are currently not present?
null
2,132
Convert 1D Array Into 2D Array
convert-1d-array-into-2d-array
You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original. The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.
Array,Matrix,Simulation
Easy
59.2
49,401
29,235
292
20
When is it possible to convert original into a 2D array and when is it impossible? It is possible if and only if m * n == original.length If it is possible to convert original to a 2D array, keep an index i such that original[i] is the next element to add to the 2D array.
566
2,133
Number of Pairs of Strings With Concatenation Equal to Target
number-of-pairs-of-strings-with-concatenation-equal-to-target
Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.
Array,String
Medium
73
23,817
17,394
278
26
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
1
2,134
Maximize the Confusion of an Exam
maximize-the-confusion-of-an-exam
A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row). You are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation: Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.
String,Binary Search,Sliding Window,Prefix Sum
Medium
57.2
23,467
13,422
459
10
Can we use the maximum length at the previous position to help us find the answer for the current position? Can we use binary search to find the maximum consecutive same answer at every position?
340,424,1046,1605
2,135
Maximum Number of Ways to Partition an Array
maximum-number-of-ways-to-partition-an-array
You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions: You are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged. Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.
Array,Hash Table,Counting,Enumeration,Prefix Sum
Hard
31.2
15,656
4,892
268
24
A pivot point splits the array into equal prefix and suffix. If no change is made to the array, the goal is to find the number of pivot p such that prefix[p-1] == suffix[p]. Consider how prefix and suffix will change when we change a number nums[i] to k. When sweeping through each element, can you find the total number of pivots where the difference of prefix and suffix happens to equal to the changes of k-nums[i].
416,698
2,136
Find Cutoff Score for Each School
find-cutoff-score-for-each-school
null
Database
Medium
68.9
4,470
3,078
25
58
null
null
2,137
Final Value of Variable After Performing Operations
final-value-of-variable-after-performing-operations
There is a programming language with only four operations and one variable X: Initially, the value of X is 0. Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.
Array,String,Simulation
Easy
89.2
104,055
92,771
473
85
There are only two operations to keep track of. Use a variable to store the value after each operation.
null
2,138
Sum of Beauty in the Array
sum-of-beauty-in-the-array
You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals: Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.
Array
Medium
45.9
29,856
13,693
290
29
Use suffix/prefix arrays. prefix[i] records the maximum value in range (0, i - 1) inclusive. suffix[i] records the minimum value in range (i + 1, n - 1) inclusive.
121,951
2,139
Detect Squares
detect-squares
You are given a stream of points on the X-Y plane. Design an algorithm that: An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis. Implement the DetectSquares class:
Array,Hash Table,Design,Counting
Medium
46.2
40,039
18,488
297
97
Maintain the frequency of all the points in a hash map. Traverse the hash map and if any point has the same y-coordinate as the query point, consider this point and the query point to form one of the horizontal lines of the square.
null
2,140
Longest Subsequence Repeated k Times
longest-subsequence-repeated-k-times
You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times. Return the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.
String,Backtracking,Greedy,Counting,Enumeration
Hard
54.7
7,316
4,005
185
52
The length of the longest subsequence does not exceed n/k. Do you know why? Find the characters that could be included in the potential answer. A character occurring more than or equal to k times can be used in the answer up to (count of the character / k) times. Try all possible candidates in reverse lexicographic order, and check the string for the subsequence condition.
395
2,141
Smallest Greater Multiple Made of Two Digits
smallest-greater-multiple-made-of-two-digits
null
Math,Enumeration
Medium
52.1
1,731
901
19
3
Could you generate all the different numbers comprised of only digit1 and digit2 with the constraints? Going from least to greatest, check if the number you generated is greater than k and a multiple of k.
null
2,142
Average Height of Buildings in Each Segment
average-height-of-buildings-in-each-segment
null
Array,Greedy,Sorting,Heap (Priority Queue)
Medium
58.1
1,469
853
30
12
Try sorting the start and end points of each building. The naive solution is to go through each position on the street and keep track of the sum of all the buildings at that position and the number of buildings at that position. How could we optimize that solution to pass? We don't need to go through every position, just the ones where a building starts or a building ends.
1803,2055,2297
2,143
Count the Number of Experiments
count-the-number-of-experiments
null
Database
Medium
50.9
4,842
2,466
7
80
null
null
2,144
Maximum Difference Between Increasing Elements
maximum-difference-between-increasing-elements
Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j]. Return the maximum difference. If no such i and j exists, return -1.
Array
Easy
54.6
54,942
30,006
368
15
Could you keep track of the minimum element visited while traversing? We have a potential candidate for the answer if the prefix min is lesser than nums[i].
121,2199
2,145
Grid Game
grid-game
You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix. Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)). At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another. The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.
Array,Matrix,Prefix Sum
Medium
41.5
24,373
10,126
430
12
There are n choices for when the first robot moves to the second row. Can we use prefix sums to help solve this problem?
null
2,146
Check if Word Can Be Placed In Crossword
check-if-word-can-be-placed-in-crossword
You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells. A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if: Given a string word, return true if word can be placed in board, or false otherwise.
Array,Matrix,Enumeration
Medium
47.9
17,745
8,503
157
168
Check all possible placements for the word. There is a limited number of places where a word can start.
null
2,147
The Score of Students Solving Math Expression
the-score-of-students-solving-math-expression
You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations: You are given an integer array answers of length n, which are the submitted answers of the students in no particular order. You are asked to grade the answers, by following these rules: Return the sum of the points of the students.
Array,Math,String,Dynamic Programming,Stack,Memoization
Hard
33.7
12,271
4,139
137
62
The number of operators in the equation is less. Could you find the right answer then generate all possible answers using different orders of operations? Divide the equation into blocks separated by the operators, and use memoization on the results of blocks for optimization. Use set and the max limit of the answer for further optimization.
224,241
2,148
Minimum Number of Moves to Seat Everyone
minimum-number-of-moves-to-seat-everyone
There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student. You may perform the following move any number of times: Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat. Note that there may be multiple seats or students in the same position at the beginning.
Array,Sorting
Easy
82.8
27,056
22,413
283
50
Can we sort the arrays to help solve the problem? Can we greedily match each student to a seat? The smallest positioned student will go to the smallest positioned chair, and then the next smallest positioned student will go to the next smallest positioned chair, and so on.
null
2,149
Remove Colored Pieces if Both Neighbors are the Same Color
remove-colored-pieces-if-both-neighbors-are-the-same-color
There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece. Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first. Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.
Math,String,Greedy,Game Theory
Medium
56.1
20,174
11,320
209
18
Does the number of moves a player can make depend on what the other player does? No How many moves can Alice make if colors == "AAAAAA" If a group of n consecutive pieces has the same color, the player can take n - 2 of those pieces if n is greater than or equal to 3
null
2,150
Kth Smallest Product of Two Sorted Arrays
kth-smallest-product-of-two-sorted-arrays
null
Array,Binary Search
Hard
27.8
18,833
5,237
298
17
Can we split this problem into four cases depending on the sign of the numbers? Can we binary search the value?
373,532
2,151
The Time When the Network Becomes Idle
the-time-when-the-network-becomes-idle
There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n. All servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels. The server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through. At the beginning of second 0, each data server sends its message to be processed. Starting from second 1, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server: The network becomes idle when there are no messages passing between servers or arriving at servers. Return the earliest second starting from which the network becomes idle.
Array,Breadth-First Search,Graph
Medium
49.1
12,999
6,385
264
18
What method can you use to find the shortest time taken for a message from a data server to reach the master server? How can you use this value and the server's patience value to determine the time at which the server sends its last message? What is the time when the last message sent from a server gets back to the server? For each data server, by the time the server receives the first returned messages, how many messages has the server sent?
744,764,774
2,152
The Number of Seniors and Juniors to Join the Company
the-number-of-seniors-and-juniors-to-join-the-company
null
Database
Hard
38.2
8,123
3,103
55
4
null
1327,2158
2,153
Subtree Removal Game with Fibonacci Tree
subtree-removal-game-with-fibonacci-tree
null
Math,Dynamic Programming,Tree,Binary Tree,Game Theory
Hard
63.6
453
288
9
26
How can game theory help us solve this problem? Think about the Sprague–Grundy theorem and the Colon Principle The Grundy value of a node is the nim sum of the Grundy values of its children.
2062
2,154
Minimum Moves to Convert String
minimum-moves-to-convert-string
You are given a string s consisting of n characters which are either 'X' or 'O'. A move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same. Return the minimum number of moves required so that all the characters of s are converted to 'O'.
String,Greedy
Easy
53.4
33,422
17,856
198
46
Find the smallest substring you need to consider at a time. Try delaying a move as long as possible.
null
2,155
Find Missing Observations
find-missing-observations
You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls. You are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n. Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array. The average value of a set of k numbers is the sum of the numbers divided by k. Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m.
Array,Math,Simulation
Medium
41.9
30,688
12,857
211
10
What should the sum of the n rolls be? Could you generate an array of size n such that each element is between 1 and 6?
1263,1343
2,156
Stone Game IX
stone-game-ix
Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone. Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice's turn). Assuming both players play optimally, return true if Alice wins and false if Bob wins.
Array,Math,Greedy,Counting,Game Theory
Medium
24.8
19,252
4,771
140
202
There are limited outcomes given the current sum and the stones remaining. Can we greedily simulate starting with taking a stone with remainder 1 or 2 divided by 3?
909,1240,1522,1617,1685,1788,1808,2002,2156
2,157
Smallest K-Length Subsequence With Occurrences of a Letter
smallest-k-length-subsequence-with-occurrences-of-a-letter
You are given a string s, an integer k, a letter letter, and an integer repetition. Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
String,Stack,Greedy,Monotonic Stack
Hard
38.7
11,283
4,365
244
6
Use stack. For every character to be appended, decide how many character(s) from the stack needs to get popped based on the stack length and the count of the required character. Pop the extra characters out from the stack and return the characters in the stack (reversed).
316
2,158
The Number of Seniors and Juniors to Join the Company II
the-number-of-seniors-and-juniors-to-join-the-company-ii
null
Database
Hard
56.6
2,924
1,654
10
5
null
1327,2152
2,159
Two Out of Three
two-out-of-three
null
Array,Hash Table
Easy
72.9
34,940
25,461
277
26
What data structure can we use to help us quickly find whether an element belongs in an array? Can we count the frequencies of the elements in each array?
null
2,160
Minimum Operations to Make a Uni-Value Grid
minimum-operations-to-make-a-uni-value-grid
You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid. A uni-value grid is a grid where all the elements of it are equal. Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1.
Array,Math,Sorting,Matrix
Medium
50.5
26,429
13,355
304
29
Is it possible to make two integers a and b equal if they have different remainders dividing by x? If it is possible, which number should you select to minimize the number of operations? What if the elements are sorted?
462
2,161
Stock Price Fluctuation
stock-price-fluctuation
You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record. Design an algorithm that: Implement the StockPrice class:
Hash Table,Design,Heap (Priority Queue),Data Stream,Ordered Set
Medium
47.4
50,693
24,047
444
28
How would you solve the problem for offline queries (all queries given at once)? Think about which data structure can help insert and delete the most optimal way.
1023
2,162
Partition Array Into Two Arrays to Minimize Sum Difference
partition-array-into-two-arrays-to-minimize-sum-difference
You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays. Return the minimum possible absolute difference.
Array,Two Pointers,Binary Search,Dynamic Programming,Bit Manipulation,Ordered Set,Bitmask
Hard
21.7
24,142
5,249
579
36
The target sum for the two partitions is sum(nums) / 2. Could you reduce the time complexity if you arbitrarily divide nums into two halves (two arrays)? Meet-in-the-Middle? For both halves, pre-calculate a 2D array where the kth index will store all possible sum values if only k elements from this half are added. For each sum of k elements in the first half, find the best sum of n-k elements in the second half such that the two sums add up to a value closest to the target sum from hint 1. These two subsets will form one array of the partition.
416,823,993,1130,1881
2,163
Kth Distinct String in an Array
kth-distinct-string-in-an-array
A distinct string is a string that is present only once in an array. Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string "". Note that the strings are considered in the order in which they appear in the array.
Array,Hash Table,String,Counting
Easy
72.9
29,728
21,680
288
6
Try 'mapping' the strings to check if they are unique or not.
2190
2,164
Two Best Non-Overlapping Events
two-best-non-overlapping-events
You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei. You can choose at most two non-overlapping events to attend such that the sum of their values is maximized. Return this maximum sum. Note that the start time and end time is inclusive: that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t, the next event must start at or after t + 1.
Array,Binary Search,Dynamic Programming,Sorting,Heap (Priority Queue)
Medium
43.1
19,427
8,367
389
7
How can sorting the events on the basis of their start times help? How about end times? How can we quickly get the maximum score of an interval not intersecting with the interval we chose?
1352,1851
2,165
Plates Between Candles
plates-between-candles
There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle. You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes the substring s[lefti...righti] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring. Return an integer array answer where answer[i] is the answer to the ith query.
Array,String,Binary Search,Prefix Sum
Medium
46
22,217
10,217
381
10
Can you find the indices of the most left and right candles for a given substring, perhaps by using binary search (or better) over an array of indices of all the bars? Once the indices of the most left and right bars are determined, how can you efficiently count the number of plates within the range? Prefix sums?
34,1281
2,166
Number of Valid Move Combinations On Chessboard
number-of-valid-move-combinations-on-chessboard
There is an 8 x 8 chessboard containing n pieces (rooks, queens, or bishops). You are given a string array pieces of length n, where pieces[i] describes the type (rook, queen, or bishop) of the ith piece. In addition, you are given a 2D integer array positions also of length n, where positions[i] = [ri, ci] indicates that the ith piece is currently at the 1-based coordinate (ri, ci) on the chessboard. When making a move for a piece, you choose a destination square that the piece will travel toward and stop on. You must make a move for every piece on the board simultaneously. A move combination consists of all the moves performed on all the given pieces. Every second, each piece will instantaneously travel one square towards their destination if they are not already at it. All pieces start traveling at the 0th second. A move combination is invalid if, at a given time, two or more pieces occupy the same square. Return the number of valid move combinations​​​​​. Notes:
Array,String,Backtracking,Simulation
Hard
58.7
4,150
2,435
32
176
N is small, we can generate all possible move combinations. For each possible move combination, determine which ones are valid.
null
2,167
Number of Accounts That Did Not Stream
number-of-accounts-that-did-not-stream
null
Database
Medium
72.8
4,876
3,551
9
75
null
null
2,168
Check if Numbers Are Ascending in a Sentence
check-if-numbers-are-ascending-in-a-sentence
A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters. Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s). Return true if so, or false otherwise.
String
Easy
67.8
33,814
22,931
236
11
Use string tokenization of your language to extract all the tokens of the string easily. For each token extracted, how can you tell if it is a number? Does the first letter being a digit mean something? Compare the number with the previously occurring number to check if ascending order is maintained.
8,1970,2243
2,169
Simple Bank System
simple-bank-system
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initial balance of balance[i]. Execute all the valid transactions. A transaction is valid if: Implement the Bank class:
Array,Hash Table,Design,Simulation
Medium
65.1
18,981
12,348
101
115
How do you determine if a transaction will fail? Simply apply the operations if the transaction is valid.
null
2,170
Count Number of Maximum Bitwise-OR Subsets
count-number-of-maximum-bitwise-or-subsets
Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different. The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed).
Array,Backtracking,Bit Manipulation
Medium
74.8
17,312
12,945
246
13
Can we enumerate all possible subsets? The maximum bitwise-OR is the bitwise-OR of the whole array.
78
2,171
Second Minimum Time to Reach Destination
second-minimum-time-to-reach-destination
A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes. Each vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time. You can enter a vertex at any time, but can leave a vertex only when the signal is green. You cannot wait at a vertex if the signal is green. The second minimum value is defined as the smallest value strictly larger than the minimum value. Given n, edges, time, and change, return the second minimum time it will take to go from vertex 1 to vertex n. Notes:
Breadth-First Search,Graph,Shortest Path
Hard
36.6
15,948
5,844
315
5
How much is change actually necessary while calculating the required path? How many extra edges do we need to add to the shortest path?
744,1456,2090
2,172
Low-Quality Problems
low-quality-problems
null
Database
Easy
86.1
5,163
4,443
16
6
null
null
2,173
Number of Valid Words in a Sentence
number-of-valid-words-in-a-sentence
A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '. A token is a valid word if all three of the following are true: Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!". Given a string sentence, return the number of valid words in sentence.
String
Easy
29.4
47,173
13,884
116
478
Iterate through the string to split it by spaces. Count the number of characters of each type (letters, numbers, hyphens, and punctuations).
2219
2,174
Next Greater Numerically Balanced Number
next-greater-numerically-balanced-number
An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x. Given an integer n, return the smallest numerically balanced number strictly greater than n.
Math,Backtracking,Enumeration
Medium
46.2
17,965
8,293
95
218
How far away can the next greater numerically balanced number be from n? With the given constraints, what is the largest numerically balanced number?
null
2,175
Count Nodes With the Highest Score
count-nodes-with-the-highest-score
There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1. Each node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees. Return the number of nodes that have the highest score.
Array,Tree,Depth-First Search,Binary Tree
Medium
46.3
20,564
9,513
389
24
For each node, you need to find the sizes of the subtrees rooted in each of its children. Maybe DFS? How to determine the number of nodes in the rest of the tree? Can you subtract the size of the subtree rooted at the node from the total number of nodes of the tree? Use these values to compute the score of the node. Track the maximum score, and how many nodes achieve such score.
863,1207,1465
2,176
Parallel Courses III
parallel-courses-iii
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course. You must find the minimum number of months needed to complete all the courses following these rules: Return the minimum number of months needed to complete all the courses. Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).
Dynamic Programming,Graph,Topological Sort
Hard
59.7
14,574
8,707
321
9
What is the earliest time a course can be taken? How would you solve the problem if all courses take equal time? How would you generalize this approach?
630,1101,1962,2012,2246
2,177
Check Whether Two Strings are Almost Equivalent
check-whether-two-strings-are-almost-equivalent
Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3. Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise. The frequency of a letter x is the number of times it occurs in the string.
Hash Table,String,Counting
Easy
66.4
24,735
16,420
193
6
What data structure can we use to count the frequency of each character? Are there edge cases where a character is present in one string but not the other?
null
2,178
Walking Robot Simulation II
walking-robot-simulation-ii
A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions ("North", "East", "South", and "West"). A robot is initially at cell (0, 0) facing direction "East". The robot can be instructed to move for a specific number of steps. For each step, it does the following. After the robot finishes moving the number of steps required, it stops and awaits the next instruction. Implement the Robot class:
Design,Simulation
Medium
21.6
25,883
5,594
108
235
The robot only moves along the perimeter of the grid. Can you think if modulus can help you quickly compute which cell it stops at? After the robot moves one time, whenever the robot stops at some cell, it will always face a specific direction. i.e., The direction it faces is determined by the cell it stops at. Can you precompute what direction it faces when it stops at each cell along the perimeter, and reuse the results?
906
2,179
Most Beautiful Item for Each Query
most-beautiful-item-for-each-query
You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively. You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0. Return an array answer of the same length as queries where answer[j] is the answer to the jth query.
Array,Binary Search,Sorting
Medium
48.4
16,619
8,040
290
8
Can we process the queries in a smart order to avoid repeatedly checking the same items? How can we use the answer to a query for other queries?
1957
2,180
Maximum Number of Tasks You Can Assign
maximum-number-of-tasks-you-can-assign
You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks, with the ith task requiring tasks[i] strength to complete. The strength of each worker is stored in a 0-indexed integer array workers, with the jth worker having workers[j] strength. Each worker can only be assigned to a single task and must have a strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i]). Additionally, you have pills magical pills that will increase a worker's strength by strength. You can decide which workers receive the magical pills, however, you may only give each worker at most one magical pill. Given the 0-indexed integer arrays tasks and workers and the integers pills and strength, return the maximum number of tasks that can be completed.
Array,Binary Search,Greedy,Queue,Sorting,Monotonic Queue
Hard
36.9
12,449
4,592
233
12
Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?
853,2263
2,181
Smallest Index With Equal Value
smallest-index-with-equal-value
Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist. x mod y denotes the remainder when x is divided by y.
Array
Easy
73.2
32,095
23,484
144
67
Starting with i=0, check the condition for each index. The first one you find to be true is the smallest index.
null
2,182
Find the Minimum and Maximum Number of Nodes Between Critical Points
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
A critical point in a linked list is defined as either a local maxima or a local minima. A node is a local maxima if the current node has a value strictly greater than the previous node and the next node. A node is a local minima if the current node has a value strictly smaller than the previous node and the next node. Note that a node can only be a local maxima/minima if there exists both a previous node and a next node. Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1].
Linked List
Medium
57.7
25,922
14,965
248
12
The maximum distance must be the distance between the first and last critical point. For each adjacent critical point, calculate the difference and check if it is the minimum distance.
null
2,183
Minimum Operations to Convert Number
minimum-operations-to-convert-number
You are given a 0-indexed integer array nums containing distinct numbers, an integer start, and an integer goal. There is an integer x that is initially set to start, and you want to perform operations on x such that it is converted to goal. You can perform the following operation repeatedly on the number x: If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x to any of the following: Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward. Return the minimum number of operations needed to convert x = start into goal, and -1 if it is not possible.
Array,Breadth-First Search
Medium
46.1
20,684
9,528
345
19
Once x drops below 0 or goes above 1000, is it possible to continue performing operations on x? How can you use BFS to find the minimum operations?
1776
2,184
Check if an Original String Exists Given Two Encoded Strings
check-if-an-original-string-exists-given-two-encoded-strings
An original string, consisting of lowercase English letters, can be encoded by the following steps: For example, one way to encode an original string "abcdefghijklmnop" might be: Given two encoded strings s1 and s2, consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2. Otherwise, return false. Note: The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3.
String,Dynamic Programming
Hard
40
13,173
5,275
150
83
For s1 and s2, divide each into a sequence of single alphabet strings and digital strings. The problem now becomes comparing if two sequences are equal. A single alphabet string has no variation, but a digital string has variations. For example: "124" can be interpreted as 1+2+4, 12+4, 1+24, and 124 wildcard characters. There are four kinds of comparisons: a single alphabet vs another; a single alphabet vs a number, a number vs a single alphabet, and a number vs another number. In the case of a number vs another (a single alphabet or a number), can you decrease the number by the min length of both? There is a recurrence relation in the search which ends when either a single alphabet != another, or one sequence ran out, or both sequences ran out.
408,1781
2,185
Accepted Candidates From the Interviews
accepted-candidates-from-the-interviews
null
Database
Medium
77.5
3,811
2,953
19
17
null
null
2,186
Count Vowel Substrings of a String
count-vowel-substrings-of-a-string
A substring is a contiguous (non-empty) sequence of characters within a string. A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it. Given a string word, return the number of vowel substrings in word.
Hash Table,String
Easy
65.8
24,749
16,283
362
109
While generating substrings starting at any index, do you need to continue generating larger substrings if you encounter a consonant? Can you store the count of characters to avoid generating substrings altogether?
808,1034,1636,1967
2,187
Vowels of All Substrings
vowels-of-all-substrings
Given a string word, return the sum of the number of vowels ('a', 'e', 'i', 'o', and 'u') in every substring of word. A substring is a contiguous (non-empty) sequence of characters within a string. Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations.
Math,String,Dynamic Programming,Combinatorics
Medium
54
23,905
12,905
351
14
Since generating substrings is not an option, can we count the number of substrings a vowel appears in? How much does each vowel contribute to the total sum?
1460
2,188
Minimized Maximum of Products Distributed to Any Store
minimized-maximum-of-products-distributed-to-any-store
You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type. You need to distribute all products to the retail stores following these rules: Return the minimum possible x.
Array,Binary Search
Medium
48.6
23,404
11,372
400
16
There exists a monotonic nature such that when x is smaller than some number, there will be no way to distribute, and when x is not smaller than that number, there will always be a way to distribute. If you are given a number k, where the number of products given to any store does not exceed k, could you determine if all products can be distributed? Implement a function canDistribute(k), which returns true if you can distribute all products such that any store will not be given more than k products, and returns false if you cannot. Use this function to binary search for the smallest possible k.
907,1056,1335,1408,1675,1886,2294
2,189
Maximum Path Quality of a Graph
maximum-path-quality-of-a-graph
There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes. Finally, you are given an integer maxTime. A valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum). Return the maximum quality of a valid path. Note: There are at most four edges connected to each node.
Array,Backtracking,Graph
Hard
57.8
14,083
8,137
258
26
How many nodes can you visit within maxTime seconds? Can you try every valid path?
741,2040
2,190
Count Common Words With One Occurrence
count-common-words-with-one-occurrence
Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.
Array,Hash Table,String,Counting
Easy
70.5
31,015
21,864
295
6
Could you try every word? Could you use a hash map to achieve a good complexity?
349,920,2163
2,191
Minimum Number of Buckets Required to Collect Rainwater from Houses
minimum-number-of-buckets-required-to-collect-rainwater-from-houses
You are given a 0-indexed string street. Each character in street is either 'H' representing a house or '.' representing an empty space. You can place buckets on the empty spaces to collect rainwater that falls from the adjacent houses. The rainwater from a house at index i is collected if a bucket is placed at index i - 1 and/or index i + 1. A single bucket, if placed adjacent to two houses, can collect the rainwater from both houses. Return the minimum number of buckets needed so that for every house, there is at least one bucket collecting rainwater from it, or -1 if it is impossible.
String,Dynamic Programming,Greedy
Medium
45.2
21,074
9,529
299
13
When is it impossible to collect the rainwater from all the houses? When one or more houses do not have an empty space adjacent to it. Assuming the rainwater from all previous houses is collected. If there is a house at index i and you are able to place a bucket at index i - 1 or i + 1, where should you put it? It is always better to place a bucket at index i + 1 because it can collect the rainwater from the next house as well.
1979,2075
2,192
Minimum Cost Homecoming of a Robot in a Grid
minimum-cost-homecoming-of-a-robot-in-a-grid
There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol). The robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n. Return the minimum total cost for this robot to return home.
Array,Greedy,Matrix
Medium
50
16,019
8,003
283
49
Irrespective of what path the robot takes, it will have to traverse all the rows between startRow and homeRow and all the columns between startCol and homeCol. Hence, making any other move other than traversing the required rows and columns will potentially incur more cost which can be avoided.
62,64,361,1402
2,193
Count Fertile Pyramids in a Land
count-fertile-pyramids-in-a-land
A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outside the grid are considered barren. A pyramidal plot of land can be defined as a set of cells with the following criteria: An inverse pyramidal plot of land can be defined as a set of cells with similar criteria: Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells. Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid.
Array,Dynamic Programming,Matrix
Hard
62.7
5,986
3,752
171
7
Think about how dynamic programming can help solve the problem. For any fixed cell (r, c), can you calculate the maximum height of the pyramid for which it is the apex? Let us denote this value as dp[r][c]. How will the values at dp[r+1][c-1] and dp[r+1][c+1] help in determining the value at dp[r][c]? For the cell (r, c), is there a relation between the number of pyramids for which it serves as the apex and dp[r][c]? How does it help in calculating the answer?
1402,1990
2,194
The Category of Each Member in the Store
the-category-of-each-member-in-the-store
null
Database
Medium
73.1
3,514
2,570
23
4
null
null
2,195
Time Needed to Buy Tickets
time-needed-to-buy-tickets
There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line. You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i]. Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line. Return the time taken for the person at position k (0-indexed) to finish buying tickets.
Array,Queue,Simulation
Easy
62.4
33,581
20,942
329
22
Loop through the line of people and decrement the number of tickets for each to buy one at a time as if simulating the line moving forward. Keep track of how many tickets have been sold up until person k has no more tickets to buy. Remember that those who have no more tickets to buy will leave the line.
1802
2,196
Reverse Nodes in Even Length Groups
reverse-nodes-in-even-length-groups
You are given the head of a linked list. The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words, Note that the length of the last group may be less than or equal to 1 + the length of the second to last group. Reverse the nodes in each group with an even length, and return the head of the modified linked list.
Linked List
Medium
50.3
18,680
9,388
177
189
Consider the list structure ...A → (B → ... → C) → D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure? Suppose you have B → ... → C reversed (because it was of even length) so that it is now C → ... → B. What references do you need to fix so that the transitions between the previous, current, and next groups are correct? A.next should be set to C, and B.next should be set to D. Once the current group is finished being modified, you need to find the new A, B, C, and D nodes for the next group. How can you use the old A, B, C, and D nodes to find the new ones? The new A is either the old B or old C depending on if the group was of even or odd length. The new B is always the old D. The new C and D can be found based on the new B and the next group's length. You can set the initial values of A, B, C, and D to A = null, B = head, C = head, D = head.next. Repeat the steps from the previous hints until D is null.
25,206
2,197
Decode the Slanted Ciphertext
decode-the-slanted-ciphertext
A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows. originalText is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText. encodedText is then formed by appending all characters of the matrix in a row-wise fashion. The characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. For example, if originalText = "cipher" and rows = 3, then we encode it in the following manner: The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = "ch ie pr". Given the encoded string encodedText and number of rows rows, return the original string originalText. Note: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText.
String,Simulation
Medium
49.8
15,631
7,787
145
30
How can you use rows and encodedText to find the number of columns of the matrix? Once you have the number of rows and columns, you can create the matrix and place encodedText in it. How should you place it in the matrix? How should you traverse the matrix to "decode" originalText?
498
2,198
Process Restricted Friend Requests
process-restricted-friend-requests
You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1. You are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] means that person xi and person yi cannot become friends, either directly or indirectly through other people. Initially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests, where requests[j] = [uj, vj] is a friend request between person uj and person vj. A friend request is successful if uj and vj can be friends. Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1]), and upon a successful request, uj and vj become direct friends for all future friend requests. Return a boolean array result, where each result[j] is true if the jth friend request is successful or false if it is not. Note: If uj and vj are already direct friends, the request is still successful.
Union Find,Graph
Hard
53.9
17,475
9,413
320
4
For each request, we could loop through all restrictions. Can you think of doing a check-in close to O(1)? Could you use Union Find?
305,1308,2246
2,199
Two Furthest Houses With Different Colors
two-furthest-houses-with-different-colors
There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house. Return the maximum distance between two houses with different colors. The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x.
Array,Greedy
Easy
68.6
33,973
23,298
378
11
The constraints are small. Can you try the combination of every two houses? Greedily, the maximum distance will come from either the pair of the leftmost house and possibly some house on the right with a different color, or the pair of the rightmost house and possibly some house on the left with a different color.
1231,1984,2144
2,200
Stamping the Grid
stamping-the-grid
You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied). You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that they follow the given restrictions and requirements: Return true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false.
Array,Greedy,Matrix,Prefix Sum
Hard
28.4
11,828
3,358
213
19
We can check if every empty cell is a part of a consecutive row of empty cells that has a width of at least stampWidth as well as a consecutive column of empty cells that has a height of at least stampHeight. We can prove that this condition is sufficient and necessary to fit the stamps while following the given restrictions and requirements. For each row, find every consecutive row of empty cells, and mark all the cells where the consecutive row is at least stampWidth wide. Do the same for the columns with stampHeight. Then, you can check if every cell is marked twice.
221,361,1242
2,201
Valid Arrangement of Pairs
valid-arrangement-of-pairs
You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti. Return any valid arrangement of pairs. Note: The inputs will be generated such that there exists a valid arrangement of pairs.
Depth-First Search,Graph,Eulerian Circuit
Hard
40
11,009
4,407
240
10
Could you convert this into a graph problem? Consider the pairs as edges and each number as a node. We have to find an Eulerian path of this graph. Hierholzer’s algorithm can be used.
332,2121
2,202
Sum of k-Mirror Numbers
sum-of-k-mirror-numbers
A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k. Given the base k and the number n, return the sum of the n smallest k-mirror numbers.
Math,Enumeration
Hard
41.2
12,203
5,030
80
117
Since we need to reduce search space, instead of checking if every number is a palindrome in base-10, can we try to "generate" the palindromic numbers? If you are provided with a d digit number, how can you generate a palindrome with 2*d or 2*d - 1 digit? Try brute-forcing and checking if the palindrome you generated is a "k-Mirror" number.
247,897
2,203
Number of Spaces Cleaning Robot Cleaned
number-of-spaces-cleaning-robot-cleaned
null
Array,Matrix,Simulation
Medium
53.7
4,393
2,360
55
14
Simulate how the robot moves and keep track of how many spaces it has cleaned so far. When can we stop the simulation? When the robot reaches a space that it has already cleaned and is facing the same direction as before, we can stop the simulation.
865