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
301
Remove Invalid Parentheses
remove-invalid-parentheses
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return all the possible results. You may return the answer in any order.
String,Backtracking,Breadth-First Search
Hard
46.8
735,686
344,520
4,569
233
Since we don't know which of the brackets can possibly be removed, we try out all the options! We can use recursion to try out all possibilities for the given expression. For each of the brackets, we have 2 options: We keep the bracket and add it to the expression that we are building on the fly during recursion. OR, we can discard the bracket and move on. The one thing all these valid expressions have in common is that they will all be of the same length i.e. as compared to the original expression, all of these expressions will have the same number of characters removed. Can we somehow find the number of misplaced parentheses and use it in our solution? For every left parenthesis, we should have a corresponding right parenthesis. We can make use of two counters which keep track of misplaced left and right parenthesis and in one iteration we can find out these two values. 0 1 2 3 4 5 6 7 ( ) ) ) ( ( ( ) i = 0, left = 1, right = 0 i = 1, left = 0, right = 0 i = 2, left = 0, right = 1 i = 3, left = 0, right = 2 i = 4, left = 1, right = 2 i = 5, left = 2, right = 2 i = 6, left = 3, right = 2 i = 7, left = 2, right = 2 We have 2 misplaced left and 2 misplaced right parentheses. We found out that the exact number of left and right parenthesis that has to be removed to get a valid expression. So, e.g. in a 1000 parentheses string, if there are 2 misplaced left and 2 misplaced right parentheses, after we are done discarding 2 left and 2 right parentheses, we will have only one option per remaining character in the expression i.e. to consider them. We can't discard them.
20,2095
302
Smallest Rectangle Enclosing Black Pixels
smallest-rectangle-enclosing-black-pixels
null
Array,Binary Search,Depth-First Search,Breadth-First Search,Matrix
Hard
56.7
71,937
40,818
418
83
null
null
303
Range Sum Query - Immutable
range-sum-query-immutable
Given an integer array nums, handle multiple queries of the following type: Implement the NumArray class:
Array,Design,Prefix Sum
Easy
55.2
628,000
346,813
1,928
1,641
null
304,307,325
304
Range Sum Query 2D - Immutable
range-sum-query-2d-immutable
Given a 2D matrix matrix, handle multiple queries of the following type: Implement the NumMatrix class:
Array,Design,Matrix,Prefix Sum
Medium
47.5
464,723
220,873
2,502
243
null
303,308
305
Number of Islands II
number-of-islands-ii
null
Array,Union Find
Hard
39.3
284,469
111,911
1,413
42
null
200,2198
306
Additive Number
additive-number
An additive number is a string whose digits can form an additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return true if it is an additive number or false otherwise. Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.
String,Backtracking
Medium
30.6
224,865
68,718
725
625
null
872
307
Range Sum Query - Mutable
range-sum-query-mutable
Given an integer array nums, handle multiple queries of the following types: Implement the NumArray class:
Array,Design,Binary Indexed Tree,Segment Tree
Medium
38.7
464,756
179,687
2,687
142
null
303,308
308
Range Sum Query 2D - Mutable
range-sum-query-2d-mutable
null
Array,Design,Binary Indexed Tree,Segment Tree,Matrix
Hard
41
158,501
64,907
651
75
null
304,307
309
Best Time to Buy and Sell Stock with Cooldown
best-time-to-buy-and-sell-stock-with-cooldown
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Array,Dynamic Programming
Medium
52.3
519,802
272,061
5,575
196
null
121,122
310
Minimum Height Trees
minimum-height-trees
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. Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))  are called minimum height trees (MHTs). Return a list of all MHTs' root labels. You can return the answer in any order. The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
38.1
507,493
193,328
5,092
210
How many MHTs can a graph have at most?
207,210
311
Sparse Matrix Multiplication
sparse-matrix-multiplication
null
Array,Hash Table,Matrix
Medium
66.2
230,071
152,385
850
295
null
null
312
Burst Balloons
burst-balloons
You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it. Return the maximum coins you can collect by bursting the balloons wisely.
Array,Dynamic Programming
Hard
56.3
325,121
182,895
5,795
157
null
1042
313
Super Ugly Number
super-ugly-number
A super ugly number is a positive integer whose prime factors are in the array primes. Given an integer n and an array of integers primes, return the nth super ugly number. The nth super ugly number is guaranteed to fit in a 32-bit signed integer.
Array,Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
Medium
45.8
226,970
103,863
1,460
278
null
264
314
Binary Tree Vertical Order Traversal
binary-tree-vertical-order-traversal
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
51.1
514,798
263,089
2,358
258
null
102
315
Count of Smaller Numbers After Self
count-of-smaller-numbers-after-self
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
Hard
42
531,794
223,619
5,393
154
null
327,406,493,1482,2280
316
Remove Duplicate Letters
remove-duplicate-letters
Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
String,Stack,Greedy,Monotonic Stack
Medium
43.8
432,267
189,513
5,181
340
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
2157
317
Shortest Distance from All Buildings
shortest-distance-from-all-buildings
null
Array,Breadth-First Search,Matrix
Hard
43.3
313,743
135,949
1,525
168
null
286,296,1117
318
Maximum Product of Word Lengths
maximum-product-of-word-lengths
Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.
Array,String,Bit Manipulation
Medium
56.6
251,492
142,365
1,700
94
null
null
319
Bulb Switcher
bulb-switcher
There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Return the number of bulbs that are on after n rounds.
Math,Brainteaser
Medium
47.2
239,996
113,307
907
1,636
null
672,1037,1491
320
Generalized Abbreviation
generalized-abbreviation
null
String,Backtracking,Bit Manipulation
Medium
56.3
107,129
60,264
596
205
null
78,288,411
321
Create Maximum Number
create-maximum-number
You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k. Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved. Return an array of the k digits representing the answer.
Stack,Greedy,Monotonic Stack
Hard
28.4
173,497
49,224
1,323
307
null
402,670
322
Coin Change
coin-change
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin.
Array,Dynamic Programming,Breadth-First Search
Medium
40
2,373,497
950,323
10,775
262
null
1025,1393,2345
323
Number of Connected Components in an Undirected Graph
number-of-connected-components-in-an-undirected-graph
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
61
399,597
243,779
1,917
59
null
200,261,547,2218
324
Wiggle Sort II
wiggle-sort-ii
Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... You may assume the input array always has a valid answer.
Array,Divide and Conquer,Sorting,Quickselect
Medium
32.2
372,665
119,965
2,055
793
null
75,215,280,2085
325
Maximum Size Subarray Sum Equals k
maximum-size-subarray-sum-equals-k
null
Array,Hash Table
Medium
49.1
311,991
153,191
1,628
47
Compute the prefix sum array where psum[i] is the sum of all the elements from 0 to i. At each index i, the sum of the prefix is psum[i], so we are searching for the index x where psum[x] = psum[i] - k. The subarray [x + 1, i] will be of sum k. Use a hashmap to get the index x efficiently or to determine that it does not exist.
209,303,525,713
326
Power of Three
power-of-three
Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x.
Math,Recursion
Easy
43.4
1,046,656
454,534
902
118
null
231,342,1889
327
Count of Range Sum
count-of-range-sum
Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j.
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
Hard
36
163,712
59,005
1,502
155
null
315,493
328
Odd Even Linked List
odd-even-linked-list
Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1) extra space complexity and O(n) time complexity.
Linked List
Medium
59.5
871,544
518,520
5,183
383
null
725
329
Longest Increasing Path in a Matrix
longest-increasing-path-in-a-matrix
Given an m x n integers matrix, return the length of the longest increasing path in matrix. From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
Hard
49.6
639,552
317,264
5,154
88
null
null
330
Patching Array
patching-array
Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.
Array,Greedy
Hard
39.5
141,671
55,966
1,085
113
null
1930
331
Verify Preorder Serialization of a Binary Tree
verify-preorder-serialization-of-a-binary-tree
One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'. For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a null node. Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree. It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid. Note: You are not allowed to reconstruct the tree.
String,Stack,Tree,Binary Tree
Medium
43.7
258,229
112,808
1,659
81
null
null
332
Reconstruct Itinerary
reconstruct-itinerary
You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
Depth-First Search,Graph,Eulerian Circuit
Hard
40.1
689,553
276,521
3,766
1,545
null
2051,2201
333
Largest BST Subtree
largest-bst-subtree
null
Dynamic Programming,Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
41.2
197,621
81,417
1,173
99
You can recursively use algorithm similar to 98. Validate Binary Search Tree at each node of the tree, which will result in O(nlogn) time complexity.
null
334
Increasing Triplet Subsequence
increasing-triplet-subsequence
Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.
Array,Greedy
Medium
41.5
642,716
266,546
3,768
208
null
300,2122,2280
335
Self Crossing
self-crossing
You are given an array of integers distance. You start at point (0,0) on an X-Y plane and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. Return true if your path crosses itself, and false if it does not.
Array,Math,Geometry
Hard
29.1
94,557
27,512
249
444
null
null
336
Palindrome Pairs
palindrome-pairs
Given a list of unique words, return all the pairs of the distinct indices (i, j) in the given list, so that the concatenation of the two words words[i] + words[j] is a palindrome.
Array,Hash Table,String,Trie
Hard
35.9
409,115
146,725
2,618
244
null
5,214,2237
337
House Robber III
house-robber-iii
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root. Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night. Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Medium
53.5
528,529
282,635
6,128
93
null
198,213
338
Counting Bits
counting-bits
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
Dynamic Programming,Bit Manipulation
Easy
74.2
759,000
563,251
6,774
317
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
191
339
Nested List Weight Sum
nested-list-weight-sum
null
Depth-First Search,Breadth-First Search
Medium
81
231,221
187,385
1,277
292
null
364,565,690
340
Longest Substring with At Most K Distinct Characters
longest-substring-with-at-most-k-distinct-characters
null
Hash Table,String,Sliding Window
Medium
47.3
572,053
270,626
2,246
69
null
3,159,424,1034,1046,2134
341
Flatten Nested List Iterator
flatten-nested-list-iterator
You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the NestedIterator class: Your code will be tested with the following pseudocode: If res matches the expected flattened list, then your code will be judged as correct.
Stack,Tree,Depth-First Search,Design,Queue,Iterator
Medium
58.7
484,448
284,132
3,052
1,068
null
251,281,385,565
342
Power of Four
power-of-four
Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x.
Math,Bit Manipulation,Recursion
Easy
43.9
663,170
291,168
1,445
285
null
231,326
343
Integer Break
integer-break
Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. Return the maximum product you can get.
Math,Dynamic Programming
Medium
54
337,951
182,547
2,696
324
There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
1936
344
Reverse String
reverse-string
Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory.
Two Pointers,String,Recursion
Easy
74.7
2,078,623
1,553,675
4,831
937
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
345,541
345
Reverse Vowels of a String
reverse-vowels-of-a-string
Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.
Two Pointers,String
Easy
46.9
737,331
345,831
1,560
1,823
null
344,1089
346
Moving Average from Data Stream
moving-average-from-data-stream
null
Array,Design,Queue,Data Stream
Easy
76.3
332,734
253,722
1,255
118
null
2211
347
Top K Frequent Elements
top-k-frequent-elements
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
Medium
65.1
1,418,616
923,599
8,858
360
null
192,215,451,659,692,1014,1919
348
Design Tic-Tac-Toe
design-tic-tac-toe
null
Array,Hash Table,Design,Matrix
Medium
57.2
313,470
179,359
1,626
94
Could you trade extra space such that move() operation can be done in O(1)? You need two arrays: int rows[n], int cols[n], plus two variables: diagonal, anti_diagonal.
810
349
Intersection of Two Arrays
intersection-of-two-arrays
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Array,Hash Table,Two Pointers,Binary Search,Sorting
Easy
68.9
939,599
647,468
2,731
1,878
null
350,1149,1392,2190,2282
350
Intersection of Two Arrays II
intersection-of-two-arrays-ii
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
Array,Hash Table,Two Pointers,Binary Search,Sorting
Easy
54.8
1,412,120
774,103
4,292
684
null
349,1044,1392,2282
351
Android Unlock Patterns
android-unlock-patterns
null
Dynamic Programming,Backtracking
Medium
50.9
124,639
63,485
92
88
null
null
352
Data Stream as Disjoint Intervals
data-stream-as-disjoint-intervals
Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals. Implement the SummaryRanges class:
Binary Search,Design,Ordered Set
Hard
50.6
100,079
50,635
625
158
null
228,436,715
353
Design Snake Game
design-snake-game
null
Array,Design,Queue,Matrix
Medium
38.1
155,255
59,171
703
255
null
null
354
Russian Doll Envelopes
russian-doll-envelopes
You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other). Note: You cannot rotate an envelope.
Array,Binary Search,Dynamic Programming,Sorting
Hard
39
345,525
134,740
2,981
72
null
300,2123
355
Design Twitter
design-twitter
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user's news feed. Implement the Twitter class:
Hash Table,Linked List,Design,Heap (Priority Queue)
Medium
34.4
244,506
84,026
1,964
273
null
1640
356
Line Reflection
line-reflection
null
Array,Hash Table,Math
Medium
34.3
92,431
31,728
225
479
Find the smallest and largest x-value for all points. If there is a line then it should be at y = (minX + maxX) / 2. For each point, make sure that it has a reflected point in the opposite side.
149,447
357
Count Numbers with Unique Digits
count-numbers-with-unique-digits
Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.
Math,Dynamic Programming,Backtracking
Medium
50.6
200,530
101,429
870
1,223
A direct way is to use the backtracking approach. Backtracking should contains three states which are (the current number, number of steps to get that number and a bitmask which represent which number is marked as visited so far in the current number). Start with state (0,0,0) and count all valid number till we reach number of steps equals to 10n. This problem can also be solved using a dynamic programming approach and some knowledge of combinatorics. Let f(k) = count of numbers with unique digits with length equals k. f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0].
null
358
Rearrange String k Distance Apart
rearrange-string-k-distance-apart
null
Hash Table,String,Greedy,Sorting,Heap (Priority Queue),Counting
Hard
37
139,155
51,469
737
33
null
621,778,2300
359
Logger Rate Limiter
logger-rate-limiter
null
Hash Table,Design
Easy
74.9
292,455
218,984
1,209
160
null
362
360
Sort Transformed Array
sort-transformed-array
null
Array,Math,Two Pointers,Sorting
Medium
53.4
99,547
53,117
550
158
x^2 + x will form a parabola. Parameter A in: A * x^2 + B * x + C dictates the shape of the parabola. Positive A means the parabola remains concave (high-low-high), but negative A inverts the parabola to be convex (low-high-low).
1019
361
Bomb Enemy
bomb-enemy
null
Array,Dynamic Programming,Matrix
Medium
50
129,539
64,739
769
93
null
2192,2200
362
Design Hit Counter
design-hit-counter
null
Array,Hash Table,Binary Search,Design,Queue
Medium
67.3
237,572
159,884
1,482
128
null
359
363
Max Sum of Rectangle No Larger Than K
max-sum-of-rectangle-no-larger-than-k
Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k. It is guaranteed that there will be a rectangle with a sum no larger than k.
Array,Binary Search,Dynamic Programming,Matrix,Ordered Set
Hard
40.1
195,205
78,325
1,887
107
null
null
364
Nested List Weight Sum II
nested-list-weight-sum-ii
null
Stack,Depth-First Search,Breadth-First Search
Medium
68.3
164,928
112,591
960
289
null
339,565
365
Water and Jug Problem
water-and-jug-problem
You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs. If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end. Operations allowed:
Math,Depth-First Search,Breadth-First Search
Medium
34.4
179,289
61,740
761
1,117
null
null
366
Find Leaves of Binary Tree
find-leaves-of-binary-tree
null
Tree,Depth-First Search,Binary Tree
Medium
78.4
214,014
167,719
2,318
42
null
null
367
Valid Perfect Square
valid-perfect-square
Given a positive integer num, write a function which returns True if num is a perfect square else False. Follow up: Do not use any built-in library function such as sqrt.
Math,Binary Search
Easy
43
821,205
352,896
2,164
229
null
69,633
368
Largest Divisible Subset
largest-divisible-subset
Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies: If there are multiple solutions, return any of them.
Array,Math,Dynamic Programming,Sorting
Medium
40.5
368,307
149,204
3,136
143
null
null
369
Plus One Linked List
plus-one-linked-list
null
Linked List,Math
Medium
60.5
110,927
67,078
768
40
null
66
370
Range Addition
range-addition
null
Array,Prefix Sum
Medium
69.4
96,669
67,079
1,258
61
Thinking of using advanced data structures? You are thinking it too complicated. For each update operation, do you really need to update all elements between i and j? Update only the first and end element is sufficient. The optimal time complexity is O(k + n) and uses O(1) extra space.
598,2385
371
Sum of Two Integers
sum-of-two-integers
Given two integers a and b, return the sum of the two integers without using the operators + and -.
Math,Bit Manipulation
Medium
50.6
575,879
291,580
2,464
3,695
null
2
372
Super Pow
super-pow
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
Math,Divide and Conquer
Medium
37.6
129,129
48,553
464
1,081
null
50
373
Find K Pairs with Smallest Sums
find-k-pairs-with-smallest-sums
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.
Array,Heap (Priority Queue)
Medium
38.8
430,871
167,230
2,979
185
null
378,719,2150
374
Guess Number Higher or Lower
guess-number-higher-or-lower
We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num), which returns three possible results: Return the number that I picked.
Binary Search,Interactive
Easy
49
620,657
303,829
842
139
null
278,375,658
375
Guess Number Higher or Lower II
guess-number-higher-or-lower-ii
We are playing the Guessing Game. The game will work as follows: Given a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick.
Math,Dynamic Programming,Game Theory
Medium
45.3
203,280
92,178
1,430
1,768
The best strategy to play the game is to minimize the maximum loss you could possibly face. Another strategy is to minimize the expected loss. Here, we are interested in the first scenario. Take a small example (n = 3). What do you end up paying in the worst case? Check out this article if you're still stuck. The purely recursive implementation of minimax would be worthless for even a small n. You MUST use dynamic programming. As a follow-up, how would you modify your code to solve the problem of minimizing the expected loss, instead of the worst-case loss?
294,374,464,658
376
Wiggle Subsequence
wiggle-subsequence
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array nums, return the length of the longest wiggle subsequence of nums.
Array,Dynamic Programming,Greedy
Medium
44.9
301,689
135,314
2,617
93
null
2271
377
Combination Sum IV
combination-sum-iv
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target. The test cases are generated so that the answer can fit in a 32-bit integer.
Array,Dynamic Programming
Medium
49.3
482,241
237,874
3,333
383
null
39
378
Kth Smallest Element in a Sorted Matrix
kth-smallest-element-in-a-sorted-matrix
Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. You must find a solution with a memory complexity better than O(n2).
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
Medium
59.6
632,411
376,832
5,707
236
null
373,668,719,802
379
Design Phone Directory
design-phone-directory
null
Array,Hash Table,Linked List,Design,Queue
Medium
50.3
108,315
54,444
281
395
null
1955
380
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the RandomizedSet class: You must implement the functions of the class such that each function works in average O(1) time complexity.
Array,Hash Table,Math,Design,Randomized
Medium
51.3
913,746
468,732
5,304
284
null
381
381
Insert Delete GetRandom O(1) - Duplicates allowed
insert-delete-getrandom-o1-duplicates-allowed
RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also removing a random element. Implement the RandomizedCollection class: You must implement the functions of the class such that each function works on average O(1) time complexity. Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection.
Array,Hash Table,Math,Design,Randomized
Hard
35.4
300,917
106,653
1,592
114
null
380
382
Linked List Random Node
linked-list-random-node
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Implement the Solution class:
Linked List,Math,Reservoir Sampling,Randomized
Medium
58.9
255,660
150,600
1,712
432
null
398
383
Ransom Note
ransom-note
Given two strings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote.
Hash Table,String,Counting
Easy
55.8
659,531
367,856
1,646
297
null
691
384
Shuffle an Array
shuffle-an-array
Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. Implement the Solution class:
Array,Math,Randomized
Medium
57
452,217
257,703
747
642
The solution expects that we always use the original array to shuffle() else some of the test cases fail. (Credits; @snehasingh31)
null
385
Mini Parser
mini-parser
Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger. Each element is either an integer or a list whose elements may also be integers or other lists.
String,Stack,Depth-First Search
Medium
35.8
133,077
47,667
360
1,129
null
341,439,722
386
Lexicographical Numbers
lexicographical-numbers
Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order. You must write an algorithm that runs in O(n) time and uses O(1) extra space.
Depth-First Search,Trie
Medium
58.7
140,350
82,427
1,197
113
null
null
387
First Unique Character in a String
first-unique-character-in-a-string
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Hash Table,String,Queue,Counting
Easy
57
1,798,969
1,025,564
4,844
193
null
451
388
Longest Absolute File Path
longest-absolute-file-path
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1.ext and subdirectory subsubdir1. subdir2 contains a subdirectory subsubdir2, which contains a file file2.ext. In text form, it looks like this (with ⟶ representing the tab character): If we were to write this representation in code, it will look like this: "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext". Note that the '\n' and '\t' are the new-line and tab characters. Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s. Using the above example, the absolute path to file2.ext is "dir/subdir2/subsubdir2/file2.ext". Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension, where name and extension consist of letters, digits, and/or spaces. Given a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0.
String,Stack,Depth-First Search
Medium
45.8
278,482
127,581
979
2,122
null
null
389
Find the Difference
find-the-difference
You are given two strings s and t. String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t.
Hash Table,String,Bit Manipulation,Sorting
Easy
60.5
635,903
384,938
2,700
381
null
136
390
Elimination Game
elimination-game
You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr: Given the integer n, return the last number that remains in arr.
Math
Medium
46.4
96,444
44,724
750
497
null
null
391
Perfect Rectangle
perfect-rectangle
Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi). Return true if all the rectangles together form an exact cover of a rectangular region.
Array,Line Sweep
Hard
32.1
106,171
34,050
592
97
null
null
392
Is Subsequence
is-subsequence
Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).
Two Pointers,String,Dynamic Programming
Easy
51
891,195
454,214
4,635
285
null
808,1051
393
UTF-8 Validation
utf-8-validation
Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters). A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: This is how the UTF-8 encoding would work: x denotes a bit in the binary form of a byte that may be either 0 or 1. Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.
Array,Bit Manipulation
Medium
39.2
171,170
67,031
365
1,508
All you have to do is follow the rules. For a given integer, obtain its binary representation in the string form and work with the rules given in the problem. An integer can either represent the start of a UTF-8 character, or a part of an existing UTF-8 character. There are two separate rules for these two scenarios in the problem. If an integer is a part of an existing UTF-8 character, simply check the 2 most significant bits of in the binary representation string. They should be 10. If the integer represents the start of a UTF-8 character, then the first few bits would be 1 followed by a 0. The number of initial bits (most significant) bits determines the length of the UTF-8 character. Note: The array can contain multiple valid UTF-8 characters. String manipulation will work fine here. But, it is too slow. Can we instead use bit manipulation to do the validations instead of string manipulations? We can use bit masking to check how many initial bits are set for a given number. We only need to work with the 8 least significant bits as mentioned in the problem. mask = 1 << 7 while mask & num: n_bytes += 1 mask = mask >> 1 Can you use bit-masking to perform the second validation as well i.e. checking if the most significant bit is 1 and the second most significant bit a 0? To check if the most significant bit is a 1 and the second most significant bit is a 0, we can make use of the following two masks. mask1 = 1 << 7 mask2 = 1 << 6 if not (num & mask1 and not (num & mask2)): return False
null
394
Decode String
decode-string
Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4].
String,Stack,Recursion
Medium
56.2
852,371
479,436
7,950
340
null
471,726,1076
395
Longest Substring with At Least K Repeating Characters
longest-substring-with-at-least-k-repeating-characters
Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.
Hash Table,String,Divide and Conquer,Sliding Window
Medium
44.5
345,377
153,849
3,853
321
null
2140,2209
396
Rotate Function
rotate-function
You are given an integer array nums of length n. Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow: Return the maximum value of F(0), F(1), ..., F(n-1). The test cases are generated so that the answer fits in a 32-bit integer.
Array,Math,Dynamic Programming
Medium
39.2
154,081
60,330
817
208
null
null
397
Integer Replacement
integer-replacement
Given a positive integer n, you can apply one of the following operations: Return the minimum number of operations needed for n to become 1.
Dynamic Programming,Greedy,Bit Manipulation,Memoization
Medium
34.7
232,928
80,756
811
421
null
null
398
Random Pick Index
random-pick-index
Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class:
Hash Table,Math,Reservoir Sampling,Randomized
Medium
63.6
262,892
167,330
955
1,028
null
382,894,912
399
Evaluate Division
evaluate-division
You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable. You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?. Return the answers to all queries. If a single answer cannot be determined, return -1.0. Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
Medium
57.1
432,353
246,732
4,916
419
Do you recognize this as a graph problem?
null
400
Nth Digit
nth-digit
Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].
Math,Binary Search
Medium
33.5
223,742
74,920
656
1,499
null
null