Skip to content

Monotonic Stack — Next Greater Element II ​

↗ LeetCode: Next Greater Element II · Medium · pattern chapter →

Asked atAmazonGoogleBloomberg

Given a circular integer array nums, return the next greater element for each position. If none exists, output -1.

Example 1 — nums = [1,2,1] → [2,-1,2] (position 2 wraps around to position 0's 1, still not greater; but then to position 1's 2) Example 2 — nums = [1,2,3,4,3] → [2,3,4,-1,4]Example 3 — nums = [5,4,3,2,1] → [-1,5,5,5,5]

Constraints — 1 ≤ n ≤ 10⁴; -10⁹ ≤ nums[i] ≤ 10⁹.

Progressive Hints
Try to solve it yourself first. Reveal hints only when stuck — each hint is progressively more specific.
---
⏱️Interview timer00:00
Practice under interview pressure. Start when you begin reading; stop when you finish. Save best only when you had a full working solution.
Target for interview: Medium = 20-25 min · Hard = 30-40 min · Best time persists on this device only.

Approach 1 — Brute force (2n scan per position) ​

Intuition. For each i, walk clockwise (mod n) up to n-1 positions; return first nums[j] > nums[i].

java
int[] nextGreaterElementsBrute(int[] nums) {
    int n = nums.length;
    int[] out = new int[n];
    Arrays.fill(out, -1);
    for (int i = 0; i < n; i++) {
        for (int k = 1; k < n; k++) {
            int j = (i + k) % n;
            if (nums[j] > nums[i]) { out[i] = nums[j]; break; }
        }
    }
    return out;
}

Complexity — Time O(n²); Space O(1).


Approach 2 — Monotonic stack over 2n indices (canonical) ​

Insight from brute. For the non-circular version, we sweep right-to-left with a decreasing stack. To handle circularity, we sweep the array twice (iterating 2n - 1 down to 0), taking i % n as the real index. On the second pass, the stack is already primed with everything "to the right including wrap."

java
int[] nextGreaterElements(int[] nums) {
    int n = nums.length;
    int[] out = new int[n];
    Arrays.fill(out, -1);
    Deque<Integer> stack = new ArrayDeque<>();
    for (int i = 2 * n - 1; i >= 0; i--) {
        int val = nums[i % n];
        while (!stack.isEmpty() && stack.peek() <= val) stack.pop();
        if (i < n) out[i] = stack.isEmpty() ? -1 : stack.peek();
        stack.push(val);
    }
    return out;
}
Execution Trace
Circular NGE — nums=[1,2,1]
i102112132415stack = [1]
Step 1 / 62nd pass: nums[5%3]=1; nothing to pop; push

Complexity — Time O(n) (each index pushed and popped at most twice); Space O(n).


Try it yourself ​

Complexity summary ​

ApproachTimeSpaceInterview grade
Brute 2n-scanO(n²)O(1)baseline
Monotonic stack, 2n sweepO(n)O(n)canonical

When to use which ​

  • Any "next greater / smaller" problem → monotonic stack.
  • Circular variant → double the sweep, take i % n.
  • Return indices, not values → push indices instead of values.
  • **Nearest greater in a stream ** → maintain the stack incrementally; answer only for finalized items.
✨AI Study CompanionBeta
Was this page helpful?

Released under MIT license.

💡 Quick shortcuts
H HintsR Run JavaA AI Help