Next Greater Element II

Medium

Topics
ArrayStackMonotonic Stack

Given a circular array nums, return an array where each position holds the next greater element (searching circularly), or -1 if none exists.

Example 1

nums102112
answer2-12
index 0its next greater value
For each cell the answer is about the first later value greater than it, wrapping past the end.
Top row is the input; bottom row is the answer per index (-1 when none exists).
Input:  nums = [1,2,1]
Output: [2,-1,2]

Example 2

nums1021324334
answer234-14
index 0its next greater value
Input:  nums = [1,2,3,4,3]
Output: [2,3,4,-1,4]

Constraints

  • 1 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

The non-circular version is the textbook monotonic stack: hold indices whose answer is still unknown, in decreasing order of value, and when a larger value arrives, pop and resolve everything it dominates.

Circularity is handled by walking 2n indices and reading nums[i % n]. The second lap gives every element a chance to be resolved by a value that sits before it in the original order. Indices are only pushed during the first lap, so each one resolves at most once.

Approach

  1. Fill the result with -1, the answer for anything never resolved.
  2. Walk i from 0 to 2n - 1, taking cur = nums[i % n].
  3. While the stack is non-empty and its top value is strictly less than cur, pop it and write cur into that slot.
  4. Push i only while i < n.

Dry Run

nums = [1,2,3,4,3]

  i  i%n  cur   pops           stack(idx)   res
  0   0    1    -              [0]          [-1,-1,-1,-1,-1]
  1   1    2    res[0]=2       [1]          [ 2,-1,-1,-1,-1]
  2   2    3    res[1]=3       [2]          [ 2, 3,-1,-1,-1]
  3   3    4    res[2]=4       [3]          [ 2, 3, 4,-1,-1]
  4   4    3    -              [3,4]        [ 2, 3, 4,-1,-1]
  5   0    1    -              [3,4]        [ 2, 3, 4,-1,-1]
  6   1    2    -              [3,4]        [ 2, 3, 4,-1,-1]
  7   2    3    -              [3,4]        [ 2, 3, 4,-1,-1]
  8   3    4    res[4]=4       [3]          [ 2, 3, 4,-1, 4]   <- the wrap-around resolution
  9   4    3    -              [3]          [ 2, 3, 4,-1, 4]

answer [2,3,4,-1,4]

Index 4 holds a 3 whose next greater element is the 4 at index 3 — reachable only by wrapping. Index 3 holds the maximum and stays -1, correctly, since the comparison is strict.

Complexity

  • Time — O(n): 2n iterations, and across all of them each index is pushed at most once and popped at most once. The inner while is amortised, not nested.
  • Space — O(n) for the stack. The result array is output and is conventionally excluded.

Common Pitfalls

  • Using <= instead of < when popping. On [1,1] that returns [1,1] instead of [-1,-1]: equal elements resolve each other, but "next greater" is strict.
  • Only one lap, which leaves every element whose answer wraps around at -1.
  • Storing values on the stack instead of indices, which loses the slot to write the answer into.
  • Misreading what the i < n guard is for. Compared against the shown solution on every array up to length 6 over four distinct values, the no-guard version never diverges, so the guard is not protecting correctness here. It keeps each index resolved once and the stack at O(n) — defend it on those grounds, not as a bug fix.
  • Walking 3n or more laps "to be safe". Two laps suffice, because an element not resolved after seeing every other element once will never be resolved.

Full Solution — all languages

class Solution:
    def nextGreaterElements(self, nums):
        n = len(nums)
        res = [-1] * n
        stack = []
        for i in range(2 * n):
            cur = nums[i % n]
            while stack and nums[stack[-1]] < cur:
                res[stack.pop()] = cur
            if i < n:
                stack.append(i)
        return res
SensAI
Beta
Tap the mic to stop voice mode