DrawCode Algorithm Visualizer • Stack & Queue • Medium

Next Greater Element

Tags: Stack, Monotonic, NGE, Array

1. One-Liner

Scan left to right with a stack of indices holding a decreasing value sequence; popping resolves next greater for popped items.


2. The Problem It Solves

Classic for stock span, temperature rise, and histogram warm-ups—pattern recurs in many stack problems.


3. The Core Idea

When a[i] is larger than stack top’s value, it is the NGE for that index—record and pop until monotonic property restored.


4. How It Works (Step-by-Step)

StepAction
1Empty stack
2For each i: while stack & a[top]<a[i] → answer[pop]=a[i]
3Push i
4Remaining indices have no greater to right (-1)

5. Dry Run Example

Array [1,3,2,4]: 1’s NGE is 3, 3’s is 4, 2’s is 4, 4 → -1.


6. Key Properties

PropertyDetail
MonotonicDecreasing values in stack
CircularDuplicate array trick
PairsTrack indices

7. Where It Is Used

Domain / SystemUse
StockNext warm day
CompilersSome bracket flows
AnalyticsSpike detection

8. Interview Tips

Variants: next smaller, circular array, distance instead of value. Time each index pushed/popped once.


9. Comparison with Other Algorithms

TechniqueNotes
Brute forceO(n²)
Deque for min windowDifferent problem
Segment treeOverkill here

10. Complexity

----
TimeO(n)
SpaceO(n) stack

Implementation Example (PYTHON)

def next_greater(nums):
    n = len(nums)
    ans = [-1] * n
    st = []
    for i in range(n):
        while st and nums[st[-1]] < nums[i]:
            ans[st.pop()] = nums[i]
        st.append(i)
    return ans

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer