Linear structures: arrays, hash maps and monotonic stacks
CS · Chapter 212 min readAsked at Hudson River Trading, Jump, Citadel Securities, Optiver
After this lesson you should be able to
- Choose between an array, a hash map and a linked list from the access pattern.
- Explain how a hash map handles collisions and when it degrades.
- Recognise the problems a monotonic stack solves in linear time.
Most interview problems are solved by choosing the right linear structure, and the choice follows from one question: what do you need to look up, and by what? Everything else — the hash map, the deque, the monotonic stack — is an answer to a particular version of that.
| You need | Use | Why |
|---|---|---|
| Index-based access | Array | and contiguous |
| Lookup by key | Hash map | average |
| Ordered iteration by key | Balanced tree / sorted map | , keeps order |
| Insert and remove at both ends | Deque | at either end |
| Last-in, first-out | Stack | Matching, nesting, backtracking |
| Frequent insert and delete mid-sequence | Linked list | given the node |
Proposition 2.2
How a hash map works
Hash the key to a bucket index, then handle collisions by chaining a list in each bucket or by probing for the next free slot. Average lookup is because the load factor is kept bounded — the table resizes and rehashes when it fills past a threshold, which is what makes the amortised cost constant.
Holds when
- Worst case is when every key collides, which an adversary can arrange if the hash is predictable.
- Open addressing is faster in cache terms; chaining degrades more gracefully at high load.
- Keys must be immutable, or a mutation changes the hash and the entry becomes unreachable.
The hash map is the trade you make first. A very large share of interview problems reduce to "I am doing a linear scan inside a loop, so this is quadratic" — and the fix is nearly always to precompute a hash map and replace the inner scan with a lookup. Two-sum, finding duplicates, grouping anagrams, counting pairs: all the same move, trading memory for a factor of in time. Recognising that shape quickly is worth more than any individual algorithm.
Proposition 2.4
Monotonic stacks and deques
Keep a stack whose contents are always increasing or decreasing, popping anything that violates the order as you push. Each element is pushed and popped once, so the whole scan is linear despite the inner loop — and it answers "next greater element" style questions directly.
Holds when
- Next greater or smaller element: a monotonic stack, in one pass.
- Sliding-window maximum: a monotonic deque, popping from both ends.
- Largest rectangle in a histogram: a monotonic stack, and the canonical hard example.
The rest of this lesson is in Premium
You have read the opening. 11 more sections follow, including 4 worked examples and 3 quick checks.
Nothing is charged for 7 days, and you can cancel before then. Or read Complexity: reading it off, and deriving it in full, free.