The Top 50 LeetCode Problems That Cover Every Interview Pattern

May 29, 202614 min read
dsaalgorithmsinterview-prepleetcode
The Top 50 LeetCode Problems That Cover Every Interview Pattern
TL;DR
  • Pattern identification over application: mediums hide the signal while easy problems announce it, making them the highest-ROI prep for real interviews
  • Two pointers, sliding window, and prefix sum cover the majority of subarray and string problems; master these three families before anything else
  • The BST validation mistake is checking only the parent node; pass a (min, max) range down through recursion to enforce the full ancestor invariant
  • 0/1 knapsack requires backward iteration over capacity; forward iteration silently produces unbounded knapsack and gives wrong answers on LC 416
  • Binary search on the answer applies when the feasibility check is easy but computing the answer directly is not, as in LC 875 and LC 1011
  • Kahn's cycle check: if the processed node count equals total node count after BFS, the graph is acyclic
  • The mistake log beats problem count: write down which pattern signal you missed, not just that you looked up the solution

You have limited time and too many problems. Every list says something different. 150 problems. 300. "Just grind until you feel ready." None of that answers the real question: which problems actually teach you something new?

This list is the top 50 LeetCode problems for coding interviews, organized into 20 pattern families. Every problem earns its spot because it is either the cleanest introduction to a pattern or contains a wrinkle you will see again in disguise. Finish these and you will have a real framework, not just a problem count.

Each entry shows the pattern signal and the single insight that makes the problem worth solving.

Why Not 300? Why Not Blind 75?

Real interviews run about 60% medium difficulty at Amazon, Meta, and Google. Hards should not drive your prep schedule. Mediums are where pattern identification lives: easy problems announce their pattern, hard problems demand a flash of insight you either have or don't.

Fifty problems covers every major pattern without repeating territory. More problems does not mean better preparation unless each one adds coverage. Solving variation 47 of sliding window does not teach you anything variation 4 didn't.

Google search autocomplete showing "how to study data structures and algorithms in one day" with suggestions like "...day course" and "...day pdf"

The plan. Every time.

Solve One Family at a Time

Work through one pattern family before moving to the next. Spend 25 minutes on each problem before looking at a solution. After finishing a family, write down in your own words what the signal is and what the template looks like. That active reconstruction is what builds retention, not re-reading solutions.


Two Pointers

The signal: sorted input, minimize or maximize over a pair, or eliminate one option per step.

#ProblemWhat it teaches
167Two Sum IIThe canonical converging pointer template. Too-small sum moves left right; too-large moves right left. Every other two-pointer problem is a variation.
153SumSort first, fix one element, run a two-pointer scan on the remainder. The non-obvious part is skipping duplicates at both the outer loop and the inner scan.
11Container With Most WaterMoving the shorter pointer is the only non-losing move. No better answer exists in the discarded region. This is the exchange argument in action.

Sliding Window

The signal: contiguous subarray or substring, optimize window size, shrink when a constraint is violated.

#ProblemWhat it teaches
3Longest Substring Without Repeating CharactersVariable window with a set. Expand right, shrink from left when a duplicate appears. This is the base template every other sliding window problem inherits.
424Longest Repeating Character ReplacementTrack the most frequent character count. If window_size - max_count > k, shrink. You never need to decrease max_count across the whole run. That safe approximation is the insight.
209Minimum Size Subarray SumMinimum valid window. Shrink until the constraint breaks, record the size right before it does.
438Find All Anagrams in a StringFixed-size window. Compare frequency arrays at each step. This distinguishes fixed-size from variable-size windows at the implementation level.

The sliding window pattern covers more interview ground than almost any other technique.

Prefix Sum + Hash Map

The signal: subarray count or existence, sum equals target.

#ProblemWhat it teaches
560Subarray Sum Equals Kprefix_sum - k found in the hash map means a valid subarray ends here. One pass, O(n). This is the pattern behind half of all subarray problems.
525Contiguous ArrayRemap 0 to -1. "Equal counts of 0s and 1s" becomes "subarray sum equals 0." Same mechanism as 560, different setup.

Hash Map and Set

The signal: group, count, or deduplicate by a derived key.

