Next Greater Element II

Medium Monotonic Stack Monotonic Stack Original on LeetCode

Next Greater Element II is a medium monotonic stack problem solved with the monotonic stack pattern. The best approach, optimal (monotonic stack over two passes), runs in O(n) time and O(n) space. Below are 2 approaches in Java, from brute force up.

Problem

Given a circular array, return the next greater number for every element: the first larger value found by moving right and wrapping around the end. If none exists, use -1.

Examples

Example 1

Input
nums = [3, 8, 4, 1]
Output
[8, -1, 8, 3]
Why
The array is circular: after 1 comes 3, then 8.

Example 2

Input
nums = [5, 5]
Output
[-1, -1]

Constraints

  • 1 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.

ApproachTimeSpace
Brute forceO(n²)O(1)
Optimal (monotonic stack over two passes)O(n)O(n)

1Brute force

TimeO(n²)
SpaceO(1)

For each index, check the next n - 1 elements circularly.

  1. For each i, for k = 1..n-1, look at nums[(i + k) % n].
Java
class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int n = nums.length;
        int[] out = new int[n];
        for (int i = 0; i < n; i++) {
            out[i] = -1;
            for (int k = 1; k < n; k++)
                if (nums[(i + k) % n] > nums[i]) { out[i] = nums[(i + k) % n]; break; }
        }
        return out;
    }
}

2Optimal (monotonic stack over two passes)

TimeO(n)
SpaceO(n)

Run the usual next-greater stack for i from 0 to 2n - 1 with index i % n. Only push during the first pass; the second pass exists to resolve elements whose answer lies before them.

  1. Fill out with -1.
  2. For i in 0..2n-1: while stack top value < nums[i % n], out[pop()] = nums[i % n].
  3. If i < n, push i.
Java
class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int n = nums.length;
        int[] out = new int[n];
        Arrays.fill(out, -1);
        Deque<Integer> st = new ArrayDeque<>();
        for (int i = 0; i < 2 * n; i++) {
            int x = nums[i % n];
            while (!st.isEmpty() && nums[st.peek()] < x) out[st.pop()] = x;
            if (i < n) st.push(i);
        }
        return out;
    }
}

Edge cases to test

  • The maximum element (always -1)
  • All equal values

Hints

Hint 1

Walk the array twice (indices 0 .. 2n - 1, using i % n) so every element can see around the end.

FAQ

What is the best time complexity for Next Greater Element II?

Optimal (monotonic stack over two passes) runs in O(n) time and O(n) extra space.

Which pattern does Next Greater Element II use?

It is a monotonic stack problem that uses the monotonic stack pattern. Other problems with the same pattern: Next Greater Element I, Daily Temperatures, Largest Rectangle in Histogram.

Is there a brute force solution for Next Greater Element II?

Yes. Brute force takes O(n²) time and O(1) space. For each index, check the next n - 1 elements circularly.

Which edge cases should I test for Next Greater Element II?

The maximum element (always -1); All equal values.