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.

1

Two pointers

O(n)

Cue: sorted array, pairs, palindromes, in-place partitioning. Example: pair with target sum in a sorted array.

2

Sliding window

O(n)

Cue: contiguous subarray/substring with a constraint - longest, shortest, at most k. Example: longest substring without repeating characters.

3

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.

4

Frequency counting

hash map

Cue: anagrams, duplicates, 'how many times', majority. Example: group anagrams.

5

Matrix traversal

grid

Cue: 2D grid, islands, spiral order, rotations. Example: rotate an image 90° in place.

6

Monotonic stack

O(n)

Cue: next greater/smaller element, spans, histograms. Example: daily temperatures.

7

Prefix sum

O(1) queries

Cue: many range-sum queries, subarray sums equal to k. Example: subarray sum equals k (prefix sums + hash map).

8

Overlapping intervals

sort first

Cue: meetings, ranges, merge/insert intervals. Example: merge intervals after sorting by start.

9

Greedy

local → global

Cue: choosing the locally best option provably leads to the best overall. Example: jump game; interval scheduling.

10

Top-K with heaps

O(n log k)

Cue: k largest, k most frequent, k closest, running median. Example: top k frequent elements.

11

Backtracking

explore + undo

Cue: all combinations, permutations, subsets, constraint puzzles. Example: N-Queens; generate parentheses.

12

Tree traversal

recursion

Cue: binary trees - pre/in/post-order, level order, path sums. Example: validate a BST with in-order traversal.

13

Depth-first search

graph

Cue: connectivity, cycles, topological order, exploring all paths. Example: number of islands; course schedule.

14

Breadth-first search

shortest path

Cue: fewest steps in an unweighted graph or grid; level by level. Example: word ladder; rotting oranges.

15

Dynamic programming

overlapping subproblems

Cue: 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]:

ia[i]cur = max(a[i], cur + a[i])best
0−2−2−2
11max(1, −1) = 1 - start fresh1
2−3max(−3, −2) = −21
34max(4, 2) = 4 - start fresh4
4−1max(−1, 3) = 34
52max(2, 5) = 55
61max(1, 6) = 66
7−5max(−5, 1) = 16
84max(4, 5) = 56

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#

AlgorithmBestAverageWorstSpaceStable
Bubblenn²n²1Yes
Cocktail shakernn²n²1Yes
Gnomenn²n²1Yes
Selectionn²n²n²1No
Insertionnn²n²1Yes
Shelln log ndepends on gapsn² (original gaps)1No
Combn log n≈ n² / 2ᵖn²1No
Mergen log nn log nn log nnYes
Quickn log nn log nn²log nNo
Heapn log nn log nn log n1No
Timsortnn log nn log nnYes
Countingn + kn + kn + kkYes
Radix (LSD)d(n + k)d(n + k)d(n + k)n + kYes
Bucketn + kn + kn²n + kYes†

† 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.

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.