N coding interview cheat sheet: how to spot the 5 patterns, with a template for each - Netscape _ □ ×
Back Forward Home Reload Guides Sign
URL: http://www.nicnonac.com/guides/coding-interview-patterns/
☷ coding interview cheat sheet: how to spot the 5 patterns, with a template for each - nicnonac guides _□×

← back to guides

coding interview cheat sheet: how to spot the 5 patterns, with a template for each

Stacks · 9 min read · posted Nov 29, 2026, 6:19 am

Most coding interview questions are one of a small set of patterns with a different story on top. Once you can tell which pattern a question is asking for, most of the code is a template you already know.

This is the cheat sheet from the reel. It covers the five patterns in it. For each one you get the signals that give it away in a question, the template in Python, the mistake that usually breaks it, and problems to practise on, easiest first.

These are five of the twelve patterns my own notes are organised by. I spent about three months preparing for my Atlassian internship interviews, and the notes ended up sorted by pattern instead of by problem. None of the problems below come from an interview. They're all public on LeetCode.

the quick lookup

Read the question and look for these words before you write anything.

the question says try
sorted array, find a pair, palindrome, "in place" two pointers
longest or shortest substring or subarray, "contiguous" sliding window
sorted input, O(log n), "the smallest X that still works" binary search
tree, grid, graph, islands, "fewest steps" BFS or DFS
"how many ways", "minimum cost", "can you make" dynamic programming

1. two pointers

Spot it. The input is sorted, or you're allowed to sort it. The question wants a pair or a triplet that hits a target, or a palindrome check. An array you have to change in place with no extra memory is the other giveaway.

The idea. Two indexes walk the array, and each step throws one element away for good. That turns a loop inside a loop, O(n²), into a single pass, O(n).

Template: one pointer at each end.

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      # need a bigger sum
        else:
            r -= 1      # need a smaller sum
    return []

Because the array is sorted, moving l right can only make the sum bigger, and moving r left can only make it smaller. This is the one in the reel: the target is 14 and the pointers stop on 6 and 8.

Second shape: slow and fast. Both pointers start on the left. The fast one reads and the slow one writes.

def remove_duplicates(nums):
    if not nums:
        return 0
    write = 1
    for read in range(1, len(nums)):
        if nums[read] != nums[read - 1]:
            nums[write] = nums[read]
            write += 1
    return write

What breaks it. Running the two-ends version on an unsorted array. The whole argument depends on the order. The other one is writing while l <= r when you need two different elements, because at l == r you're adding a number to itself.

Practise.

2. sliding window

Spot it. The question asks for the longest or shortest contiguous run, meaning a substring or a subarray. There's a rule the run has to obey, like "no repeated characters" or "at most k of something".

The idea. Keep a window between two indexes. Grow it on the right, one element at a time. When it breaks the rule, shrink it from the left until it's legal again. Every element enters once and leaves at most once, so the whole thing is O(n).

Template.

def longest_without_repeats(s):
    seen = set()
    l = best = 0
    for r in range(len(s)):
        while s[r] in seen:       # the window would break the rule
            seen.remove(s[l])     # so shrink it from the left
            l += 1
        seen.add(s[r])
        best = max(best, r - l + 1)
    return best

In the reel this runs on "abcabdef" and ends on the window "cabdef", which is 6 letters.

Most sliding window answers are that loop with two things swapped: what you track about the window (a set here, a count per character or a running sum elsewhere) and what makes it invalid. For "shortest" questions the inner loop flips. While the window is still valid, record it and shrink.

What breaks it. The word "subsequence". A subsequence can skip elements, so a window can't describe it, and that's usually dynamic programming. Negative numbers break windows that track a sum too, because growing the window no longer always grows the sum. For those you want prefix sums and a hash map, as in 560. Subarray Sum Equals K.

Practise.

3. binary search

Spot it. Sorted input and the word "find". A statement that asks for O(log n). Then there's the one that doesn't look like a search at all: "what is the smallest speed or capacity that still works?" If a value works and every bigger value works too, you can binary search the answer itself.

Template: find an exact value.

