Step 1 of 5
DSA Patterns
Fifteen patterns that cover most interview problems, Kadane's algorithm traced step by step, and fourteen sorts compared.
16 min read
Coding interviews look like hundreds of different problems, but most of them are variations on about fifteen patterns. Learn to recognize the pattern from the problem's wording and you're most of the way to the solution. This guide gives you the patterns with the cue that signals each one, walks through Kadane's algorithm step by step, and compares fourteen sorting algorithms.
15 DSA patterns#
For each pattern: the cue in the problem statement that should make you think of it, and a classic example.
Two pointers
O(n)Cue: sorted array, pairs, palindromes, in-place partitioning. Example: pair with target sum in a sorted array.
Sliding window
O(n)Cue: contiguous subarray/substring with a constraint - longest, shortest, at most k. Example: longest substring without repeating characters.
Binary search
O(log n)Cue: sorted input, or a monotonic yes/no answer you can search over ('minimum capacity that works'). Example: search in rotated sorted array.
Frequency counting
hash mapCue: anagrams, duplicates, 'how many times', majority. Example: group anagrams.
Matrix traversal
gridCue: 2D grid, islands, spiral order, rotations. Example: rotate an image 90° in place.
Monotonic stack
O(n)Cue: next greater/smaller element, spans, histograms. Example: daily temperatures.
Prefix sum
O(1) queriesCue: many range-sum queries, subarray sums equal to k. Example: subarray sum equals k (prefix sums + hash map).
Overlapping intervals
sort firstCue: meetings, ranges, merge/insert intervals. Example: merge intervals after sorting by start.
Greedy
local → globalCue: choosing the locally best option provably leads to the best overall. Example: jump game; interval scheduling.
Top-K with heaps
O(n log k)Cue: k largest, k most frequent, k closest, running median. Example: top k frequent elements.
Backtracking
explore + undoCue: all combinations, permutations, subsets, constraint puzzles. Example: N-Queens; generate parentheses.
Tree traversal
recursionCue: binary trees - pre/in/post-order, level order, path sums. Example: validate a BST with in-order traversal.
Depth-first search
graphCue: connectivity, cycles, topological order, exploring all paths. Example: number of islands; course schedule.
Breadth-first search
shortest pathCue: fewest steps in an unweighted graph or grid; level by level. Example: word ladder; rotting oranges.
Dynamic programming
overlapping subproblemsCue: count the ways, min/max cost, 'can you reach', choices at each step. Example: coin change; longest common subsequence.
Two templates worth memorizing#
# Sliding window: longest substring with at most k distinct characters
def longest_k_distinct(s: str, k: int) -> int:
counts, left, best = {}, 0, 0
for right, ch in enumerate(s):
counts[ch] = counts.get(ch, 0) + 1
while len(counts) > k: # shrink until the window is valid
counts[s[left]] -= 1
if counts[s[left]] == 0:
del counts[s[left]]
left += 1
best = max(best, right - left + 1)
return best
# Binary search on the answer: smallest value where ok(x) becomes True
def first_true(lo: int, hi: int, ok) -> int:
while lo < hi:
mid = (lo + hi) // 2
if ok(mid):
hi = mid # mid works - look left
else:
lo = mid + 1 # mid fails - look right
return lo
Kadane's algorithm#
Problem: find the largest sum of any contiguous subarray. The brute force checks every subarray in O(n²). Kadane's algorithm does it in one pass, O(n) time and O(1) space.
The insight: at each position, the best subarray ending here either extends the best subarray ending at the previous position, or starts fresh at this element - whichever is larger. If the running sum has gone negative, it can only hurt, so drop it.
cur = max(a[i], cur + a[i]); best = max(best, cur)
cur = best sum of a subarray ending at i; best = best sum seen anywhere so far.
def max_subarray(a: list[int]) -> int:
cur = best = a[0]
for x in a[1:]:
cur = max(x, cur + x)
best = max(best, cur)
return best
A full trace on [-2, 1, -3, 4, -1, 2, 1, -5, 4]:
| i | a[i] | cur = max(a[i], cur + a[i]) | best |
|---|---|---|---|
| 0 | −2 | −2 | −2 |
| 1 | 1 | max(1, −1) = 1 - start fresh | 1 |
| 2 | −3 | max(−3, −2) = −2 | 1 |
| 3 | 4 | max(4, 2) = 4 - start fresh | 4 |
| 4 | −1 | max(−1, 3) = 3 | 4 |
| 5 | 2 | max(2, 5) = 5 | 5 |
| 6 | 1 | max(1, 6) = 6 | 6 |
| 7 | −5 | max(−5, 1) = 1 | 6 |
| 8 | 4 | max(4, 5) = 5 | 6 |
The answer is 6, from the subarray [4, -1, 2, 1]. Notice that initializing with a[0] (not 0) makes it correct when every number is negative.
Variations to know: track start/end indices when you reset cur; maximum product subarray (keep both max and min, since a negative flips them); maximum circular subarray (max of the normal answer and total − minimum subarray).
14 sorting techniques compared#
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Bubble | n | n² | n² | 1 | Yes |
| Cocktail shaker | n | n² | n² | 1 | Yes |
| Gnome | n | n² | n² | 1 | Yes |
| Selection | n² | n² | n² | 1 | No |
| Insertion | n | n² | n² | 1 | Yes |
| Shell | n log n | depends on gaps | n² (original gaps) | 1 | No |
| Comb | n log n | ≈ n² / 2ᵖ | n² | 1 | No |
| Merge | n log n | n log n | n log n | n | Yes |
| Quick | n log n | n log n | n² | log n | No |
| Heap | n log n | n log n | n log n | 1 | No |
| Timsort | n | n log n | n log n | n | Yes |
| Counting | n + k | n + k | n + k | k | Yes |
| Radix (LSD) | d(n + k) | d(n + k) | d(n + k) | n + k | Yes |
| Bucket | n + k | n + k | n² | n + k | Yes† |
† Bucket sort is stable if the per-bucket sort is. k = range of keys (counting), base (radix), or number of buckets; d = digits.
What each one is for#
Insertion sort
Fastest in practice on tiny or nearly sorted arrays - which is why hybrid sorts use it for small runs.
Merge sort
Guaranteed n log n and stable; the choice for linked lists and external (on-disk) sorting.
Quicksort
Usually fastest in memory thanks to cache-friendly partitioning; randomized pivots make the n² case vanishingly rare.
Heap sort
n log n worst case with O(1) extra space - useful when memory is tight and guarantees matter.
Timsort
Merge + insertion hybrid that exploits existing runs. Python's sorted() and Java's object sort use it.
Counting / radix
Beat the n log n comparison bound when keys are small integers or fixed-width - not comparison sorts at all.
Shell sort
Insertion sort over shrinking gaps; simple, in-place, and decent for medium arrays.
Comb sort
Bubble sort with a shrinking gap (shrink factor ≈ 1.3) that clears out small values stuck at the end ('turtles').
Bubble, cocktail, gnome
Teaching algorithms. Know how they work and why you'd never ship them.