Notes
All notes

Coding Interview Patterns (DSA #28)

The final chapter is a field guide. Learning individual data structures is necessary but not sufficient; interviews and real problems present you with a shape, and experienced engineers recognize the shape and reach for a known pattern. This chapter collects the recurring patterns from the roadmap — fast/slow pointers, merge intervals, cyclic sort, two heaps, k-th element, brute force, randomised algorithms, and multi-threaded thinking — and ends with a decision table tying the whole course together.

Fast and slow pointers

Two references at different speeds, from Chapter 3. The workhorses:

def find_duplicate(nums):
    slow = fast = nums[0]
    while True:                          # phase 1: find a meeting point
        slow, fast = nums[slow], nums[nums[fast]]
        if slow == fast:
            break
    slow = nums[0]                       # phase 2: find the cycle entrance
    while slow != fast:
        slow, fast = nums[slow], nums[fast]
    return slow

The array-as-list trick is worth remembering: index i points to nums[i], so a repeated value is a cycle.

Merge intervals

Given intervals, merge overlapping ones. Sort by start, then sweep: if the next start is within the current end, extend; otherwise emit and start a new interval.

def merge(intervals):
    intervals.sort(key=lambda x: x[0])
    out = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= out[-1][1]:          # overlaps the last merged
            out[-1][1] = max(out[-1][1], end)
        else:
            out.append([start, end])
    return out

print(merge([[1,3],[2,6],[8,10],[15,18]]))   # [[1,6],[8,10],[15,18]]

Variants: insert an interval, find free slots, meet-room scheduling (is any overlap?), interval intersection. All are the same sort-and-sweep.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, minimum height=0.4cm, font=\scriptsize},
  a/.style={->, thick, black!40}]
  \draw[a] (0,0) -- (7.2,0) node[below, font=\small] {time};
  \fill[blue!20] (0.3,0.2) rectangle (2.0,0.5); \node[font=\scriptsize] at (1.15,0.35) {[1,3]};
  \fill[orange!25] (1.6,0.8) rectangle (3.6,1.1); \node[font=\scriptsize] at (2.6,0.95) {[2,6]};
  \fill[green!28] (0.3,1.5) rectangle (3.6,1.8); \node[font=\scriptsize] at (1.95,1.65) {[1,6] merged};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (3.6,-0.5) {sort by start, then extend when the next start overlaps};
\end{tikzpicture}

Cyclic sort

When an array contains numbers in a known range 1..n, each number belongs at index value - 1. Swap each element into its home until every position is correct — \(O(n)\) with \(O(1)\) space. The pattern solves “missing number”, “duplicate”, “first missing positive”, and “find all duplicates”.

def cyclic_sort(nums):
    i = 0
    while i < len(nums):
        home = nums[i] - 1
        if 1 <= nums[i] <= len(nums) and nums[i] != nums[home]:
            nums[i], nums[home] = nums[home], nums[i]   # send to its home
        else:
            i += 1
    return nums

def first_missing_positive(nums):
    cyclic_sort(nums)
    for i, x in enumerate(nums):
        if x != i + 1:
            return i + 1
    return len(nums) + 1

The guard nums[i] != nums[home] prevents an infinite swap when a duplicate is already home.

Two heaps

Maintain a running median (Chapter 11) with a max-heap for the lower half and a min-heap for the upper half, kept balanced. The same shape answers “sliding window median” and “maximise capital”. Whenever a problem needs the middle of a stream, think two heaps.

import heapq
low, high = [], []                       # low: max-heap (negated), high: min-heap
def add(x):
    heapq.heappush(low, -x)
    heapq.heappush(high, -heapq.heappop(low))
    if len(high) > len(low):
        heapq.heappush(low, -heapq.heappop(high))

K-th element

For “k-th largest/smallest”, three tools with different trades:

import heapq
def kth_largest(nums, k):
    return heapq.nlargest(k, nums)[-1]     # or a size-k min-heap for a stream

Choose by context: a stream needs the heap; a one-shot array with a tight time budget wants quickselect.

Brute force

Every pattern starts as a brute force. Its role is diagnostic:

def two_sum_brute(nums, target):          # O(n^2) baseline
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]

Randomised algorithms

Randomness is a tool, not a flaw.

import random
def reservoir_sample(stream, k):
    reservoir = []
    for i, x in enumerate(stream):
        if i < k:
            reservoir.append(x)
        else:
            j = random.randint(0, i)      # replace with probability k/(i+1)
            if j < k:
                reservoir[j] = x
    return reservoir

Multi-threaded and concurrent thinking

Even in single-threaded interviews, recognizing concurrency patterns matters:

The DSA angle: a hash map with resizing is not thread-safe during rehash; a skip list is easier to make concurrent than a balanced tree (Chapter 19).

Island traversal and graph patterns

Grid problems (number of islands, flood fill, surrounded regions) are graph traversal on an implicit grid (Chapter 20). Recognize them by a 2D grid, a “connected region”, and a need to mark visited. BFS, DFS, or Union-Find all apply.

The pattern decision table

Clue in the problem Reach for
Sorted + pair/triplet two pointers (Chapter 27)
Contiguous subarray/substring, longest/shortest sliding window (Chapter 27)
“Have I seen this?” hash map/set (Chapter 6)
Frequency / grouping / dedupe hash map (Chapter 6)
Top-k / k-th / merge sorted streams heap (Chapter 11)
Middle / cycle / palindrome list fast and slow pointers (Chapter 3, 28)
Overlapping intervals sort + merge intervals (Chapter 28)
Numbers in range 1..n cyclic sort (Chapter 28)
Ordered operations, range query with updates segment tree / Fenwick (Ch. 15–16)
Prefix queries over strings trie (Chapter 14)
Connectivity, merging sets union-find (Chapter 17)
Shortest path, weighted Dijkstra / Bellman-Ford (Chapter 21)
Minimum connection cost MST (Chapter 22)
All combinations/permutations backtracking (Chapter 23)
Split and combine, no overlap divide and conquer (Chapter 24)
Local choice provably optimal greedy (Chapter 25)
Overlapping subproblems, count/optimise dynamic programming (Chapter 26)

A method for any new problem

  1. Restate the problem and write two small examples.
  2. Brute force it; note the complexity.
  3. Find the pattern using the table above; identify the structure that removes the inner loop.
  4. Pick the data structure that makes the key operation cheap.
  5. Handle edge cases: empty input, single element, duplicates, overflow, unreachable.
  6. Analyse time and space; see if either can improve.

Pitfalls

QQuestionFinal self-check

Which pattern handles overlapping intervals, and what is the first step? How do you decide between a heap, quickselect, and sorting for k-th largest? What is the role of brute force?

ASolution

Merge intervals: sort by start, then sweep and extend. Use a size-k heap for streaming, quickselect for average \(O(n)\) on a static array, and sorting when \(n\) is small or simplicity matters. Brute force establishes correctness on small inputs, reveals the complexity to improve, and demonstrates structured reasoning.

That completes the course. Pick a problem, name its shape, and the right structure usually names itself.