Coding Interview Patterns That Cover Most Questions

Most coding interview questions are variations on a small number of patterns. Learning to recognize the pattern from the problem statement is more useful than memorizing hundreds of solutions, because it works on problems you haven't seen before. This guide covers the patterns that come up most, how to spot each one, and what to practice.

Quick reference: from signal to pattern

If the problem mentions...Reach forTypical complexity
Find a pair, count occurrences, "have we seen this?"Hash mapsO(n)
A sorted array, pairs or triplets, palindromesTwo pointersO(n)
Longest or shortest contiguous subarray or substringSliding windowO(n)
Sum of a subarray, range sumsPrefix sumsO(n)
Sorted input, or "minimum value that works"Binary searchO(log n) per search
Cycle in a linked list, middle elementFast and slow pointersO(n)
Next greater or smaller element, matching bracketsMonotonic stackO(n)
Top k, kth largest, merge k sorted listsHeapsO(n log k)
Overlapping ranges, meetings, schedulesIntervalsO(n log n)
Trees: depth, paths, level by levelTree traversalO(n)
Grids, networks, shortest path in stepsGraph BFS and DFSO(V + E)
Dependencies, prerequisites, build orderTopological sortO(V + E)
Connected groups, merging setsUnion-findnearly O(1) per operation
All combinations, permutations, subsetsBacktrackingexponential
Count the ways, minimum cost, "is it possible?"Dynamic programmingvaries

The templates below are in Python, because it's concise and common in interviews. The practice problems use their names on LeetCode.

Arrays and strings

Hash maps

Signals: you need to find a pair, count frequencies, group items, or check whether you've seen something before.

Idea: trade memory for time. A hash map turns "search the array for X" from O(n) into O(1), which often turns an O(n²) brute force into O(n).

def two_sum(nums: list[int], target: int) -> list[int]:
    seen = {}  # value -> index
    for i, x in enumerate(nums):
        if target - x in seen:
            return [seen[target - x], i]
        seen[x] = i
    return []

Practice: Two Sum, Group Anagrams, Longest Consecutive Sequence.

Two pointers

Signals: the input is sorted (or can be sorted), and you're looking for a pair or triplet, comparing from both ends, or checking a palindrome.

Idea: start one pointer at each end and move one inward based on a comparison, so each step rules out a whole set of candidates.

def two_sum_sorted(nums: list[int], target: int) -> tuple[int, int] | None:
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return left, right
        if total < target:
            left += 1   # need a bigger sum
        else:
            right -= 1  # need a smaller sum
    return None

Practice: Two Sum II, 3Sum, Container With Most Water, Valid Palindrome.

Sliding window

Signals: "longest," "shortest" or "number of" contiguous subarrays or substrings that satisfy a condition.

Idea: grow the window by moving the right edge; when the window becomes invalid, shrink it from the left. Each element enters and leaves the window at most once, so it's O(n).

def longest_unique_substring(s: str) -> int:
    last_seen = {}  # character -> last index
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1  # jump past the duplicate
        last_seen[ch] = right
        best = max(best, right - left + 1)
    return best

Practice: Longest Substring Without Repeating Characters, Longest Repeating Character Replacement, Minimum Window Substring.

Prefix sums

Signals: sums over subarrays or ranges, especially many range queries, or "subarrays that sum to k."

Idea: the sum of any subarray is the difference between two running totals. Store running totals in an array, or in a hash map when you need to count matches.

def count_subarrays_with_sum(nums: list[int], k: int) -> int:
    seen = {0: 1}  # running total -> how many times it has occurred
    total = count = 0
    for x in nums:
        total += x
        count += seen.get(total - k, 0)
        seen[total] = seen.get(total, 0) + 1
    return count

Sliding window doesn't work here when the array can contain negative numbers, because shrinking the window no longer reliably lowers the sum. That's the signal to switch to prefix sums.

Practice: Subarray Sum Equals K, Range Sum Query - Immutable, Product of Array Except Self.

Searching

Signals: sorted input — or a question of the form "what's the smallest (or largest) value that works?" where, if a value works, every larger value works too.

Idea: halve the search space each step. The second form, often called binary search on the answer, is the one candidates miss: you binary search over possible answers, not over the input.

