PREP
CHEATSHEET
Patterns.
— a coding reference for the panic moments.
i. Complexity — quick reference
O(1)
Constant. Same work, any input size. dict lookup, array index, ptr vars.
O(log n)
Halving each step. binary search, bisect.
O(n)
Walk each item once. one pass, Counter, Kadane's.
O(n log n)
Sort then sweep. sorted(), merge intervals.
O(n²)
Every pair. nested loops, brute force.
O(n + k)
Linear + buckets. counting sort, bucket sort.
O(2ⁿ)
Exponential — every subset. naive backtracking.
→ Full visual primer with curves, mental models & real numbers on page 3.
ii. The Verbal Opener — six beats, every problem
- Restate"What I'm hearing is: given X, return Y. Did I get that right?"
- ClarifySize? Empty? Duplicates? No-answer return? Time vs space?
- ExamplesWalk 1–2 inputs by hand, out loud, before any code.
- ApproachBrute force first, name its O. Then optimal, name its O.
- CodeNarrate each line. State the invariant out loud.
- TestTrace fresh input. Sweep the edge-case checklist.
iii. The Patterns — When you see X, reach for Y
find a pair summing to target — unsorted input
Hash Map of
Complements
Complements
O(n)
O(n) space
dict
For each
x, ask the notebook: have I seen target − x? If yes, return the pair. If no, write x in. One pass.find a pair summing to target — sorted input
Two
Pointers
Pointers
O(n)
O(1) space
indices
L at start, R at end. Sum too small → L++. Sum too big → R−−. Sorted means moving L only raises sum, R only lowers. Never backtrack.
longest / shortest substring with property
Sliding
Window
Window
O(n)
O(k) space
dict + L,R
R expands the window. When the invariant breaks (dup char, sum > k, >k distinct), L advances until it's repaired. Each index visited ≤ 2× → linear.
does anything repeat? has X been seen?
Set
Existence
Existence
O(n)
O(n) space
set
A bouncer at a door with a guest list. Walk the input — if the name is already on the list, that's the duplicate. Otherwise write it and move on.
how many of each? frequency map
Counter /
defaultdict
defaultdict
O(n)
O(k) space
Counter
One walk, increment.
counts[c] += 1 with defaultdict(int). Counter(seq) is the same in one call. .most_common(k) gives top-K for free.top K elements · K-th largest · streaming median
Min-Heap
of Size K
of Size K
O(n log k)
O(k) space
heapq
Hold the K best you've seen.
heappush a new one, heappop the smallest if size > K. Python only ships min-heap — negate values for max-heap.sorted array — find element / boundary fast
Binary
Search
Search
O(log n)
O(1) space
bisect
Peek the middle. Eliminate the half that can't contain the answer. Repeat. Decide
low <= high vs low < high intentionally — bug-magnet otherwise.next greater / next smaller / span on the right
Monotonic
Stack
Stack
O(n)
O(n) space
list
Stack stays monotonic (decreasing, say). New item comes in: pop everything smaller — each pop pairs that popped element with the new one. Each item pushed + popped at most once → linear.
PG · 01 / 03
PATTERNS — PRINT LANDSCAPE · CHEATSHEET