#ProblemWhat it teaches
49Group AnagramsHash by a computed property (sorted characters or frequency tuple), not the raw string. Generalizes to any grouping problem.
128Longest Consecutive SequenceOnly start a sequence at numbers with no left neighbor in the set. Avoids the O(n²) naive scan without sorting.
347Top K Frequent ElementsBucket sort by frequency gives O(n) without a heap. The lesson: when to reach for bucket sort instead of a priority queue.

Binary Search

The signal: sorted structure, find a target or a boundary in O(log n).

#ProblemWhat it teaches
74Search a 2D MatrixTreat the matrix as a flat array. row = mid // cols, col = mid % cols. Binary search collapses 2D to 1D.
33Search in Rotated Sorted ArrayOne half is always fully sorted. Determine which half, check if the target falls inside it, discard the other. The condition ordering is the entire problem.
153Find Minimum in Rotated Sorted ArrayIf arr[mid] > arr[right], the minimum is in the right half. Teaches shrinking toward a property at a boundary rather than toward a target.

Binary Search on the Answer

The signal: "minimize the maximum" or "maximize the minimum"; the feasibility check is easy even when computing the answer directly is not.

#ProblemWhat it teaches
875Koko Eating BananasBinary search the answer space (eating speed 1 to max pile), not the array. The feasibility check is a greedy scan. Complete template in one problem.
1011Capacity to Ship PackagesSame pattern, different framing. lo = max(weights), hi = sum(weights). Seeing both back to back cements the template.

Linked List

The signal: pointer manipulation, in-place modification, no random access.

#ProblemWhat it teaches
19Remove Nth Node from EndAdvance fast pointer n+1 steps first. When fast reaches null, slow is one node before the target. A dummy head node makes head deletion uniform.
143Reorder ListThree sub-problems chained: find middle, reverse second half, merge alternately. Tests whether you can sequence linked-list primitives cleanly.
148Sort ListMerge sort on a linked list. Same find-middle plus merge, but recursed. O(n log n) sort with O(log n) stack frames, not O(n).

Tree DFS

The signal: subtree property, path-based condition, tree construction, or validation.

#ProblemWhat it teaches
98Validate Binary Search TreeThe BST property is about all ancestors, not just the parent. Pass a (min, max) range down through recursion. Checking only the parent is the classic wrong answer.
105Construct Binary Tree from Preorder and InorderThe preorder root splits inorder into left and right subtrees. Use a hash map for O(1) inorder index lookup.
236Lowest Common AncestorPostorder: if both subtrees return non-null, the current node is the LCA. If one returns null, propagate the non-null result upward.
437Path Sum IIIPrefix sum on a tree. Store running sums in a hash map during DFS; remove them on backtrack. LC 560 mapped onto tree paths.

Tree BFS

The signal: level-by-level processing.

#ProblemWhat it teaches
102Binary Tree Level Order TraversalSnapshot the queue length before processing each level (for _ in range(len(queue))). Everything enqueued during that loop belongs to the current level.
199Binary Tree Right Side ViewBFS then take the last node at each level. Or DFS with depth tracking, overwriting the result at each depth. Two valid approaches, one problem worth knowing both.

Graph BFS

The signal: shortest path in an unweighted graph, multi-source propagation, connected regions.

#ProblemWhat it teaches
200Number of IslandsThe outer loop starting a new BFS from each unvisited cell is not optional. Some islands are disconnected from the rest.
994Rotting OrangesMulti-source BFS: seed all rotten cells at time zero, then propagate. The answer is when the last fresh cell is reached, not when the first branch terminates.

Graph DFS

The signal: reachability, cycle detection, connected component properties.

#ProblemWhat it teaches
417Pacific Atlantic Water FlowReverse the flow direction: DFS inward from each ocean's border instead of outward from each cell. Then intersect the two reachable sets. Reversing the problem is the whole move.
133Clone GraphDFS with a {original: clone} hash map. Check whether a neighbor is already cloned before recursing; without that check you loop forever on cycles.

Topological Sort

The signal: directed graph, dependency ordering, cycle detection.

#ProblemWhat it teaches
207Course ScheduleKahn's algorithm: process nodes with in-degree zero. If processed count equals total node count, no cycle exists. That counting check is the cycle detector.
210Course Schedule IISame algorithm, but record the processing order as output.

Union-Find

The signal: dynamic connectivity, grouping by equivalence, same-component queries.

