StackMedium

Next Greater Element Visualizer

What is Next Greater Element

For each value, the next greater element is the first value to its right that is strictly larger. If none exists, the answer is -1.

Approach

Walk left to right. Pop indexes whose value is smaller than the current one and write the current value as their answer. Push the current index.

Visualization & algorithm

Waiting indexes, then the answer row
ans = [-1] * n
stack holds indexes
for i in range(n):
while stack and a[stack.top] < a[i]:
ans[stack.pop()] = a[i]
push i
return ans
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.

Complexity

PieceCostWhy
TimeO(n)Each index is pushed and popped at most once.
SpaceO(n)The stack and the answer row.

Implementation

def solve(self, nums):
    n = len(nums)
    ans = [-1]*n
    st = []
    for i, val in enumerate(nums):
        while st and nums[st[-1]] < val:
            ans[st.pop()] = val
        st.append(i)
    return ans