synopsis · Linear patterns · chapter 16
Stacks & Monotonic Stack
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A stack touches only its top:
push,pop,peek— all O(1). Last in, first out: the most recent unfinished thing is handled first. - use it when
Brackets and tags that nest, undo, postfix,
k[...],..in paths, things that collide or cancel — wherever the newest item settles first. - use it when
"Next greater / smaller", "days until warmer", the widest rectangle → a monotonic stack of indices.
- template
while (!st.isEmpty() && a[st.peek()] < a[i]) ans[st.pop()] = a[i]; st.push(i);— each pop gets its answer from the newcomer. - cost
Each index is pushed once and popped at most once → O(n) time, even with a
whileinside thefor. Stack space: O(n) worst case. - trap
pop()on an emptyArrayDequethrows;peek()returns null. CheckisEmpty()first — and check the stack is empty at the end. - trap
stack.peek() == mins.peek()on twoIntegers compares references: fine up to 127, wrong for 1000. Unbox tointfirst. - trap
Postfix: the first
pop()is the right operand. Fora b -, pop b, then a, push a − b. - pro tip
Use
Deque<Integer> st = new ArrayDeque<>(), not legacyStack. Push indices, not values, so you can measure distances and widths.
Shaky on a card? Open the chapter or flip its recall cards.