Which pattern?
Most candidates can implement the patterns and still freeze, because nothing in the question says which one to use. This is the decision tree to run in the first two minutes, out loud.
The four questions, in order
- Is the answer a number?"Minimum capacity", "smallest k", "maximise the minimum". If you can check a candidate faster than you can build one, and the check is monotone, binary search the answer.
- Is it a contiguous run?"Longest substring such that", "subarray with sum at most". Grow a window on the right, repair it from the left, and never move the left edge back.
- Is the input sorted, or about pairs and ends?Two pointers, provided you can argue that a comparison rules one end out for ever. If you cannot, sort first or use a hash map.
- Do subproblems repeat?Write the recursion. If it asks for the same arguments twice, it is dynamic programming: choose an order that makes each entry final before it is read.
Then say which one you picked and why, before you type. That sentence is worth more marks than the first ten lines of code.
The patterns
Arrays and hashing
Trade memory for time: a hash map answers "have I seen this?" in O(1), and most array problems reduce to asking it the right question.
Learn the pattern → 023 problemsTwo pointers
Two indices walking a sorted or paired structure, each step ruling out one candidate for good.
Learn the pattern → 032 problemsSliding window
A window that grows on the right, shrinks on the left, and holds an invariant at all times.
Learn the pattern → 042 problemsBinary search
Search the answer, not the array: halve a monotone predicate until one candidate is left.
Learn the pattern → 052 problemsDynamic programming
Write the recursion, notice the repeats, fill a table in an order that makes each entry final.
Learn the pattern → 063 problemsStack
Keep the elements whose question is still open; each new element settles the ones it beats and waits its turn.
Learn the pattern → 073 problemsHeap (priority queue)
Keep the few elements that matter in a structure that hands you the smallest (or largest) in O(1) and updates in O(log n).
Learn the pattern → 083 problemsBacktracking
Build a solution one choice at a time, and abandon a branch the moment it cannot succeed.
Learn the pattern →