When to reach for a stack
Read FirstTrigger: "I'm at index i and I need to consult elements I already passed." Rather than a nested backward loop (O(n²)), push as you go; the top of the stack is your most-recent relevant predecessor, reachable in O(1).
- ⭐ TRICK — Push either the index, the value,
or the character depending on the problem. Push the
index when you need to write back into a result array later
(you can always recover the value via
arr[index], but not the reverse). - 💡 TIP — Stack follows LIFO. Core ops all O(1):
push,pop,peek/top,size,isEmpty. - 💡 TIP — The recurring template:
foreach element →while (!stack.isEmpty() && <condition on top>) pop;then push current. Only thewhilecondition changes per problem. This shape covers ~80% of stack problems. - ⭐ TRICK — Think conversely. "Next greater element" feels like a forward-looking problem, but you solve it by asking "is the current element the answer for some earlier element still on the stack?" Same mental flip as "I wish I had a parent pointer" in trees.