def smallest_valid(lo: int, hi: int, ok) -> int:
    """Smallest x in [lo, hi] where ok(x) is True. ok must be monotonic
    (False, ..., False, True, ..., True) and ok(hi) must be True."""
    while lo < hi:
        mid = (lo + hi) // 2
        if ok(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo


# Koko Eating Bananas: the slowest eating speed that finishes within h hours
def min_eating_speed(piles: list[int], h: int) -> int:
    hours_at = lambda k: sum((p + k - 1) // k for p in piles)  # ceiling division
    return smallest_valid(1, max(piles), lambda k: hours_at(k) <= h)

Practice: Binary Search, Search in Rotated Sorted Array, Koko Eating Bananas, Find Minimum in Rotated Sorted Array.

Linked lists

Fast and slow pointers

Signals: detect a cycle, find the middle of a list, or find where a cycle begins.

Idea: move one pointer one step at a time and another two steps. If there's a cycle, they meet; if not, the fast pointer reaches the end, and the slow one is at the middle.

def has_cycle(head) -> bool:
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

Practice: Linked List Cycle, Middle of the Linked List, Linked List Cycle II, Find the Duplicate Number.

Stacks, heaps and intervals

Monotonic stack

Signals: "next greater element," "how many days until a warmer day," spans, or the largest rectangle in a histogram. Plain stacks also cover matching brackets and undo-style problems.

Idea: keep a stack whose values are always increasing or decreasing. When a new element breaks the order, pop everything it resolves.

def days_until_warmer(temps: list[int]) -> list[int]:
    answer = [0] * len(temps)
    stack = []  # indices still waiting for a warmer day (temperatures decreasing)
    for i, t in enumerate(temps):
        while stack and temps[stack[-1]] < t:
            j = stack.pop()
            answer[j] = i - j
        stack.append(i)
    return answer

Practice: Valid Parentheses, Daily Temperatures, Next Greater Element I, Largest Rectangle in Histogram.

Heaps

Signals: "top k," "kth largest," "k closest," merging k sorted lists, or repeatedly taking the smallest or largest remaining item.

Idea: a heap gives you the minimum (or maximum) in O(1) and inserts in O(log n). For top k, keeping a heap of size k makes it O(n log k) instead of sorting everything in O(n log n).

import heapq
from collections import Counter

def top_k_frequent(nums: list[int], k: int) -> list[int]:
    counts = Counter(nums)
    return heapq.nlargest(k, counts, key=counts.get)

Practice: Kth Largest Element in an Array, Top K Frequent Elements, K Closest Points to Origin, Merge k Sorted Lists.

Intervals

Signals: ranges with a start and end — meetings, bookings, schedules — and words like "overlap," "merge" or "minimum rooms."

Idea: sort by start time, then sweep once, comparing each interval with the last one you kept.

def merge(intervals: list[list[int]]) -> list[list[int]]:
    merged = []
    for start, end in sorted(intervals):
        if merged and start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)  # overlaps: extend
        else:
            merged.append([start, end])
    return merged

Practice: Merge Intervals, Insert Interval, Non-overlapping Intervals.

Trees and graphs

Tree traversal

Signals: anything on a binary tree — depth, paths, validation, lowest common ancestor, or processing level by level.

Idea: most tree problems are a recursive DFS that combines answers from the left and right subtrees. Use BFS with a queue when the problem says "level by level."

def max_depth(root) -> int:
    if root is None:
        return 0
    return 1 + max(max_depth(root.left), max_depth(root.right))

Practice: Maximum Depth of Binary Tree, Binary Tree Level Order Traversal, Validate Binary Search Tree, Lowest Common Ancestor of a Binary Tree.

Graph BFS and DFS

Signals: grids, networks, "connected," "islands," "spread," or the fewest steps to reach something. Many problems are graphs in disguise — a word ladder, a lock with dials, a grid of oranges.

Idea: BFS explores in layers, so it finds the shortest path in an unweighted graph. DFS goes deep first and is simpler for counting components or exploring everything. Either way, mark nodes as visited when you add them, so nothing is processed twice.

from collections import deque

def count_islands(grid: list[list[str]]) -> int:
    if not grid:
        return 0
    rows, cols = len(grid), len(grid[0])
    seen = set()
    islands = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != "1" or (r, c) in seen:
                continue
            islands += 1
            seen.add((r, c))
            queue = deque([(r, c)])
            while queue:
                cr, cc = queue.popleft()
                for nr, nc in ((cr + 1, cc), (cr - 1, cc), (cr, cc + 1), (cr, cc - 1)):
                    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1" and (nr, nc) not in seen:
                        seen.add((nr, nc))
                        queue.append((nr, nc))
    return islands

Practice: Number of Islands, Rotting Oranges, Clone Graph, Word Ladder.

Topological sort

Signals: dependencies or prerequisites, build or course order, or "is there a valid ordering?"

Idea: repeatedly take a node with no remaining prerequisites (in-degree zero) and remove its outgoing edges. If you can't process every node, there's a cycle.

from collections import deque

def can_finish(num_courses: int, prerequisites: list[list[int]]) -> bool:
    graph = [[] for _ in range(num_courses)]
    indegree = [0] * num_courses
    for course, prereq in prerequisites:
        graph[prereq].append(course)
        indegree[course] += 1
    queue = deque(i for i in range(num_courses) if indegree[i] == 0)
    taken = 0
    while queue:
        node = queue.popleft()
        taken += 1
        for nxt in graph[node]:
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                queue.append(nxt)
    return taken == num_courses

Practice: Course Schedule, Course Schedule II, Alien Dictionary.

Union-find

Signals: grouping items into connected sets as connections arrive, counting components, or detecting a cycle in an undirected graph.

Idea: each set has a representative. find follows parent links to it, and union links two representatives. Path compression keeps the trees flat, so operations are nearly constant time in practice.

class UnionFind:
    def __init__(self, n: int):
        self.parent = list(range(n))

    def find(self, x: int) -> int:
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]  # path halving
            x = self.parent[x]
        return x

    def union(self, a: int, b: int) -> bool:
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False  # already connected: this edge would form a cycle
        self.parent[ra] = rb
        return True

Adding union by rank or size gives the guaranteed near-constant bound; mention it even if you don't code it.

Practice: Redundant Connection, Number of Provinces, Accounts Merge.

Recursion and dynamic programming

Backtracking

Signals: "all" combinations, permutations, subsets, or arrangements; constraint puzzles like N-Queens or Sudoku.

Idea: build a candidate one choice at a time, recurse, then undo the choice. Prune branches that can't lead to a valid answer as early as possible.

def subsets(nums: list[int]) -> list[list[int]]:
    result, path = [], []

    def backtrack(start: int) -> None:
        result.append(path[:])
        for i in range(start, len(nums)):
            path.append(nums[i])  # choose
            backtrack(i + 1)      # explore
            path.pop()            # un-choose

    backtrack(0)
    return result

Practice: Subsets, Permutations, Combination Sum, Word Search.

Dynamic programming

Signals: "number of ways," "minimum or maximum cost," "longest," or "is it possible," where the answer for a big input depends on answers for smaller inputs — and the same smaller inputs come up again and again.

Idea: define what a subproblem means in one sentence, write the recurrence, then fill a table from the smallest subproblems up (or memoize a recursive solution). Getting that one-sentence definition right is most of the work.

def min_coins(coins: list[int], amount: int) -> int:
    INF = float("inf")
    best = [0] + [INF] * amount  # best[a] = fewest coins that sum to a
    for a in range(1, amount + 1):
        for coin in coins:
            if coin <= a:
                best[a] = min(best[a], best[a - coin] + 1)
    return best[amount] if best[amount] != INF else -1

Practice: Climbing Stairs, House Robber, Coin Change, Longest Increasing Subsequence, Longest Common Subsequence.

Less common, still worth knowing

  • Tries for prefix lookups and word games: Implement Trie, Word Search II.
  • Greedy choices when a local best choice can be proven to lead to the overall best: Jump Game, Gas Station.
  • Bit manipulation for problems about binary representations or finding a unique element: Single Number, Counting Bits.
  • Dijkstra's algorithm for shortest paths with weighted edges: Network Delay Time.

How to study patterns

  1. Learn one pattern at a time. Read the idea, then write the template from memory until you can do it without looking.
  2. Solve three to five problems per pattern, from easy to medium. Solve them out loud, with a timer.
  3. Switch to mixed practice. Once you know the patterns, practice on problems where you don't know the pattern in advance. Recognizing which pattern applies is the actual interview skill.
  4. Revisit after a few days. Re-solve problems you struggled with. If you can't, you memorized a solution rather than learning the pattern.
  5. Say the signal out loud. In an interview, "this asks for the longest substring with a condition, so I'm thinking sliding window" shows the interviewer exactly how you think.

For a week-by-week plan that puts these patterns in order, see how to prepare for LeetCode interviews. When a problem doesn't fit any pattern you recognize, see what to do when you get stuck.

RELATED
FAQ

Questions about coding patterns

How many LeetCode problems should I solve before an interview?

There's no magic number. Covering each common pattern with three to five problems of increasing difficulty, solved out loud and against a timer, prepares you better than a large count of problems solved silently. Recognizing the pattern is the skill you're building.

Which programming language should I use in coding interviews?

The one you're most fluent in, as long as the company allows it. Python is popular because it's concise and has built-in heaps, deques and counters, but fluency matters more than the language.

What if a problem doesn't fit any pattern I know?

Fall back to fundamentals: work an example by hand, state the brute force, and look for repeated work to remove. Many unfamiliar problems turn out to be a known pattern once you simplify them.

READY · WIN-X64

See the pattern on your own practice problems.

Interview Assistant AI reads the problem and your code on screen, then streams the approach, the complexity and the code — download it and try it while you practice.