Pattern playbook
Fifteen patterns cover most interview and contest problems. Learn to spot the signal, then reach for the matching tool — every example below runs.
Most interview and contest problems are one of about fifteen patterns wearing a disguise. The skill is to recognise the signals in the statement, pick the pattern, and then fill in the details. Each card below gives the signals, the one-paragraph idea, a worked example that really runs (press ▶ to try it or edit it), the cost, and LeetCode problems that use the same pattern.
Which pattern? Match the signal
| If the problem says… | Reach for |
|---|---|
| sorted input, pair/triple wanted | Two pointers |
| longest / shortest contiguous block | Sliding window |
| many range sums, or 'subarrays with sum k' | Prefix sums + hash map |
| 'seen before?', counts, duplicates | Hash map / set |
| next greater / smaller, spans | Monotonic stack |
| 'minimum possible maximum', yes/no check is monotone | Binary search on the answer |
| overlapping intervals / schedules | Sort, then sweep |
| fewest steps in an unweighted graph or grid | BFS |
| regions, reachability, prerequisites | DFS / topological order |
| k best, repeated min or max | Heap |
| merging groups, redundant edge | Union-Find |
| generate every arrangement, n ≤ 20 | Backtracking |
| count ways, min cost, overlapping sub-problems | Dynamic programming |
| local choice provably safe | Greedy |
| weighted edges, non-negative | Dijkstra |
1) Write the brute force and its cost. 2) Ask what the brute force repeats or wastes. 3) Match that waste to a pattern. 4) State the new cost before you code. 5) Test on the smallest case, an empty input and a tricky one.
The 15 patterns
Two pointers Week 2
- sorted array or string
- find a pair / triple with a property
- reverse, partition or compare from both ends
Keep one index at each end (or one slow, one fast). Each step moves one pointer inward using what the sorted order tells you, so you never need a nested loop.
Cost: O(n) time, O(1) space
Practise: Two Sum II ↗ · Container With Most Water ↗ · Valid Palindrome ↗ · Move Zeroes ↗
Sliding window Week 3
- contiguous subarray / substring
- 'longest', 'shortest' or 'best sum of size k'
- a condition that can be maintained while the window grows and shrinks
Grow the window on the right; when the condition breaks, shrink from the left. Each element enters once and leaves once, so the total is linear.
Cost: O(n) time, O(window) space
Practise: Longest Substring Without Repeating ↗ · Minimum Size Subarray Sum ↗ · Max Average Subarray I ↗
Prefix sums Week 3
- many range-sum queries
- 'number of subarrays with sum k'
- counting between two positions
Precompute P[i] = a[0] + … + a[i−1]. Then any range sum is P[j] − P[i] in O(1). Combine with a hash map of earlier prefix values to count subarrays with a target sum.
Cost: O(n) build, O(1) per query
Practise: Subarray Sum Equals K ↗ · Range Sum Query ↗ · Product of Array Except Self ↗
Hash map: count and complement Week 3
- 'have I seen this before?'
- frequencies, duplicates, anagrams
- find a partner value: target − x
A dict or set turns an O(n) search into an O(1) lookup. Store what you have seen; look up what you need. Check for the complement BEFORE inserting the current item.
Cost: O(n) time, O(n) space
Practise: Two Sum ↗ · Group Anagrams ↗ · Contains Duplicate ↗ · Longest Consecutive Sequence ↗
Monotonic stack Week 3
- 'next greater / smaller element'
- 'how many days until warmer'
- largest rectangle, spans
Keep a stack whose values are in sorted order. When a new value breaks the order, pop everything it beats — each popped item has just found its answer. Every item is pushed and popped once.
Cost: O(n) time, O(n) space
Practise: Daily Temperatures ↗ · Next Greater Element I ↗ · Largest Rectangle in Histogram ↗ · Valid Parentheses ↗
Binary search on the answer Week 2
- 'minimum possible maximum' / 'smallest x such that…'
- a yes/no check that is monotone: if x works, x+1 works
- the answer lies in a numeric range
Do not search an array — search the range of possible answers. Write a function ok(x) that tests feasibility in O(n), then binary-search the smallest x with ok(x) true.
Cost: O(n log range)
Practise: Koko Eating Bananas ↗ · Binary Search ↗ · Ship Packages in D Days ↗ · Search in Rotated Sorted Array ↗
Sort, then sweep (intervals) Week 7
- overlapping intervals, meetings, schedules
- merge / count rooms / remove overlaps
- greedy choice needs an order
Sort by start (to merge) or by finish time (to pick the most non-overlapping). After sorting, one left-to-right pass is enough because only neighbours can interact.
Cost: O(n log n) for the sort, O(n) sweep
Practise: Merge Intervals ↗ · Non-overlapping Intervals ↗ · Meeting Rooms II (premium) ↗
BFS: shortest path, levels, grids Week 4
- fewest steps / moves / edges
- unweighted graph or grid
- level-by-level processing
A queue explores vertices in order of distance. The first time you reach a vertex is the shortest way. Mark vertices visited when you ENQUEUE them, not when you pop them.
Cost: O(n + m)
Practise: Shortest Path in Binary Matrix ↗ · Rotting Oranges ↗ · Word Ladder ↗ · Level Order Traversal ↗
DFS: components, cycles, topological order Week 4
- connected regions, islands, reachability
- dependencies / prerequisites
- any 'explore everything reachable' task
Recurse into each unvisited neighbour. Count how many times you START a fresh search to count components. For directed graphs, an edge back to a vertex still on the stack means a cycle.
Cost: O(n + m)
Practise: Number of Islands ↗ · Course Schedule ↗ · Number of Provinces ↗ · Clone Graph ↗
Heap / top-k Week 6
- 'k largest / smallest / most frequent'
- repeatedly need the current min or max
- merge k sorted lists, running median
A heap of size k keeps the best k items in O(log k) per element. Python's heapq is a MIN-heap: for the k largest, keep a min-heap of size k and drop the smallest when it overflows.
Cost: O(n log k)
Practise: Kth Largest Element ↗ · Top K Frequent Elements ↗ · Merge k Sorted Lists ↗ · Median from Data Stream ↗
Union-Find Week 6
- 'are these connected?' while edges keep arriving
- group merging, redundant edge, number of components
- Kruskal's MST
Each group has one representative. find follows parents to the root (compress the path as you go); union links the two roots. Union by size keeps trees shallow.
Cost: almost O(1) amortised per operation
Practise: Redundant Connection ↗ · Connected Components (premium) ↗ · Accounts Merge ↗
Backtracking Recursion chapter
- generate all subsets / permutations / combinations
- 'place things so that no rule is broken' (N-Queens, Sudoku)
- small input size (n ≤ 20)
Build the answer one choice at a time: choose → explore → un-choose. Prune a branch as soon as it cannot lead to a valid answer. See the Recursion & Backtracking chapter for the full treatment.
Cost: exponential in the worst case; pruning is what makes it usable
Practise: Subsets ↗ · Permutations ↗ · Combination Sum ↗ · N-Queens ↗
Dynamic programming Week 9
- 'count the ways', 'minimum cost', 'is it possible'
- the same sub-problem is solved again and again
- choices at each step with a clear state (index, remaining amount…)
Define the state, write the recurrence, fill the table in dependency order. If you can write the brute-force recursion, add a cache first (memoisation); convert to a table only if you need to.
Cost: O(number of states × work per state)
Practise: Climbing Stairs ↗ · Coin Change ↗ · Longest Increasing Subsequence ↗ · Longest Common Subsequence ↗ · Edit Distance ↗
Greedy Week 7
- a locally best choice is never regretted
- scheduling, covering, 'minimum number of…'
- sorting by one key makes the choice obvious
Make the best-looking choice now and never revisit it. It is only correct when you can argue why (exchange argument). If a counter-example exists — coins {1, 3, 4} and amount 6 — switch to DP.
Cost: usually O(n log n) for the sort
Practise: Jump Game ↗ · Gas Station ↗ · Assign Cookies ↗ · Burst Balloons with Arrows ↗
Weighted shortest paths Week 5
- edges have costs / times
- 'cheapest route', 'minimum time to reach all nodes'
- no negative weights (otherwise Bellman-Ford)
Dijkstra: keep a min-heap of (distance, vertex). Pop the closest, skip stale entries, relax its edges. The first time a vertex is popped its distance is final.
Cost: O((n + m) log n)
Practise: Network Delay Time ↗ · Path With Minimum Effort ↗ · Cheapest Flights Within K Stops ↗
Python toolbox for contests and interviews
| Tool | Use it for | Remember |
|---|---|---|
heapq | priority queue, top-k, Dijkstra | Min-heap only. Push (-x) for a max-heap; tuples compare element by element. |
bisect_left / bisect_right | binary search in a sorted list, insertion point | bisect_left(a, x) = first index with a[i] ≥ x. Insert is still O(n). |
collections.deque | BFS queue, sliding-window deque | popleft() is O(1); list.pop(0) is O(n). |
collections.Counter | frequencies, anagram checks | Counter(a) == Counter(b); .most_common(k). |
collections.defaultdict | adjacency lists, grouping | g = defaultdict(list); g[u].append(v) — no key checks. |
functools.lru_cache | memoised recursion (DP top-down) | Arguments must be hashable (use tuples, not lists). |
sys.setrecursionlimit | deep recursion | Default is about 1000. Prefer an explicit stack when depth can reach 10⁵. |
sorted(key=…), itertools | custom sort order, permutations, combinations | sorted is stable. itertools.permutations is a generator. |
Complexity traps
| Trap | Why it bites | Fix |
|---|---|---|
x in some_list inside a loop | Each test scans the list: O(n) × n loops = O(n²) | Convert to a set once |
list.insert(0, x) or list.pop(0) in a loop | Every call shifts all elements: O(n) each | Use deque |
s += ch building a long string in a loop | May copy the whole string each time | Collect pieces in a list and ''.join(pieces) |
Slicing a[1:] in a recursive call | Copies O(n) items per call, so O(n²) overall | Pass indices lo, hi instead |
| Two recursive calls where one would do | f(n//2) * f(n//2) turns O(log n) into O(n) | Store the result in a variable |
| Naive recursion with overlapping calls | Fibonacci-style recursion is exponential | Memoise with lru_cache or a table |
| Recursion depth | Python stops at about 1000 frames (RecursionError) | Iterate with an explicit stack, or raise the limit carefully |
| Counting 'amortised' as 'worst case' | append is O(1) amortised: one call may cost O(n) | Reason about the total over all operations |