LeetCode patterns: the 10 that cover most coding interviews
Most coding interview problems reuse a small set of ideas. Learn the LeetCode patterns below, how to recognize each one and one short Python example, and your coding interview preparation gets faster and less random.
Why study LeetCode patterns instead of random problems?
A problem list is long and random practice leaves gaps. Patterns give you a small map: when you see a sorted array, a window of items or a grid, you know which tool to reach for first. In the interview you then spend your time on the details, edge cases and talking through your choices. For the live side of the round, see live coding interview tips.
How to prepare for coding interview rounds with patterns
Here is a simple loop for coding interview preparation:
- Read the pattern section and its example.
- Solve the example from a blank editor without looking.
- Solve 3 to 5 more problems of that pattern, timing each at 30 to 45 minutes.
- Write one line for each: the clue that gave away the pattern.
- Revisit the problems a week later. Redo the ones you missed.
1. Two pointers
Clues: sorted array, pair or triple that meets a condition, palindrome, in-place changes. Idea: two indexes move toward each other, or one chases the other, so you skip a nested loop.
Example: in a sorted list, find two numbers that add up to a target (0-indexed result).
def two_sum_sorted(nums, target):
l, r = 0, len(nums) - 1
while l < r:
s = nums[l] + nums[r]
if s == target:
return [l, r]
if s < target:
l += 1
else:
r -= 1
return []
Time O(n), space O(1). If the sum is too small, only a larger left value can help, so move left.
2. Sliding window
Clues: longest or shortest substring or subarray with a rule, "at most k". Idea: keep a window, grow the right side, shrink the left side when the rule breaks.
Example: length of the longest substring without repeating characters.
def length_of_longest_substring(s):
last = {}
start = best = 0
for i, ch in enumerate(s):
if ch in last and last[ch] >= start:
start = last[ch] + 1
last[ch] = i
best = max(best, i - start + 1)
return best
Time O(n). Check: "abba" gives 2. The last[ch] >= start test stops an old position outside the window from moving the start backward.
3. Hash map
Clues: "have I seen this before", counting, grouping, find a complement. Idea: trade memory for speed with O(1) lookups.
Example: two sum on an unsorted list.
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
need = target - x
if need in seen:
return [seen[need], i]
seen[x] = i
return []
Time O(n), space O(n). Checking before storing means one number is never paired with itself.
4. Binary search
Clues: sorted input, "minimum value that works", O(log n) hinted. Idea: halve the search space each step. It also works on answers, not only arrays, when a yes/no test flips once.
Example: the index where a target is, or would be inserted, in a sorted list.
def search_insert(nums, target):
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
Check: [1,3,5,6] with 5 gives 2, with 7 gives 4, with 0 gives 0. Using hi = len(nums) and lo < hi avoids off-by-one errors.
5. BFS and DFS
Clues: trees, graphs, grids, connected regions. BFS (queue) for shortest steps or level by level. DFS (recursion or stack) to explore everything, count regions or try paths.
BFS example: binary tree level order.
from collections import deque
def level_order(root):
if not root:
return []
out, q = [], deque([root])
while q:
level = []
for _ in range(len(q)):
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
out.append(level)
return out
DFS example: count islands in a grid of "1" (land) and "0" (water).
def num_islands(grid):
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
def dfs(r, c):
if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != "1":
return
grid[r][c] = "0"
dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1)
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1":
count += 1
dfs(r, c)
return count
Time O(rows x cols). It changes the input, which you should say aloud, and recursion can run deep on big grids. Mention an iterative version as an alternative.
6. Dynamic programming
Clues: "minimum number of", "how many ways", choices that repeat the same sub-problems. Idea: define what the answer for a smaller input means, write the rule that builds a bigger one from it, and store results.
Example: fewest coins to make an amount, or -1.
def coin_change(coins, amount):
INF = amount + 1
dp = [0] + [INF] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a:
dp[a] = min(dp[a], dp[a - c] + 1)
return dp[amount] if dp[amount] != INF else -1
Check: coins [1,2,5], amount 11 gives 3; amount 0 gives 0; coins [2], amount 3 gives -1. Time O(amount x coins).
7. Heap
Clues: "top k", "k-th largest", merge sorted lists, always need the current smallest or largest. Idea: a heap gives min or max in O(log n).
Example: the k most frequent numbers.
import heapq
from collections import Counter
def top_k_frequent(nums, k):
counts = Counter(nums)
return heapq.nlargest(k, counts.keys(), key=counts.get)
Check: [1,1,1,2,2,3] with k=2 gives [1, 2]. Time about O(n log k). Be ready to explain what nlargest does inside.
8. Backtracking
Clues: "all combinations", "all permutations", "all subsets", puzzles with choices. Idea: choose, explore, undo.
Example: all subsets of a list of distinct numbers.
def subsets(nums):
res, path = [], []
def backtrack(start):
res.append(path[:])
for i in range(start, len(nums)):
path.append(nums[i])
backtrack(i + 1)
path.pop()
backtrack(0)
return res
Check: [1,2,3] gives 8 subsets, including the empty one. Copying path[:] matters, since path keeps changing.
9. Intervals
Clues: meetings, ranges, schedules, overlaps. Idea: sort by start time, then sweep and merge.
Example: merge overlapping intervals.
def merge(intervals):
intervals.sort(key=lambda x: x[0])
merged = []
for s, e in intervals:
if merged and s <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], e)
else:
merged.append([s, e])
return merged
Check: [[1,3],[2,6],[8,10]] gives [[1,6],[8,10]]. Ask whether touching ranges such as [1,2] and [2,3] should merge. This code merges them.
10. Stack
Clues: matching brackets, nested structure, "next greater element", undo. Idea: last in, first out.
Example: valid parentheses.
def is_valid(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return not stack
Check: "([])" is true, "(]" is false, "((" is false because the stack is not empty at the end.
Also keep your CV or resume handy: some rounds start with questions about projects on it.
LeetCode patterns cheat sheet: one page to review
Print this table or copy it into your notes. It is a one-page checklist of the 10 patterns above: the clue, the core move and the usual cost. Review it the night before, and redo one problem per row.
| Pattern | Clue in the problem | Core move | Usual cost |
|---|---|---|---|
| Two pointers | Sorted array, pair, palindrome | Move two indexes inward | O(n) time, O(1) space |
| Sliding window | Longest or shortest subarray with a rule | Grow right, shrink left | O(n) |
| Hash map | Seen before, count, complement | Store as you scan | O(n) time, O(n) space |
| Binary search | Sorted, or a yes/no test that flips once | Halve the range | O(log n) |
| BFS and DFS | Tree, graph, grid | Queue for levels, recursion for regions | O(nodes + edges) |
| Dynamic programming | Fewest, number of ways, repeated sub-problems | Define a state, store results | States times choices |
| Heap | Top k, k-th largest, merge sorted | Keep the current best on top | O(n log k) |
| Backtracking | All subsets, permutations, combinations | Choose, explore, undo | Often exponential |
| Intervals | Meetings, ranges, overlaps | Sort by start, sweep | O(n log n) |
| Stack | Brackets, nesting, next greater | Last in, first out | O(n) |
Where do you find LeetCode patterns practice problems?
LeetCode is the usual place to submit solutions, and many sites and GitHub lists group problems by pattern. We did not compare them, so pick one list and follow the study order below. The examples here are a starting point and not a full problem set.
What does a pattern-first coding interview preparation week look like?
A sample week, if you can give an hour a day. It follows the study order below and is meant to be adapted.
- Monday and Tuesday: one new pattern. Solve the example here from a blank editor, then 2 more problems.
- Wednesday: 2 problems from the previous week's pattern, timed at 30 minutes each.
- Thursday: one new pattern, same routine as Monday.
- Friday: redo the problems you missed this week, and write the clue line for each.
- Weekend: one mock round out loud with a friend or a timer, explaining your approach before you code.
In what order should you study the patterns?
- Weeks 1 to 2: hash map, two pointers, sliding window, stack. These are the quickest to learn and show up often.
- Weeks 3 to 4: binary search, intervals, heap.
- Weeks 5 to 6: BFS and DFS on trees, graphs and grids.
- Weeks 7 to 8: backtracking, then dynamic programming, which needs the most practice.
Fit this around your own timeline. In every session, say your approach and its cost out loud, since interviewers listen to that. Add system design in the last weeks if your loop includes it: see the system design interview guide. More general advice is in technical interview tips.
A live option if you get stuck
Practice is what builds this skill, and the rules of the company and your employer come first. If those rules allow it, Hintly is a desktop app for Mac and Windows that can answer what is on your screen, with an overlay that is left out of screen shares. It is pre-launch, so you can join the waitlist. See the AI coding interview assistant page for details.
Questions
How many LeetCode problems should I solve?
There is no magic number. Solving a few problems per pattern, and being able to explain each one, is worth more than a large count. If you can redo a problem from a blank page a week later, you learned it.
Which language should I use?
Use the one you know best that the company allows. Python is short to write, which helps in a 45 minute round. The examples here are Python 3.
Should I memorize solutions?
No. Memorize the pattern, the signal that tells you to use it and the shape of the code. Then write it fresh each time.
How long should coding interview preparation take?
It depends on where you start. Many people plan 6 to 8 weeks of steady practice. If your gap is large, plan longer. The study order below can stretch or shrink to fit.
What if I do not recognize the pattern in the interview?
Say so, then solve a small example by hand and look for repeated work. Start with the brute force, state its cost, and look for what you can reuse. Interviewers value the process.