Competitive Programming

Chapter 17

Pattern cheat sheet

This is the page to reread before a contest or an interview. It compresses the whole book into signals, tools, and typical costs. When a problem lands in front of you, run down this list and something will click.

Signal to pattern

The problem says or impliesTry this patternTypical time
Seen this value before, count, or pair upHash map or setO(n)
Sorted array, pair summing to a target, palindromeTwo pointersO(n)
Longest or shortest contiguous runSliding windowO(n)
Matching brackets, next greater, undoStackO(n)
Sorted data, or "smallest value that works"Binary searchO(log n)
Reverse, middle, cycle in a chainLinked list pointersO(n)
Depth, height, path sum in a treeDFS recursionO(n)
Level by level, shortest unweighted pathBFS with a queueO(n)
Kth largest, top K, running medianHeapO(n log k)
All subsets, permutations, combinationsBacktrackingexponential
Islands, connected groups, reachabilityDFS or BFS on a graphO(nodes + edges)
Prerequisites, build orderTopological sortO(nodes + edges)
Min or max cost, number of ways, overlapping subproblemsDynamic programmingO(states)
Locally best choice provably safeGreedyO(n log n) with a sort
Overlapping ranges, meeting roomsIntervals, sort firstO(n log n)
Appears once among pairs, flags, togglesBit manipulationO(n)

The decision flow, in words

Start by reading the constraints. If n is tiny (up to about 20), an exponential backtracking solution is probably fine and maybe expected. If n is large (100,000 or more), you need roughly O(n) or O(n log n), which rules out nested loops.

Next, look at the shape of the data. Is it sorted, or would sorting help? That points to binary search, two pointers, or a greedy sweep. Is it a tree or a grid or a network? That points to DFS and BFS. Is it a string or array asking for a contiguous best? That is a sliding window.

Finally, look at what is being asked. "How many ways" or "min / max with subproblems" is dynamic programming. "All of something" is backtracking. "The Kth best" is a heap. "Have I seen this" is a hash map.

Write the brute force anyway. Getting a slow but correct solution on the board does three things: it proves you understood the problem, it often reveals the repeated work you can cut, and it gives you partial credit. Then ask the one question that unlocks most optimizations: "what am I recomputing, and can I remember it instead?"

Complexity reference for common operations

OperationCost
Hash map or set lookup, insert, deleteO(1) average
Array index accessO(1)
Append to a dynamic array or listO(1) amortized
Insert or delete in the middle of an arrayO(n)
SortingO(n log n)
Binary search on a sorted arrayO(log n)
Heap push or popO(log n)
BFS or DFS over a graphO(nodes + edges)