Tech Interview RoomStudy guides

Stack & Queue

Next greater element for every array element. Compare brute force and the monotonic stack.

Intermediate · 2 min read · Lesson 2 of 4 in Stack & Queue

Problem

For each element, find the first element to its right that is larger, or -1. [2, 1, 2, 4, 3] → [4, 2, 4, -1, -1].

Pattern

Monotonic stack: keep a stack of indices still waiting for their answer, in decreasing value order. When a bigger element arrives, it is the answer for everything smaller on the stack.

Approach 1: Scan to the right for each element (feasible, O(n²))

java
class NextGreaterBrute {
    static int[] find(int[] a) {
        int[] out = new int[a.length];
        for (int i = 0; i < a.length; i++) {
            out[i] = -1;
            for (int j = i + 1; j < a.length; j++) if (a[j] > a[i]) { out[i] = a[j]; break; }
        }
        return out;
    }
}

Approach 2: Monotonic stack, left to right (O(n)) — optimal

java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

class NextGreaterStack {
    static int[] find(int[] a) {
        int[] out = new int[a.length];
        Arrays.fill(out, -1);
        Deque<Integer> waiting = new ArrayDeque<>();             // indices with decreasing values
        for (int i = 0; i < a.length; i++) {
            while (!waiting.isEmpty() && a[waiting.peek()] < a[i]) out[waiting.pop()] = a[i];
            waiting.push(i);
        }
        return out;
    }

    // Circular array variant: iterate twice, using i % n
    static int[] findCircular(int[] a) {
        int n = a.length;
        int[] out = new int[n];
        Arrays.fill(out, -1);
        Deque<Integer> waiting = new ArrayDeque<>();
        for (int i = 0; i < 2 * n; i++) {
            while (!waiting.isEmpty() && a[waiting.peek()] < a[i % n]) out[waiting.pop()] = a[i % n];
            if (i < n) waiting.push(i);
        }
        return out;
    }
}

class NextGreaterDemo {
    public static void main(String[] args) {
        int[] a = {2, 1, 2, 4, 3};
        System.out.println(Arrays.toString(NextGreaterBrute.find(a)) + " " + Arrays.toString(NextGreaterStack.find(a)));   // [4, 2, 4, -1, -1] x2
        System.out.println(Arrays.toString(NextGreaterStack.findCircular(a)));                                            // [4, 2, 4, -1, 4]
    }
}

Feasible → optimal

O(n²) → O(n) with a monotonic stack: each index is pushed and popped once. Use ArrayDeque, not the synchronised legacy Stack class.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): daily temperatures (days until a warmer day).

Same stack; instead of storing the value, store the distance i - poppedIndex. O(n).

Related (same pattern): stock span (consecutive previous days with price ≤ today).

Keep a stack of (price, span) pairs; while the top price ≤ today's, pop and add its span to today's span. Amortised O(1) per day.

Related (same pattern): largest rectangle in a histogram.

Monotonic increasing stack: when a lower bar arrives, pop taller bars; each popped bar's rectangle extends from the new stack top to the current index (see the next question).