Skip to content

Stack & Queue

A stack (LIFO) remembers things you haven’t resolved yet. When a new element arrives, it resolves the ones on top.

A monotonic stack keeps elements in sorted order (for example, decreasing). When a new element breaks that order, you pop, and the new element is the “next greater” for everything you popped. Every element is pushed and popped once, so it’s O(n).

In Java, use ArrayDeque for both:

Deque<Integer> stack = new ArrayDeque<>();
stack.push(x); stack.pop(); stack.peek(); stack.isEmpty();
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(x); queue.poll(); queue.peek();
// Next greater element to the right, for each index
int[] next = new int[n];
Arrays.fill(next, -1);
Deque<Integer> stack = new ArrayDeque<>(); // stores INDICES, values decreasing
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) {
next[stack.pop()] = nums[i]; // nums[i] is the next greater for the popped index
}
stack.push(i);
}

Store indices, not values. You almost always need the distance or position.

Problem: Valid Parentheses (Easy) — LC 20

Approach (say out loud): “Push opening brackets. On a closing bracket, the top of the stack must be the matching opener. At the end, the stack must be empty.”

Java:

class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(') stack.push(')');
else if (c == '[') stack.push(']');
else if (c == '{') stack.push('}');
else if (stack.isEmpty() || stack.pop() != c) return false;
}
return stack.isEmpty();
}
}

Complexity: O(n) time, O(n) space

Edge cases: odd length (early false), only closing ")", only opening "((" (the stack isn’t empty at the end).

Problem: Min Stack (Medium) — LC 155

Approach (say out loud): “Each stack entry also stores the minimum at the time it was pushed. Then getMin is just a peek, O(1).”

Java:

class MinStack {
private final Deque<int[]> stack = new ArrayDeque<>(); // {value, minSoFar}
public void push(int val) {
int min = stack.isEmpty() ? val : Math.min(val, stack.peek()[1]);
stack.push(new int[]{val, min});
}
public void pop() { stack.pop(); }
public int top() { return stack.peek()[0]; }
public int getMin() { return stack.peek()[1]; }
}

Complexity: O(1) for every operation, O(n) space

Edge cases: duplicate minimums (handled, since each entry has its own min), negative values.

Problem: Implement Queue using Stacks (Easy) — LC 232

Approach (say out loud): “Two stacks: in takes pushes, out serves pops. When out is empty, I pour everything from in into it, which reverses the order. Each element moves at most once, so it’s amortized O(1).”

Java:

class MyQueue {
private final Deque<Integer> in = new ArrayDeque<>();
private final Deque<Integer> out = new ArrayDeque<>();
public void push(int x) { in.push(x); }
public int pop() {
shift();
return out.pop();
}
public int peek() {
shift();
return out.peek();
}
public boolean empty() { return in.isEmpty() && out.isEmpty(); }
private void shift() {
if (out.isEmpty()) {
while (!in.isEmpty()) out.push(in.pop());
}
}
}

Complexity: amortized O(1) per operation, O(n) space

Edge cases: mixing pushes and pops. Only shift when out is empty, or you’ll break the order.

Problem: Evaluate Reverse Polish Notation (Medium) — LC 150

Approach (say out loud): “Push numbers. On an operator, pop two values. The first pop is the right operand. Compute and push the result.”

Java:

class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new ArrayDeque<>();
for (String t : tokens) {
switch (t) {
case "+" -> stack.push(stack.pop() + stack.pop());
case "*" -> stack.push(stack.pop() * stack.pop());
case "-" -> { int b = stack.pop(), a = stack.pop(); stack.push(a - b); }
case "/" -> { int b = stack.pop(), a = stack.pop(); stack.push(a / b); }
default -> stack.push(Integer.parseInt(t));
}
}
return stack.pop();
}
}

Complexity: O(n) time, O(n) space

Edge cases: negative numbers like "-11" (handled because the switch matches the exact string), division truncates toward zero.

Problem: Next Greater Element I (Easy) — LC 496

Approach (say out loud): “Run a monotonic stack over nums2 to find the next greater value for each number, and store it in a map. Then answer each nums1 query from the map.”

Java:

class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map<Integer, Integer> nextGreater = new HashMap<>();
Deque<Integer> stack = new ArrayDeque<>();
for (int x : nums2) {
while (!stack.isEmpty() && x > stack.peek()) {
nextGreater.put(stack.pop(), x);
}
stack.push(x);
}
int[] res = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) {
res[i] = nextGreater.getOrDefault(nums1[i], -1);
}
return res;
}
}

Complexity: O(n + m) time, O(n) space

Edge cases: no greater element → -1. (Values are unique here, which is why storing values works.)

Problem: Daily Temperatures (Medium) — LC 739

Approach (say out loud): “For each day I want the distance to the next warmer day. Monotonic decreasing stack of indices: when today is warmer than the top, the top’s answer is today - top.”

Java:

class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
int[] res = new int[n];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
int prev = stack.pop();
res[prev] = i - prev;
}
stack.push(i);
}
return res; // anything left on the stack stays 0
}
}

Complexity: O(n) time, O(n) space

Edge cases: strictly decreasing temperatures → all 0. Equal temperatures don’t count as warmer (use >, not >=).

Problem: Largest Rectangle in Histogram (Hard) — LC 84

Approach (say out loud): “For each bar, the biggest rectangle using its full height stretches until a shorter bar on each side. Increasing stack of indices: when a shorter bar arrives, I pop. The popped bar’s right boundary is i, and its left boundary is the new top of the stack. I add a sentinel height 0 at the end to flush the stack.”

Java:

class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.length, best = 0;
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i <= n; i++) {
int h = (i == n) ? 0 : heights[i]; // sentinel
while (!stack.isEmpty() && h < heights[stack.peek()]) {
int height = heights[stack.pop()];
int left = stack.isEmpty() ? -1 : stack.peek();
int width = i - left - 1;
best = Math.max(best, height * width);
}
stack.push(i);
}
return best;
}
}

Complexity: O(n) time, O(n) space

Edge cases: a single bar, all bars equal, strictly increasing bars (everything gets popped by the sentinel).