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
201
Bitwise AND of Numbers Range
bitwise-and-of-numbers-range
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Bit Manipulation
Medium
41.8
510,983
213,336
2,225
176
null
null
202
Happy Number
happy-number
Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Return true if n is a happy number, and false if not.
Hash Table,Math,Two Pointers
Easy
53.1
1,496,471
795,194
5,193
694
null
141,258,263,2076
203
Remove Linked List Elements
remove-linked-list-elements
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Linked List,Recursion
Easy
43.4
1,582,236
686,326
4,794
162
null
27,237,2216
204
Count Primes
count-primes
Given an integer n, return the number of prime numbers that are strictly less than n.
Array,Math,Enumeration,Number Theory
Medium
33
1,819,491
600,270
4,703
985
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors: 2 × 6 = 12 3 × 4 = 12 4 × 3 = 12 6 × 2 = 12 As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n. Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach? public int countPrimes(int n) { int count = 0; for (int i = 1; i < n; i++) { if (isPrime(i)) count++; } return count; } private boolean isPrime(int num) { if (num <= 1) return false; // Loop's ending condition is i * i <= num instead of i <= sqrt(num) // to avoid repeatedly calling an expensive function sqrt(). for (int i = 2; i * i <= num; i++) { if (num % i == 0) return false; } return true; } The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple. Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0. We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime. The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia. public int countPrimes(int n) { boolean[] isPrime = new boolean[n]; for (int i = 2; i < n; i++) { isPrime[i] = true; } // Loop's ending condition is i * i < n instead of i < sqrt(n) // to avoid repeatedly calling an expensive function sqrt(). for (int i = 2; i * i < n; i++) { if (!isPrime[i]) continue; for (int j = i * i; j < n; j += i) { isPrime[j] = false; } } int count = 0; for (int i = 2; i < n; i++) { if (isPrime[i]) count++; } return count; }
263,264,279
205
Isomorphic Strings
isomorphic-strings
Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
Hash Table,String
Easy
42.1
1,160,012
487,870
3,435
638
null
290
206
Reverse Linked List
reverse-linked-list
Given the head of a singly linked list, reverse the list, and return the reversed list.
Linked List,Recursion
Easy
70.1
2,927,119
2,052,205
11,446
199
null
92,156,234,2196,2236
207
Course Schedule
course-schedule
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. Return true if you can finish all courses. Otherwise, return false.
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
45
1,871,795
842,989
9,007
362
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
210,261,310,630
208
Implement Trie (Prefix Tree)
implement-trie-prefix-tree
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class:
Hash Table,String,Design,Trie
Medium
57.9
977,633
566,500
6,810
90
null
211,642,648,676,1433,1949
209
Minimum Size Subarray Sum
minimum-size-subarray-sum
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Array,Binary Search,Sliding Window,Prefix Sum
Medium
43.2
1,177,660
508,413
6,324
185
null
76,325,718,1776,2211,2329
210
Course Schedule II
course-schedule-ii
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
46.4
1,304,440
605,688
6,464
232
This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
207,269,310,444,630,1101,2220
211
Design Add and Search Words Data Structure
design-add-and-search-words-data-structure
Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: Example: Constraints:
String,Depth-First Search,Design,Trie
Medium
44
896,587
394,265
4,757
198
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
208,746
212
Word Search II
word-search-ii
Given an m x n board of characters and a list of strings words, return all words on the board. Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Array,String,Backtracking,Trie,Matrix
Hard
38.1
1,120,097
426,210
5,820
213
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
79,1022,1433
213
House Robber II
house-robber-ii
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Array,Dynamic Programming
Medium
39.8
960,606
382,370
5,261
91
Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.
198,256,276,337,600,656
214
Shortest Palindrome
shortest-palindrome
You are given a string s. You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation.
String,Rolling Hash,String Matching,Hash Function
Hard
31.7
425,047
134,927
2,322
187
null
5,28,336
215
Kth Largest Element in an Array
kth-largest-element-in-an-array
Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
63.3
2,021,242
1,279,643
8,917
480
null
324,347,414,789,1014,2113,2204,2250
216
Combination Sum III
combination-sum-iii
Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.
Array,Backtracking
Medium
63.9
444,760
284,155
2,739
74
null
39
217
Contains Duplicate
contains-duplicate
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
Array,Hash Table,Sorting
Easy
60.7
2,443,511
1,483,087
4,378
943
null
219,220
218
The Skyline Problem
the-skyline-problem
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively. The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]: You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]
Array,Divide and Conquer,Binary Indexed Tree,Segment Tree,Line Sweep,Heap (Priority Queue),Ordered Set
Hard
38.6
528,556
204,234
3,745
198
null
699
219
Contains Duplicate II
contains-duplicate-ii
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Array,Hash Table,Sliding Window
Easy
40.6
1,107,769
450,207
2,368
1,847
null
217,220
220
Contains Duplicate III
contains-duplicate-iii
Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k.
Array,Sliding Window,Sorting,Bucket Sort,Ordered Set
Medium
21.7
920,049
199,738
2,264
2,212
Time complexity O(n logk) - This will give an indication that sorting is involved for k elements. Use already existing state to evaluate next state - Like, a set of k sorted numbers are only needed to be tracked. When we are processing the next number in array, then we can utilize the existing sorted state and it is not necessary to sort next overlapping set of k numbers again.
217,219
221
Maximal Square
maximal-square
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Array,Dynamic Programming,Matrix
Medium
43.4
1,116,716
484,269
7,011
145
null
85,769,1312,2200
222
Count Complete Tree Nodes
count-complete-tree-nodes
Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Design an algorithm that runs in less than O(n) time complexity.
Binary Search,Tree,Depth-First Search,Binary Tree
Medium
55.1
719,342
396,136
4,722
312
null
270
223
Rectangle Area
rectangle-area
Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles. The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2). The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).
Math,Geometry
Medium
40.1
337,644
135,232
745
1,008
null
866
224
Basic Calculator
basic-calculator
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Math,String,Stack,Recursion
Hard
40.5
713,024
288,485
3,519
291
null
150,227,241,282,785,2147,2328
225
Implement Stack using Queues
implement-stack-using-queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty). Implement the MyStack class: Notes:
Stack,Design,Queue
Easy
52.5
552,169
290,064
2,028
782
null
232
226
Invert Binary Tree
invert-binary-tree
Given the root of a binary tree, invert the tree, and return its root.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
71.4
1,394,634
995,662
8,061
110
null
null
227
Basic Calculator II
basic-calculator-ii
Given a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Math,String,Stack
Medium
41.5
1,006,227
417,714
4,208
553
null
224,282,785
228
Summary Ranges
summary-ranges
You are given a sorted unique integer array nums. A range [a,b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums. Each range [a,b] in the list should be output as:
Array
Easy
46.3
629,144
291,499
2,035
1,147
null
163,352
229
Majority Element II
majority-element-ii
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Array,Hash Table,Sorting,Counting
Medium
42.2
667,653
282,018
4,680
277
How many majority elements could it possibly have? Do you have a better hint? Suggest it!
169,1102
230
Kth Smallest Element in a BST
kth-smallest-element-in-a-bst
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
66.6
1,100,066
732,943
6,137
123
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
94,671
231
Power of Two
power-of-two
Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x.
Math,Bit Manipulation,Recursion
Easy
44.9
1,354,147
608,583
3,100
288
null
191,326,342
232
Implement Queue using Stacks
implement-queue-using-stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). Implement the MyQueue class: Notes:
Stack,Design,Queue
Easy
57.9
682,866
395,580
3,210
218
null
225
233
Number of Digit One
number-of-digit-one
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Math,Dynamic Programming,Recursion
Hard
33.5
190,665
63,889
704
1,022
Beware of overflow.
172,1068
234
Palindrome Linked List
palindrome-linked-list
Given the head of a singly linked list, return true if it is a palindrome.
Linked List,Two Pointers,Stack,Recursion
Easy
46.5
2,014,641
935,997
8,563
523
null
9,125,206,2236
235
Lowest Common Ancestor of a Binary Search Tree
lowest-common-ancestor-of-a-binary-search-tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
56.8
1,282,701
729,126
5,455
182
null
236,1190,1780,1790,1816
236
Lowest Common Ancestor of a Binary Tree
lowest-common-ancestor-of-a-binary-tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Tree,Depth-First Search,Binary Tree
Medium
55.2
1,755,028
967,969
9,393
272
null
235,1190,1354,1780,1790,1816,2217
237
Delete Node in a Linked List
delete-node-in-a-linked-list
Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly. It is guaranteed that the node to be deleted is not a tail node in the list.
Linked List
Easy
71.7
1,093,877
784,762
4,258
11,520
null
203
238
Product of Array Except Self
product-of-array-except-self
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation.
Array,Prefix Sum
Medium
63.9
1,754,180
1,120,129
11,850
724
null
42,152,265,2267
239
Sliding Window Maximum
sliding-window-maximum
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
Hard
46.2
1,201,410
554,953
9,485
337
How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window’s size. Remove redundant elements and the queue should store only elements that need to be considered.
76,155,159,265,1814
240
Search a 2D Matrix II
search-a-2d-matrix-ii
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:
Array,Binary Search,Divide and Conquer,Matrix
Medium
48.3
1,215,171
586,774
7,143
121
null
74
241
Different Ways to Add Parentheses
different-ways-to-add-parentheses
Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order.
Math,String,Dynamic Programming,Recursion,Memoization
Medium
61.5
259,836
159,798
3,513
171
null
95,224,282,2147,2328
242
Valid Anagram
valid-anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Easy
61.4
1,961,949
1,203,937
4,620
209
null
49,266,438
243
Shortest Word Distance
shortest-word-distance
null
Array,String
Easy
64.3
268,584
172,586
993
85
null
244,245,2320
244
Shortest Word Distance II
shortest-word-distance-ii
null
Array,Hash Table,Two Pointers,String,Design
Medium
59.4
209,173
124,203
824
253
null
21,243,245
245
Shortest Word Distance III
shortest-word-distance-iii
null
Array,String
Medium
57.2
116,774
66,747
340
83
null
243,244
246
Strobogrammatic Number
strobogrammatic-number
null
Hash Table,Two Pointers,String
Easy
47.6
285,282
135,671
450
748
null
247,248,1069
247
Strobogrammatic Number II
strobogrammatic-number-ii
null
Array,String,Recursion
Medium
50.9
230,646
117,468
769
194
Try to use recursion and notice that it should recurse with n - 2 instead of n - 1.
246,248,2202
248
Strobogrammatic Number III
strobogrammatic-number-iii
null
Array,String,Recursion
Hard
41.3
81,199
33,542
270
170
null
246,247
249
Group Shifted Strings
group-shifted-strings
null
Array,Hash Table,String
Medium
63.4
260,115
165,023
1,288
238
null
49
250
Count Univalue Subtrees
count-univalue-subtrees
null
Tree,Depth-First Search,Binary Tree
Medium
54.8
215,228
117,876
932
299
null
572,687
251
Flatten 2D Vector
flatten-2d-vector
null
Array,Two Pointers,Design,Iterator
Medium
47.9
214,619
102,769
562
313
How many variables do you need to keep track? Two variables is all you need. Try with x and y. Beware of empty rows. It could be the first few rows. To write correct code, think about the invariant to maintain. What is it? The invariant is x and y must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it? Not sure? Think about how you would implement hasNext(). Which is more complex? Common logic in two different places should be refactored into a common method.
173,281,284,341
252
Meeting Rooms
meeting-rooms
null
Array,Sorting
Easy
56.7
463,131
262,491
1,376
67
null
56,253
253
Meeting Rooms II
meeting-rooms-ii
null
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
Medium
49.6
1,250,885
620,539
5,384
104
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied. If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
56,252,452,1184
254
Factor Combinations
factor-combinations
null
Array,Backtracking
Medium
48.6
217,685
105,862
890
48
null
39
255
Verify Preorder Sequence in Binary Search Tree
verify-preorder-sequence-in-binary-search-tree
null
Stack,Tree,Binary Search Tree,Recursion,Monotonic Stack,Binary Tree
Medium
47.5
134,362
63,813
916
68
null
144
256
Paint House
paint-house
null
Array,Dynamic Programming
Medium
58.6
262,070
153,579
1,747
119
null
198,213,265,276
257
Binary Tree Paths
binary-tree-paths
Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children.
String,Backtracking,Tree,Depth-First Search,Binary Tree
Easy
58.5
857,207
501,173
3,949
181
null
113,1030,2217
258
Add Digits
add-digits
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Math,Simulation,Number Theory
Easy
62.4
743,480
463,936
2,409
1,642
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
202,1082,2076,2264
259
3Sum Smaller
3sum-smaller
null
Array,Two Pointers,Binary Search,Sorting
Medium
50.3
227,026
114,177
1,232
124
null
15,16,611,1083
260
Single Number III
single-number-iii
Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order. You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.
Array,Bit Manipulation
Medium
67.1
372,615
250,144
3,806
182
null
136,137
261
Graph Valid Tree
graph-valid-tree
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
45.7
554,173
253,243
2,327
60
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
207,323,871
262
Trips and Users
trips-and-users
Table: Trips Table: Users The cancellation rate is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day. Write a SQL query to find the cancellation rate of requests with unbanned users (both client and driver must not be banned) each day between "2013-10-01" and "2013-10-03". Round Cancellation Rate to two decimal points. Return the result table in any order. The query result format is in the following example.
Database
Hard
37.8
298,221
112,594
709
454
null
1779,1785,1795
263
Ugly Number
ugly-number
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return true if n is an ugly number.
Math
Easy
41.8
699,108
292,500
1,376
1,018
null
202,204,264
264
Ugly Number II
ugly-number-ii
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return the nth ugly number.
Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
Medium
45.2
563,935
254,942
3,941
210
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
23,204,263,279,313,1307
265
Paint House II
paint-house-ii
null
Array,Dynamic Programming
Hard
50.7
185,563
94,055
968
33
null
238,239,256,276
266
Palindrome Permutation
palindrome-permutation
null
Hash Table,String,Bit Manipulation
Easy
65.4
248,715
162,569
860
63
Consider the palindromes of odd vs even length. What difference do you notice? Count the frequency of each character. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
5,242,267,409
267
Palindrome Permutation II
palindrome-permutation-ii
null
Hash Table,String,Backtracking
Medium
39.6
136,309
53,956
708
84
If a palindromic permutation exists, we just need to generate the first half of the string. To generate all distinct permutations of a (half of) string, use a similar approach from: Permutations II or Next Permutation.
31,47,266
268
Missing Number
missing-number
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Array,Hash Table,Math,Bit Manipulation,Sorting
Easy
59.3
1,649,957
977,912
5,317
2,830
null
41,136,287,770,2107
269
Alien Dictionary
alien-dictionary
null
Array,String,Depth-First Search,Breadth-First Search,Graph,Topological Sort
Hard
34.8
814,197
283,406
3,491
718
null
210
270
Closest Binary Search Tree Value
closest-binary-search-tree-value
null
Binary Search,Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
53.7
463,260
248,677
1,404
86
null
222,272,783
271
Encode and Decode Strings
encode-and-decode-strings
null
Array,String,Design
Medium
37.6
247,055
93,009
815
227
null
38,297,443,696
272
Closest Binary Search Tree Value II
closest-binary-search-tree-value-ii
null
Two Pointers,Stack,Tree,Depth-First Search,Binary Search Tree,Heap (Priority Queue),Binary Tree
Hard
56.8
167,444
95,078
1,033
33
Consider implement these two helper functions: getPredecessor(N), which returns the next smaller node to N. getSuccessor(N), which returns the next larger node to N. Try to assume that each node has a parent pointer, it makes the problem much easier. Without parent pointer we just need to keep track of the path from the root to the current node using a stack. You would need two stacks to track the path in finding predecessor and successor node separately.
94,270
273
Integer to English Words
integer-to-english-words
Convert a non-negative integer num to its English words representation.
Math,String,Recursion
Hard
29.6
1,008,214
298,067
2,025
4,942
Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)
12
274
H-Index
h-index
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return compute the researcher's h-index. According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. If there are several possible values for h, the maximum one is taken as the h-index.
Array,Sorting,Counting Sort
Medium
37.5
615,449
231,089
1,197
1,802
An easy approach is to sort the array first. What are the possible values of h-index? A faster approach is to use extra space.
275
275
H-Index II
h-index-ii
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in an ascending order, return compute the researcher's h-index. According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. If there are several possible values for h, the maximum one is taken as the h-index. You must write an algorithm that runs in logarithmic time.
Array,Binary Search
Medium
37
424,877
157,060
705
1,035
Expected runtime complexity is in O(log n) and the input is sorted.
274
276
Paint Fence
paint-fence
null
Dynamic Programming
Medium
42.8
197,036
84,256
1,235
354
null
198,213,256,265
277
Find the Celebrity
find-the-celebrity
null
Two Pointers,Greedy,Graph,Interactive
Medium
46.4
465,906
216,234
2,241
204
The best hint for this problem can be provided by the following figure: Well, if you understood the gist of the above idea, you can extend it to find a candidate that can possibly be a celebrity. Why do we say a "candidate"? That is for you to think. This is clearly a greedy approach to find the answer. However, there is some information that would still remain to be verified without which we can't obtain an answer with certainty. To get that stake in the ground, we would need some more calls to the knows API.
1039
278
First Bad Version
first-bad-version
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Binary Search,Interactive
Easy
41.5
2,305,289
956,971
4,654
1,743
null
34,35,374
279
Perfect Squares
perfect-squares
Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.
Math,Dynamic Programming,Breadth-First Search
Medium
51.8
1,002,301
519,105
6,581
291
null
204,264
280
Wiggle Sort
wiggle-sort
null
Array,Greedy,Sorting
Medium
66
172,096
113,554
907
74
null
75,324,2085
281
Zigzag Iterator
zigzag-iterator
null
Array,Design,Queue,Iterator
Medium
61.4
129,456
79,471
555
30
null
173,251,284,341,1894
282
Expression Add Operators
expression-add-operators
Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value. Note that operands in the returned expressions should not contain leading zeros.
Math,String,Backtracking
Hard
39.2
460,309
180,213
2,475
420
Note that a number can contain multiple digits. Since the question asks us to find all of the valid expressions, we need a way to iterate over all of them. (Hint: Recursion!) We can keep track of the expression string and evaluate it at the very end. But that would take a lot of time. Can we keep track of the expression's value as well so as to avoid the evaluation at the very end of recursion? Think carefully about the multiply operator. It has a higher precedence than the addition and subtraction operators. 1 + 2 = 3 1 + 2 - 4 --> 3 - 4 --> -1 1 + 2 - 4 * 12 --> -1 * 12 --> -12 (WRONG!) 1 + 2 - 4 * 12 --> -1 - (-4) + (-4 * 12) --> 3 + (-48) --> -45 (CORRECT!) We simply need to keep track of the last operand in our expression and reverse it's effect on the expression's value while considering the multiply operator.
150,224,227,241,494
283
Move Zeroes
move-zeroes
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array.
Array,Two Pointers
Easy
60.6
2,674,454
1,619,817
8,830
239
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
27
284
Peeking Iterator
peeking-iterator
Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations. Implement the PeekingIterator class: Note: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions.
Array,Design,Iterator
Medium
53.6
291,298
156,171
994
685
Think of "looking ahead". You want to cache the next element. Is one variable sufficient? Why or why not? Test your design with call order of peek() before next() vs next() before peek(). For a clean implementation, check out Google's guava library source code.
173,251,281
285
Inorder Successor in BST
inorder-successor-in-bst
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
47
551,827
259,214
2,081
78
null
94,173,509
286
Walls and Gates
walls-and-gates
null
Array,Breadth-First Search,Matrix
Medium
59.2
362,551
214,618
2,293
36
null
130,200,317,865,1036
287
Find the Duplicate Number
find-the-duplicate-number
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and uses only constant extra space.
Array,Two Pointers,Binary Search,Bit Manipulation
Medium
58.8
1,384,998
814,172
13,323
1,514
null
41,136,142,268,645
288
Unique Word Abbreviation
unique-word-abbreviation
null
Array,Hash Table,String,Design
Medium
24.7
260,052
64,209
161
1,639
null
170,320
289
Game of Life
game-of-life
According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.
Array,Matrix,Simulation
Medium
65.2
515,014
335,534
4,649
436
null
73
290
Word Pattern
word-pattern
Given a pattern and a string s, find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
Hash Table,String
Easy
40.2
886,230
356,008
3,477
402
null
205,291
291
Word Pattern II
word-pattern-ii
null
Hash Table,String,Backtracking
Medium
46.2
129,832
59,964
720
54
null
290
292
Nim Game
nim-game
You are playing the following Nim Game with your friend: Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.
Math,Brainteaser,Game Theory
Easy
55.5
497,284
275,879
1,042
2,198
If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?
294
293
Flip Game
flip-game
null
String
Easy
62.5
94,469
59,045
161
381
null
294
294
Flip Game II
flip-game-ii
null
Math,Dynamic Programming,Backtracking,Memoization,Game Theory
Medium
51.5
123,119
63,375
519
49
null
292,293,375,464
295
Find Median from Data Stream
find-median-from-data-stream
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values. Implement the MedianFinder class:
Two Pointers,Design,Sorting,Heap (Priority Queue),Data Stream
Hard
50.2
886,525
445,468
6,641
123
null
480,1953,2207
296
Best Meeting Point
best-meeting-point
null
Array,Math,Sorting,Matrix
Hard
59.4
97,281
57,766
873
70
Try to solve it in one dimension first. How can this solution apply to the two dimension case?
317,462
297
Serialize and Deserialize Binary Tree
serialize-and-deserialize-binary-tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
Hard
53.6
1,109,191
594,595
6,420
250
null
271,449,652,765
298
Binary Tree Longest Consecutive Sequence
binary-tree-longest-consecutive-sequence
null
Tree,Depth-First Search,Binary Tree
Medium
51.1
234,391
119,775
881
212
null
128,549,1416
299
Bulls and Cows
bulls-and-cows
You are playing the Bulls and Cows game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: Given the secret number secret and your friend's guess guess, return the hint for your friend's guess. The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.
Hash Table,String,Counting
Medium
47.1
561,240
264,594
1,354
1,292
null
null
300
Longest Increasing Subsequence
longest-increasing-subsequence
Given an integer array nums, return the length of the longest strictly increasing subsequence. 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,Binary Search,Dynamic Programming
Medium
49.1
1,685,924
827,984
11,472
227
null
334,354,646,673,712,1766,2096,2234