#ProblemWhat it teaches
684Redundant ConnectionAdd edges one at a time; if find(u) == find(v) before the union, that edge creates a cycle. Union-Find checks connectivity, not cycles directly.
547Number of ProvincesConnected components via Union-Find. Count how many roots point to themselves at the end.

Heap and Priority Queue

The signal: repeated minimum or maximum extraction, top-K elements, scheduling.

#ProblemWhat it teaches
215Kth Largest ElementMax-heap of size n (extract k times), min-heap of size k (evict when oversized), or quickselect for O(n) average. Know all three and when each applies.
973K Closest Points to OriginMax-heap of size K. When a new point is closer than the current max, swap it in. The heap maintains the K smallest distances seen so far.

Greedy

The signal: local choice is provably globally optimal; there is an exchange argument you can articulate.

#ProblemWhat it teaches
55Jump GameTrack the farthest reachable index as you scan. If the current index exceeds that bound, return false. One pass, O(1) space.
45Jump Game IIGreedy BFS. Track the boundary of the current "level" and the farthest reachable from within it. Increment jump count when you cross the boundary.

Intervals

The signal: overlapping ranges, merging, counting simultaneous events.

#ProblemWhat it teaches
56Merge IntervalsSort by start. Merge into the last interval when curr.start <= last.end. The max() on the end time is non-optional. Without it, a contained interval silently truncates the merged result.
435Non-overlapping IntervalsSort by end time, not start. Greedily keep the interval that ends earliest. This is the activity selection problem.

Monotonic Stack

The signal: next or previous greater or smaller element, spans, O(n) required.

#ProblemWhat it teaches
739Daily TemperaturesDecreasing stack. When a warmer day appears, pop all cooler days and record the distance. The stack holds indices, not temperatures.
853Car FleetSort by position descending. Compare arrival times: if a car behind arrives no sooner than the car ahead, they form one fleet. A monotonic stack counts distinct arrival times.

1D Dynamic Programming

The signal: optimal substructure plus overlapping subproblems on a sequence.

DP problems are where people stare at a blank editor for 20 minutes and then read the solution and say "oh, obviously." The only cure is reps. These four problems cover the main DP shapes.

My algorithms knowledge (a small bulldozer) being blocked by a huge cargo ship labeled "Coding interview" stuck in the Suez Canal

This is what 1D DP feels like the first time. The ship moves eventually.

#ProblemWhat it teaches
322Coin ChangeUnbounded knapsack. dp[i] = min(dp[i - c] + 1) for each coin c. Initialize to infinity; base case dp[0] = 0.
300Longest Increasing SubsequenceO(n²) DP or O(n log n) via patience sorting with binary search on a "piles" array. Worth knowing both approaches and when each applies.
139Word Breakdp[i] = can you form s[:i]? For each i, check all j where dp[j] is true and s[j:i] is in the dictionary.
416Partition Equal Subset Sum0/1 knapsack. Iterate capacity from high to low to prevent reusing an item within a single pass. Forward iteration gives you unbounded knapsack.

2D Dynamic Programming

The signal: two sequences or a grid; the state needs two parameters.

#ProblemWhat it teaches
62Unique Pathsdp[r][c] = dp[r-1][c] + dp[r][c-1]. Space-optimize to a single row by updating left to right.
1143Longest Common SubsequenceOn a match, dp[i][j] = dp[i-1][j-1] + 1. On no match, dp[i][j] = max(dp[i-1][j], dp[i][j-1]). Reduce to two rows with rolling arrays.

Backtracking

The signal: enumerate all valid configurations, prune branches early, undo state after each recursive call.

#ProblemWhat it teaches
39Combination SumPass a start index to avoid revisiting earlier elements. The same number can be reused, so recurse with start unchanged (not start + 1).
79Word SearchMark a cell with a sentinel before recursing; restore the original value when returning. Four-directional DFS with in-place visited tracking.

What to Do After You Finish

Solving a problem once is not enough. For each problem you got right, write down the pattern signal that tipped you off. For each problem you looked up or got wrong, write down specifically what you missed. That mistake log is more valuable than any problem count.

Once you can identify the pattern within the first two minutes of reading a new problem, you are ready. Pattern identification is the hard part. Application follows.

To test your pattern recognition under real interview conditions, SpaceComplexity runs voice-based mock interviews with rubric feedback on communication, pattern identification, code quality, and testing. It is a fast way to find out whether you have internalized these patterns or just memorized the solutions.

Further Reading