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
828
Chalkboard XOR Game
chalkboard-xor-game
You are given an array of integers nums represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins. Return true if and only if Alice wins the game, assuming both players play optimally.
Array,Math,Bit Manipulation,Brainteaser,Game Theory
Hard
53.3
12,094
6,444
126
235
null
null
829
Subdomain Visit Count
subdomain-visit-count
A website domain "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com" and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly. A count-paired domain is a domain that has one of the two formats "rep d1.d2.d3" or "rep d1.d2" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself. Given an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order.
Array,Hash Table,String,Counting
Medium
74.2
228,000
169,116
1,050
1,109
null
null
830
Largest Triangle Area
largest-triangle-area
Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted.
Array,Math,Geometry
Easy
59.6
54,067
32,240
332
1,318
null
1018
831
Largest Sum of Averages
largest-sum-of-averages
You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in nums, and that the score is not necessarily an integer. Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted.
Array,Dynamic Programming
Medium
52.4
75,480
39,546
1,547
76
null
null
832
Binary Tree Pruning
binary-tree-pruning
Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed. A subtree of a node node is node plus every node that is a descendant of node.
Tree,Depth-First Search,Binary Tree
Medium
71
196,440
139,432
2,373
66
null
null
833
Bus Routes
bus-routes
You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.
Array,Hash Table,Breadth-First Search
Hard
45.3
183,370
83,037
1,992
51
null
null
834
Ambiguous Coordinates
ambiguous-coordinates
We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces and ended up with the string s. Return a list of strings representing all possibilities for what our original coordinates could have been. Our original representation never had extraneous zeroes, so we never started with numbers like "00", "0.0", "0.00", "1.0", "001", "00.01", or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like ".1". The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)
String,Backtracking
Medium
55.9
45,529
25,467
251
588
null
null
835
Linked List Components
linked-list-components
You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values. Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list.
Hash Table,Linked List
Medium
58
117,314
68,083
696
1,743
null
2299
836
Race Car
race-car
Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse): For example, after commands "AAR", your car goes to positions 0 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1. Given a target position target, return the length of the shortest sequence of instructions to get there.
Dynamic Programming
Hard
42.6
86,020
36,686
919
97
null
null
837
Most Common Word
most-common-word
Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique. The words in paragraph are case-insensitive and the answer should be returned in lowercase.
Hash Table,String,Counting
Easy
45.2
626,728
283,564
1,245
2,543
null
null
838
Design Linked List
design-linked-list
Design your implementation of the linked list. You can choose to use a singly or doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed. Implement the MyLinkedList class:
Linked List,Design
Medium
27
679,114
183,220
1,420
1,167
null
1337
839
Short Encoding of Words
short-encoding-of-words
A valid encoding of an array of words is any reference string s and array of indices indices such that: Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words.
Array,Hash Table,String,Trie
Medium
55.2
81,434
44,965
694
262
null
null
841
Shortest Distance to a Character
shortest-distance-to-a-character
Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s. The distance between two indices i and j is abs(i - j), where abs is the absolute value function.
Array,Two Pointers,String
Easy
70.9
184,202
130,681
2,162
120
null
null
842
Card Flipping Game
card-flipping-game
You are given n cards, with a positive integer printed on the front and back of each card (possibly different). You can flip any number of cards (possibly zero). After choosing the front and the back of each card, you will pick each card, and if the integer printed on the back of this card is not printed on the front of any other card, then this integer is good. You are given two integer array fronts and backs where fronts[i] and backs[i] are the integers printer on the front and the back of the ith card respectively. Return the smallest good and integer after flipping the cards. If there are no good integers, return 0. Note that a flip swaps the front and back numbers, so the value on the front is now on the back and vice versa.
Array,Hash Table
Medium
44.6
28,904
12,902
110
628
null
null
843
Binary Trees With Factors
binary-trees-with-factors
Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.
Array,Hash Table,Dynamic Programming
Medium
43.7
83,583
36,507
834
101
null
null
850
Insert into a Sorted Circular Linked List
insert-into-a-sorted-circular-linked-list
null
Linked List
Medium
34.4
319,840
109,918
906
599
null
147
851
Goat Latin
goat-latin
You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: Return the final sentence representing the conversion from sentence to Goat Latin.
String
Easy
67.6
209,025
141,230
674
1,084
null
null
852
Friends Of Appropriate Ages
friends-of-appropriate-ages
There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person. A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true: Otherwise, x will send a friend request to y. Note that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themself. Return the total number of friend requests made.
Array,Two Pointers,Binary Search,Sorting
Medium
45.9
137,798
63,269
541
1,037
null
null
853
Most Profit Assigning Work
most-profit-assigning-work
You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: Every worker can be assigned at most one job, but one job can be completed multiple times. Return the maximum profit we can achieve after assigning the workers to the jobs.
Array,Two Pointers,Binary Search,Greedy,Sorting
Medium
41.7
85,414
35,632
849
97
null
2180
854
Making A Large Island
making-a-large-island
You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. Return the size of the largest island in grid after applying this operation. An island is a 4-directionally connected group of 1s.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Hard
44.7
236,442
105,794
2,242
48
null
null
855
Count Unique Characters of All Substrings of a Given String
count-unique-characters-of-all-substrings-of-a-given-string
Let's define a function countUniqueChars(s) that returns the number of unique characters on s. Given a string s, return the sum of countUniqueChars(t) where t is a substring of s. Notice that some substrings can be repeated so in this case you have to count the repeated ones too.
String,Dynamic Programming
Hard
49.7
78,320
38,959
1,243
169
null
null
856
Consecutive Numbers Sum
consecutive-numbers-sum
Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.
Math,Enumeration
Hard
41
164,713
67,555
998
1,209
null
null
857
Positions of Large Groups
positions-of-large-groups
In a string s of lowercase letters, these letters form consecutive groups of the same character. For example, a string like s = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z", and "yy". A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, "xxxx" has the interval [3,6]. A group is considered large if it has 3 or more characters. Return the intervals of every large group sorted in increasing order by start index.
String
Easy
51.4
137,434
70,621
619
111
null
2260
858
Masking Personal Information
masking-personal-information
You are given a personal information string s, representing either an email address or a phone number. Return the masked personal information using the below rules. Email address: An email address is: To mask an email: Phone number: A phone number is formatted as follows: To mask a phone number:
String
Medium
46
30,991
14,250
117
400
null
null
859
Design Circular Deque
design-circular-deque
Design your implementation of the circular double-ended queue (deque). Implement the MyCircularDeque class:
Array,Linked List,Design,Queue
Medium
57.2
73,935
42,296
683
56
null
860,1767
860
Design Circular Queue
design-circular-queue
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer". One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. Implementation the MyCircularQueue class: You must solve the problem without using the built-in queue data structure in your programming language.
Array,Linked List,Design,Queue
Medium
48.6
349,928
170,144
1,642
170
null
859,1767
861
Flipping an Image
flipping-an-image
Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.
Array,Two Pointers,Matrix,Simulation
Easy
79.7
365,811
291,381
2,060
201
null
null
862
Find And Replace in String
find-and-replace-in-string
You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k. To complete the ith replacement operation: For example, if s = "abcd", indices[i] = 0, sources[i] = "ab", and targets[i] = "eee", then the result of this replacement will be "eeecd". All replacement operations must occur simultaneously, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap. Return the resulting string after performing all replacement operations on s. A substring is a contiguous sequence of characters in a string.
Array,String,Sorting
Medium
54.3
195,433
106,187
814
780
null
null
863
Sum of Distances in Tree
sum-of-distances-in-tree
There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.
Dynamic Programming,Tree,Depth-First Search,Graph
Hard
52.9
76,967
40,727
2,472
58
null
1021,2175
864
Image Overlap
image-overlap
You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values. We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images. Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased. Return the largest possible overlap.
Array,Matrix
Medium
61.3
77,230
47,304
100
29
null
null
865
Robot Room Cleaner
robot-room-cleaner
null
Backtracking,Interactive
Hard
75.6
153,744
116,296
2,152
128
null
286,1931,1959,2203
866
Rectangle Overlap
rectangle-overlap
An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.
Math,Geometry
Easy
43.1
232,372
100,219
1,385
383
null
223
867
New 21 Game
new-21-game
Alice plays the following game, loosely based on the card game "21". Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets k or more points. Return the probability that Alice has n or fewer points. Answers within 10-5 of the actual answer are considered accepted.
Math,Dynamic Programming,Sliding Window,Probability and Statistics
Medium
36
86,086
31,029
942
629
null
null
868
Push Dominoes
push-dominoes
There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string dominoes representing the initial state where: Return a string representing the final state.
Two Pointers,String,Dynamic Programming
Medium
52.3
109,893
57,485
1,629
110
null
null
869
Similar String Groups
similar-string-groups
Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal. For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts". Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}.  Notice that "tars" and "arts" are in the same group even though they are not similar.  Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?
Array,String,Depth-First Search,Breadth-First Search,Union Find
Hard
45.4
110,642
50,207
771
167
null
2276
870
Magic Squares In Grid
magic-squares-in-grid
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum. Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there?  (Each subgrid is contiguous).
Array,Math,Matrix
Medium
38.3
83,432
31,992
245
1,450
null
1311
871
Keys and Rooms
keys-and-rooms
There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.
Depth-First Search,Breadth-First Search,Graph
Medium
68.9
274,493
189,061
2,954
172
null
261
872
Split Array into Fibonacci Sequence
split-array-into-fibonacci-sequence
You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579]. Formally, a Fibonacci-like sequence is a list f of non-negative integers such that: Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself. Return any Fibonacci-like sequence split from num, or return [] if it cannot be done.
String,Backtracking
Medium
37.8
80,355
30,350
824
249
null
306,1013
873
Guess the Word
guess-the-word
This is an interactive problem. You are given an array of unique strings wordlist where wordlist[i] is 6 letters long, and one word in this list is chosen as secret. You may call Master.guess(word) to guess a word. The guessed word should have type string and must be from the original list with 6 lowercase letters. This function returns an integer type, representing the number of exact matches (value and position) of your guess to the secret word. Also, if your guess is not in the given wordlist, it will return -1 instead. For each test case, you have exactly 10 guesses to guess the word. At the end of any number of calls, if you have made 10 or fewer calls to Master.guess and at least one of these guesses was secret, then you pass the test case.
Array,Math,String,Interactive,Game Theory
Hard
43.1
263,498
113,453
1,196
1,331
null
null
874
Backspace String Compare
backspace-string-compare
Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty.
Two Pointers,String,Stack,Simulation
Easy
47.3
860,272
406,718
3,801
185
null
1720
875
Longest Mountain in Array
longest-mountain-in-array
You may recall that an array arr is a mountain array if and only if: Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.
Array,Two Pointers,Dynamic Programming,Enumeration
Medium
39.8
223,572
88,970
1,841
55
null
1766,2205
876
Hand of Straights
hand-of-straights
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards. Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.
Array,Hash Table,Greedy,Sorting
Medium
56.2
153,110
86,064
1,322
113
null
null
877
Shortest Path Visiting All Nodes
shortest-path-visiting-all-nodes
You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.
Dynamic Programming,Bit Manipulation,Breadth-First Search,Graph,Bitmask
Hard
61.2
90,353
55,288
2,362
121
null
null
878
Shifting Letters
shifting-letters
You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times. Return the final string after all such shifts to s are applied.
Array,String
Medium
45.4
157,075
71,387
849
96
null
1954
879
Maximize Distance to Closest Person
maximize-distance-to-closest-person
You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed). There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return that maximum distance to the closest person.
Array
Medium
47.4
359,728
170,547
2,552
163
null
885
880
Rectangle Area II
rectangle-area-ii
You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner. Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once. Return the total area. Since the answer may be too large, return it modulo 109 + 7.
Array,Segment Tree,Line Sweep,Ordered Set
Hard
53.3
54,704
29,148
772
51
null
null
881
Loud and Rich
loud-and-rich
There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness. You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time). Return an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x.
Array,Depth-First Search,Graph,Topological Sort
Medium
56.6
41,245
23,326
616
544
null
null
882
Peak Index in a Mountain Array
peak-index-in-a-mountain-array
Let's call an array arr a mountain if the following properties hold: Given an integer array arr that is guaranteed to be a mountain, return any i such that arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].
Array,Binary Search
Easy
70.6
501,691
354,121
2,494
1,616
null
162,1185,1766
883
Car Fleet
car-fleet
There are n cars going to the same destination along a one-lane road. The destination is target miles away. You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return the number of car fleets that will arrive at the destination.
Array,Stack,Sorting,Monotonic Stack
Medium
48
160,651
77,114
1,333
397
null
1902,2317
884
K-Similar Strings
k-similar-strings
Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2. Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.
String,Breadth-First Search
Hard
39.3
81,593
32,042
801
48
null
770
885
Exam Room
exam-room
There is an exam room with n seats in a single row labeled from 0 to n - 1. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0. Design a class that simulates the mentioned exam room. Implement the ExamRoom class:
Design,Ordered Set
Medium
43.6
106,672
46,501
963
374
null
879
886
Score of Parentheses
score-of-parentheses
Given a balanced parentheses string s, return the score of the string. The score of a balanced parentheses string is based on the following rule:
String,Stack
Medium
65.4
207,101
135,503
4,324
140
null
null
887
Minimum Cost to Hire K Workers
minimum-cost-to-hire-k-workers
There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker. We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules: Given the integer k, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5 of the actual answer will be accepted.
Array,Greedy,Sorting,Heap (Priority Queue)
Hard
51.6
96,508
49,820
1,599
192
null
null
888
Mirror Reflection
mirror-reflection
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. Given the two integers p and q, return the number of the receptor that the ray meets first. The test cases are guaranteed so that the ray will meet a receptor eventually.
Math,Geometry
Medium
59.6
44,050
26,258
366
712
null
null
889
Buddy Strings
buddy-strings
Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].
Hash Table,String
Easy
28.8
408,704
117,591
1,384
879
null
1777,1915
890
Lemonade Change
lemonade-change
At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5. Note that you do not have any change in hand at first. Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.
Array,Greedy
Easy
52.4
180,709
94,723
1,206
120
null
null
891
Score After Flipping Matrix
score-after-flipping-matrix
You are given an m x n binary matrix grid. A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's). Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. Return the highest possible score after making any number of moves (including zero moves).
Array,Greedy,Bit Manipulation,Matrix
Medium
74.8
45,815
34,267
1,024
162
null
2268
892
Shortest Subarray with Sum at Least K
shortest-subarray-with-sum-at-least-k
Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1. A subarray is a contiguous part of an array.
Array,Binary Search,Queue,Sliding Window,Heap (Priority Queue),Prefix Sum,Monotonic Queue
Hard
26.2
263,462
68,923
2,814
74
null
null
893
All Nodes Distance K in Binary Tree
all-nodes-distance-k-in-binary-tree
Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node. You can return the answer in any order.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
61
369,754
225,513
6,051
125
null
null
894
Random Pick with Blacklist
random-pick-with-blacklist
You are given an integer n and an array of unique integers blacklist. Design an algorithm to pick a random integer in the range [0, n - 1] that is not in blacklist. Any integer that is in the mentioned range and not in blacklist should be equally likely to be returned. Optimize your algorithm such that it minimizes the number of calls to the built-in random function of your language. Implement the Solution class:
Hash Table,Math,Binary Search,Sorting,Randomized
Hard
33.2
83,468
27,746
605
91
null
398,912,2107
895
Shortest Path to Get All Keys
shortest-path-to-get-all-keys
You are given an m x n grid grid where: You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall. If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key. For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet. Return the lowest number of moves to acquire all keys. If it is impossible, return -1.
Bit Manipulation,Breadth-First Search
Hard
44.5
51,628
22,966
761
25
null
null
896
Smallest Subtree with all the Deepest Nodes
smallest-subtree-with-all-the-deepest-nodes
Given the root of a binary tree, the depth of each node is the shortest distance to the root. Return the smallest subtree such that it contains all the deepest nodes in the original tree. A node is called the deepest if it has the largest depth possible among any node in the entire tree. The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
67.8
150,133
101,824
1,917
324
null
null
897
Prime Palindrome
prime-palindrome
Given an integer n, return the smallest prime palindrome greater than or equal to n. An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number. An integer is a palindrome if it reads the same from left to right as it does from right to left. The test cases are generated so that the answer always exists and is in the range [2, 2 * 108].
Math
Medium
25.9
98,489
25,503
315
704
null
2202
898
Transpose Matrix
transpose-matrix
Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
Array,Matrix,Simulation
Easy
61.1
213,787
130,561
1,139
371
We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!
null
899
Binary Gap
binary-gap
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0. Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.
Math,Bit Manipulation
Easy
61.8
93,801
57,939
422
590
null
null
900
Reordered Power of 2
reordered-power-of-2
You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return true if and only if we can do this so that the resulting number is a power of two.
Math,Sorting,Counting,Enumeration
Medium
61.3
66,480
40,760
577
170
null
null
901
Advantage Shuffle
advantage-shuffle
You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i]. Return any permutation of nums1 that maximizes its advantage with respect to nums2.
Array,Greedy,Sorting
Medium
51.2
102,654
52,584
1,221
78
null
null
902
Minimum Number of Refueling Stops
minimum-number-of-refueling-stops
A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas. The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1. Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Array,Dynamic Programming,Greedy,Heap (Priority Queue)
Hard
35.7
195,665
69,794
2,436
48
null
null
903
Implement Rand10() Using Rand7()
implement-rand10-using-rand7
Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API. Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().
Math,Rejection Sampling,Randomized,Probability and Statistics
Medium
46.8
132,350
61,882
864
283
null
null
904
Leaf-Similar Trees
leaf-similar-trees
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence. For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
Tree,Depth-First Search,Binary Tree
Easy
65
249,610
162,142
1,648
55
null
null
905
Length of Longest Fibonacci Subsequence
length-of-longest-fibonacci-subsequence
A sequence x1, x2, ..., xn is Fibonacci-like if: Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0. A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].
Array,Hash Table,Dynamic Programming
Medium
48.6
97,657
47,481
1,407
50
null
1013
906
Walking Robot Simulation
walking-robot-simulation
A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands: Some of the grid squares are obstacles. The ith obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command. Return the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5, return 25). Note:
Array,Simulation
Medium
37.7
83,483
31,501
69
13
null
2178
907
Koko Eating Bananas
koko-eating-bananas
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return the minimum integer k such that she can eat all the bananas within h hours.
Array,Binary Search
Medium
54.7
306,246
167,396
3,982
177
null
788,1335,2188
908
Middle of the Linked List
middle-of-the-linked-list
Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node.
Linked List,Two Pointers
Easy
72.6
861,365
625,120
5,116
129
null
2216,2236
909
Stone Game
stone-game
Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties. Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins. Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins.
Array,Math,Dynamic Programming,Game Theory
Medium
69.1
221,144
152,873
1,943
1,996
null
1685,1788,1808,2002,2156
910
Nth Magical Number
nth-magical-number
A positive integer is magical if it is divisible by either a or b. Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.
Math,Binary Search
Hard
35.8
81,480
29,143
962
134
null
null
911
Profitable Schemes
profitable-schemes
There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n. Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 109 + 7.
Array,Dynamic Programming
Hard
40.7
36,113
14,689
443
40
null
null
912
Random Pick with Weight
random-pick-with-weight
You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index. You need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w).
Math,Binary Search,Prefix Sum,Randomized
Medium
46.1
625,439
288,036
679
241
null
398,894,914
913
Random Flip Matrix
random-flip-matrix
There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1. All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned. Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity. Implement the Solution class:
Hash Table,Math,Reservoir Sampling,Randomized
Medium
39
33,969
13,252
293
89
null
null
914
Random Point in Non-overlapping Rectangles
random-point-in-non-overlapping-rectangles
You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle. Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned. Note that an integer point is a point that has integer coordinates. Implement the Solution class:
Math,Binary Search,Reservoir Sampling,Prefix Sum,Ordered Set,Randomized
Medium
39.1
86,569
33,876
379
594
null
912,915
915
Generate Random Point in a Circle
generate-random-point-in-a-circle
Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle. Implement the Solution class:
Math,Geometry,Rejection Sampling,Randomized
Medium
39.3
84,315
33,160
360
674
null
914
916
Decoded String at Index
decoded-string-at-index
You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: Given an integer k, return the kth letter (1-indexed) in the decoded string.
String,Stack
Medium
28.3
117,164
33,126
1,142
187
null
null
917
Boats to Save People
boats-to-save-people
You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit. Return the minimum number of boats to carry every given person.
Array,Two Pointers,Greedy,Sorting
Medium
52.4
270,544
141,888
2,974
79
null
null
918
Reachable Nodes In Subdivided Graph
reachable-nodes-in-subdivided-graph
You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge. To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi]. In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less. Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.
Graph,Heap (Priority Queue),Shortest Path
Hard
49.9
40,284
20,114
523
199
null
2213,2218
919
Projection Area of 3D Shapes
projection-area-of-3d-shapes
You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes. Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j). We view the projection of these cubes onto the xy, yz, and zx planes. A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the "shadow" when looking at the cubes from the top, the front, and the side. Return the total area of all three projections.
Array,Math,Geometry,Matrix
Easy
70
57,337
40,133
390
1,140
null
null
920
Uncommon Words from Two Sentences
uncommon-words-from-two-sentences
A sentence is a string of single-space separated words where each word consists only of lowercase letters. A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence. Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.
Hash Table,String
Easy
65.5
147,023
96,368
898
137
null
2190
921
Spiral Matrix III
spiral-matrix-iii
You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid. Return an array of coordinates representing the positions of the grid in the order you visited them.
Array,Matrix,Simulation
Medium
72.4
46,878
33,947
514
563
null
54,59
922
Possible Bipartition
possible-bipartition
We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
47.3
221,370
104,627
2,240
51
null
null
923
Super Egg Drop
super-egg-drop
You are given k 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. 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,Binary Search,Dynamic Programming
Hard
27.2
164,494
44,710
2,338
130
null
2031
924
Fair Candy Swap
fair-candy-swap
Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.
Array,Hash Table,Binary Search,Sorting
Easy
60.4
133,364
80,560
1,249
230
null
null
925
Construct Binary Tree from Preorder and Postorder Traversal
construct-binary-tree-from-preorder-and-postorder-traversal
Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree. If there exist multiple answers, you can return any of them.
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
Medium
69.9
99,810
69,719
1,833
85
null
null
926
Find and Replace Pattern
find-and-replace-pattern
Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order. A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.
Array,Hash Table,String
Medium
75.6
128,437
97,113
1,791
117
null
null
927
Sum of Subsequence Widths
sum-of-subsequence-widths
The width of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Array,Math,Sorting
Hard
35.4
42,660
15,081
489
139
null
null
928
Surface Area of 3D Shapes
surface-area-of-3d-shapes
You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j). After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return the total surface area of the resulting shapes. Note: The bottom face of each shape counts toward its surface area.
Array,Math,Geometry,Matrix
Easy
61.8
45,642
28,188
404
567
null
null
929
Groups of Special-Equivalent Strings
groups-of-special-equivalent-strings
You are given an array of strings of the same length words. In one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i]. Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j]. A group of special-equivalent strings from words is a non-empty subset of words such that: Return the number of groups of special-equivalent strings from words.
Array,Hash Table,String
Medium
70.5
58,103
40,965
430
1,386
null
null
930
All Possible Full Binary Trees
all-possible-full-binary-trees
Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0. Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order. A full binary tree is a binary tree where each node has exactly 0 or 2 children.
Dynamic Programming,Tree,Recursion,Memoization,Binary Tree
Medium
79.4
104,069
82,629
2,544
187
null
null
931
Maximum Frequency Stack
maximum-frequency-stack
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class:
Hash Table,Stack,Design,Ordered Set
Hard
66.4
186,266
123,623
3,573
54
null
null
932
Monotonic Array
monotonic-array
An array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j]. Given an integer array nums, return true if the given array is monotonic, or false otherwise.
Array
Easy
58.4
345,603
202,002
1,478
54
null
2316
933
Increasing Order Search Tree
increasing-order-search-tree
Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
Stack,Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
76.2
219,615
167,325
2,301
595
null
null
934
Bitwise ORs of Subarrays
bitwise-ors-of-subarrays
We have an array arr of non-negative integers. For every (contiguous) subarray sub = [arr[i], arr[i + 1], ..., arr[j]] (with i <= j), we take the bitwise OR of all the elements in sub, obtaining a result arr[i] | arr[i + 1] | ... | arr[j]. Return the number of possible results. Results that occur more than once are only counted once in the final answer
Array,Dynamic Programming,Bit Manipulation
Medium
36.3
71,422
25,906
946
176
null
null