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:
- Cycle detection (Floyd’s): fast laps slow inside a loop.
- Middle of a list: when fast hits the end, slow is at the middle.
- Palindrome linked list: reverse the second half, compare.
- Find the duplicate number in an array of \(n+1\) integers (treat the array as a linked list of indices).
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:
- Sort — \(O(n \log n)\), simplest.
- Heap of size k — \(O(n \log k)\), streaming-friendly (Chapter 11).
- Quickselect — average \(O(n)\), in-place (Chapter 24).
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:
- It establishes correctness for small inputs, which you can use to test the optimised version.
- Its complexity tells you what to optimise: \(O(n^2)\) points at a hash map or two pointers, \(O(2^n)\) points at DP or pruning.
- In interviews, stating the brute force first and then improving it shows structured thinking.
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.
- Randomised quick sort / quickselect — a random pivot avoids the adversarial worst case (Chapter 7).
- Skip lists — random level promotion gives expected \(O(\log n)\) with simple code (Chapter 19).
- Reservoir sampling — pick a uniformly random element from a stream in one pass and \(O(1)\) space.
- Randomised hashing — salt hashes to defeat collision attacks.
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:
- Producer–consumer with a bounded queue and back pressure.
- Reader–writer locks — many readers or one writer.
- Thread-safe structures — concurrent skip lists, lock-free queues; skip lists and copy-on-write structures are favoured for this.
- Deadlock avoidance — consistent lock ordering, timeouts.
- Atomics — compare-and-swap for counters and lock-free updates.
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
- Restate the problem and write two small examples.
- Brute force it; note the complexity.
- Find the pattern using the table above; identify the structure that removes the inner loop.
- Pick the data structure that makes the key operation cheap.
- Handle edge cases: empty input, single element, duplicates, overflow, unreachable.
- Analyse time and space; see if either can improve.
Pitfalls
- Pattern-matching the wrong pattern. A sliding window on data with negatives, or two pointers on unsorted data, fails; verify preconditions.
- Cyclic-sort infinite loops. Always include the
nums[i] != nums[home]guard. - Interval merge without sorting. Intervals must be sorted by start first.
- K-th largest via full sort in a stream. Use a size-k heap; sorting per query is \(O(n \log n)\) each time.
- Ignoring thread safety. Shared mutable structures need locks or concurrent variants.
- Skipping the brute force. It is how you validate the clever solution and communicate your reasoning.
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.