Stacks, queues & monotonic stacks
Solve bracket, next-greater and queue problems.
By Invicly Tech, , in Interview Preparation. About 10 minutes to read.
In short
A stack is last-in, first-out and a queue is first-in, first-out. A monotonic stack keeps elements in sorted order to find the next greater or smaller element in O(n).
Explained simply
A stack works like a pile of plates. You put a plate on top and take a plate from the top, so the last one added is the first one out. A queue works like a line at a ticket counter: the first person to arrive is the first person served.
Stacks are perfect when the most recent thing that is still "open" is the one you must deal with next. An opening bracket waits for its closing bracket. A function call waits for the calls it made to finish. An undo button reverses your latest action first.
A monotonic stack is a stack you keep in sorted order by popping anything that would break the order before you push. Each pop is a moment of discovery: the popped item has just met the first element bigger (or smaller) than itself. That is how "next greater" problems become one pass.
Queues shine when you must handle things in arrival order, like tasks or the levels of a tree in BFS. In Java, use ArrayDeque for both stacks and queues. The old Stack class still works, but it is slower and not recommended.
Press Play on a diagram to walk through it one step at a time.
- 1Scan left to right
Stack holds indexes of unresolved days
- 2Pop while warmer
Current temp beats the top: top found its answer
- 3Record the gap
answer[j] = i - j for each popped j
- 4Push current index
It waits for its own warmer day
- 5Leftovers get 0
No warmer day ever came
- push and pop at the top
- Undo, brackets, DFS
- Python list, Java ArrayDeque
- Add at back, remove at front
- BFS, task scheduling
- Python deque, Java ArrayDeque
- 1Push 3
Stack [3]
- 2Push 4
Stack [3, 4]
- 3+ pops 4 and 3
Pushes 7: stack [7]
- 4Push 2
Stack [7, 2]
- 5* pops 2 and 7
Pushes 14: the answer
- Matching
- Valid Parentheses
- Remove Adjacent Duplicates
- Monotonic stack
- Daily Temperatures
- Largest Rectangle in Histogram
- Expressions
- Evaluate RPN
- Decode String
- Queue and deque
- BFS
- Sliding Window Maximum
In depth
Which monotonic stack do I need?
Decide two things: which direction you look (next or previous) and what you look for (greater or smaller). For "next greater", keep the stack decreasing and pop while the current value is greater; each popped index has found its answer. For "previous smaller", keep the stack increasing; after popping, the top of the stack is the answer for the current index.
Store indexes, not values, so you can compute distances and still read values through the array. For circular arrays, loop over 2n positions and use i % n.
- Next greater: decreasing stack, answer on pop
- Previous smaller: increasing stack, answer is the top after popping
- Store indexes
- Circular: loop 2n times with i % n
- Keep the stack decreasing
- Pop while the current value is greater
- Each popped index gets its answer
- Keep the stack increasing
- Pop while the top is not smaller
- Answer is the top after popping
Largest Rectangle in Histogram
Each bar can be the shortest bar of some rectangle. That rectangle stretches left to just after the previous shorter bar and right to just before the next shorter bar. An increasing stack finds both in one pass.
When a bar shorter than the top arrives, pop the top. Its right boundary is the current index, and its left boundary is the new top of the stack. Width = i - newTop - 1, and area = height × width. A final pretend bar of height 0 flushes the stack. Every bar is pushed and popped once, so it runs in O(n).
Evaluating expressions with stacks
In Reverse Polish Notation, like "3 4 + 2 *", read tokens left to right. Push numbers. On an operator, pop two numbers, apply it (the second one popped is the left side), and push the result. The final stack holds the answer.
For normal expressions with parentheses, such as Basic Calculator, push the current result and sign when you meet "(", start fresh inside, and on ")" combine the inner result with what you popped. Decode String, "3[a2[c]]", uses the same push-on-open, combine-on-close shape.
Queues from stacks, and the monotonic deque
A queue can be built from two stacks. Push into an in-stack. To pop, if the out-stack is empty, move everything from in to out, which reverses the order. Each element moves at most once, so every operation is O(1) amortised.
Sliding Window Maximum uses a deque (double-ended queue) kept in decreasing order of values. Before adding index i, pop smaller values from the back, since they can never be the maximum again. Pop the front if it has left the window. The front is always the current maximum, so the whole array takes O(n).
- 1Push 1, 2, 3
All go on the in-stack
- 2First pop
Out-stack empty: move all, order flips
- 3Return 1
Oldest item is now on top of out
- 4Push 4
Goes on the in-stack
- 5Next pop
Out not empty: return 2
Learn it in 4 short steps
About 1h 15m each. Track them with a timer in your plan.
- 1Implement stacks and queues from scratch~1h 15m
- 2Learn the monotonic stack pattern~1h 15m
- 3Practice: Valid Parentheses, Min Stack~1h 15m
- 4Practice: Daily Temperatures, Next Greater Element~1h 15m
Key points
- Valid Parentheses: push openers, pop and match on closers, stack empty at the end.
- Monotonic stack problems are O(n) because each index is pushed and popped once.
- Min Stack stores the current minimum alongside each pushed value.
- Use collections.deque for queues; list.pop(0) is O(n).
Key terms
Tap a card to flip it. 0/4 known
Examples
def daily_temperatures(temps):
ans = [0] * len(temps)
stack = [] # indexes with decreasing temps
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
j = stack.pop()
ans[j] = i - j
stack.append(i)
return ans # O(n) time, O(n) spaceNext Greater Element for every value
nums = [2, 1, 2, 4, 3]. i = 0 (2): push. i = 1 (1): smaller, push. i = 2 (2): pop index 1 (value 1), its answer is 2; the top now holds 2, not smaller, so push. i = 3 (4): pop both 2s, each gets 4; push. i = 4 (3): push. Indexes left on the stack get -1. Result [4, 2, 4, -1, -1]. O(n) time, O(n) space.
int[] nextGreater(int[] nums) {
int[] ans = new int[nums.length];
Arrays.fill(ans, -1);
Deque<Integer> stack = new ArrayDeque<>(); // indexes, values decreasing
for (int i = 0; i < nums.length; i++) {
while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
ans[stack.pop()] = nums[i];
}
stack.push(i);
}
return ans;
}A queue built from two stacks
push 1 and push 2 go into in = [1, 2]. pop: out is empty, so move everything across; out now has 1 on top, and pop returns 1. push 3 goes into in. pop: out still holds 2, so return 2 without moving anything. pop: out is empty, move 3 across, return 3. Each element is moved once, so n operations cost O(n) in total.
class MyQueue {
private final Deque<Integer> in = new ArrayDeque<>(), out = new ArrayDeque<>();
void push(int x) { in.push(x); }
int pop() { peek(); return out.pop(); }
int peek() {
if (out.isEmpty()) while (!in.isEmpty()) out.push(in.pop());
return out.peek();
}
boolean empty() { return in.isEmpty() && out.isEmpty(); }
}Quick reference
- Java stack or queue: Deque<Integer> d = new ArrayDeque<>(); push/pop/peek or offer/poll
- Brackets: push openers; on a closer, the top must be its match
- Next greater: decreasing stack of indexes, answer when popped
- Monotonic stack and deque problems are O(n): each index pushed and popped once
- Queue from two stacks: move in to out only when out is empty
- Sliding window max: decreasing deque, the front is the max
- RPN: pop b, pop a, push a op b
Common mistakes
- Popping from an empty stack; check before popping.
- Storing values when you need indexes to compute distances.
- Using a list as a queue with pop(0).
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Remove All Adjacent Duplicates in String: repeatedly delete pairs of equal neighbouring letters, so "abbaca" becomes "ca".
- Exercise 2medium
Evaluate Reverse Polish Notation for tokens like ["2", "1", "+", "3", "*"] (answer 9). Division truncates toward zero.
- Exercise 3hard
Largest Rectangle in Histogram: given bar heights, return the area of the largest rectangle.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why not use java.util.Stack?
- Stack extends Vector, so every method is synchronised and slower, and it exposes list methods that break the stack idea. ArrayDeque is faster and is what the Java docs recommend.
- How do I recognise a monotonic stack problem?
- Phrases like next greater, next smaller, previous larger, days until warmer, or stock span are strong hints. So is any brute force that looks left or right from each element until something bigger appears.
- Should I store values or indexes on the stack?
- Indexes, almost always. You can still read the value through the array, and you also get distances and widths, which many problems ask for.