def search(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

The one in the reel finds 56 among 13 numbers in four looks. Checking them one by one would take nine.

Template: find the first value that works.

def first_that_works(lo, hi, works):
    while lo < hi:
        mid = (lo + hi) // 2
        if works(mid):
            hi = mid          # mid works, look for something smaller
        else:
            lo = mid + 1      # mid fails, and so does everything below it
    return lo

Koko Eating Bananas is the usual example. The search runs over eating speeds, from 1 up to the biggest pile, and works checks whether she finishes in time.

def min_eating_speed(piles, h):
    def works(speed):
        hours = sum((p + speed - 1) // speed for p in piles)   # each pile, rounded up
        return hours <= h

    return first_that_works(1, max(piles), works)

What breaks it. Mixing the two templates. lo <= hi goes with mid + 1 and mid - 1. lo < hi goes with hi = mid. Cross them and you either skip the answer or loop forever.

Practise.

4. bfs and dfs

Spot it. The input is a tree, a grid or a graph, even when the question never calls it one. "Islands", "connected", "can you get from A to B" and "courses with prerequisites" are all graphs.

Then pick the order.

  • BFS when the question says shortest path or fewest steps, or wants the answer level by level. It visits everything one step away, then everything two steps away, so the first time it reaches something is the shortest way there.
  • DFS when you need to explore everything: count the groups, or check that a path exists. Tree questions like depth are DFS too, and it's usually less code.

They visit the same nodes in a different order, which is what the two trees in the reel show. BFS uses a queue. DFS uses a stack, and recursion gives you one for free.

Template: BFS, level by level.

from collections import deque

def level_order(root):
    if not root:
        return []
    levels, q = [], deque([root])
    while q:
        level = []
        for _ in range(len(q)):       # everything in the queue right now is one level
            node = q.popleft()
            level.append(node.val)
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
        levels.append(level)
    return levels

Template: DFS on a grid.

def num_islands(grid):
    rows, cols = len(grid), len(grid[0])

    def sink(r, c):
        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1":
            return
        grid[r][c] = "0"              # mark it visited
        sink(r + 1, c)
        sink(r - 1, c)
        sink(r, c + 1)
        sink(r, c - 1)

    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "1":
                count += 1
                sink(r, c)
    return count

What breaks it. Forgetting to mark things as visited. A tree has no way back up, but in a grid or a graph you'll walk in circles. In BFS, mark a cell when you add it to the queue, not when you take it out, or the same cell gets queued several times. Python also stops recursing at about 1,000 calls deep by default, so a DFS over a big grid may need its own stack, or BFS.

Practise.

5. dynamic programming

Spot it. "How many ways", "the minimum number of", "the most you can get", "is it possible to make". You make a choice at each step, and different choices lead back to the same smaller problem. If your brute force is a recursion that keeps solving the same inputs, it's DP.

The four questions. These sit at the top of my DP notes.

  1. State. What defines a subproblem? Usually a position, sometimes with what's left of a budget.
  2. Choice. What can you do from that state?
  3. Recurrence. How does the answer combine the answers to smaller states?
  4. Base case. Which states can you answer straight away?

Template: top down. Write the plain recursion, then add a cache so each state is solved once.

from functools import cache

@cache
def climb_stairs(n):
    if n <= 1:
        return 1
    return climb_stairs(n - 1) + climb_stairs(n - 2)

Without @cache that takes exponential time. With it, each n is worked out once.

Template: bottom up. Fill a table from the base cases forward. This is the grid from the reel, where every cell is the cell above plus the cell to its left.

def unique_paths(m, n):
    dp = [[1] * n for _ in range(m)]
    for r in range(1, m):
        for c in range(1, n):
            dp[r][c] = dp[r - 1][c] + dp[r][c - 1]
    return dp[-1][-1]

What breaks it. Starting with the table. Say the recurrence as a sentence first ("the ways to reach this cell are the ways to reach the one above plus the one on the left") and the code follows from it. The other trap is going greedy. With coins of 1, 3 and 4, the greedy way to make 6 is 4 + 1 + 1, which is three coins. The best is 3 + 3.

Practise.

how to practise with this

One pattern at a time, which is how I went through LeetCode. Do the easy problem with the template open, then the mediums with it closed. When you're stuck, go back to the quick lookup and ask which signal the question is giving you before you look at a solution.

In the interview, say the pattern out loud before you write code. "It's sorted and I need a pair, so I'm thinking two pointers" tells the interviewer more than silent typing does.

honest limitations

Five patterns isn't the full set. My notes have twelve, and the other seven are arrays and hashing, stack, linked list, trees, heap, backtracking and intervals. The full order is in my big tech internship prep guide.

A template gets you the structure. You still have to explain why it works and what it costs in time and memory, and that part only comes from doing the problems.

Harder questions combine patterns. 3Sum is a sort with two pointers inside a loop. Koko is a binary search with a loop inside it.

Everything here is Python. The patterns carry over to any language, but deque and @cache are Python's.

← all guides

Done nicnonac.com 56.6k