High interview relevanceRoadmap: Intermediate
TimeO(n) total
SpaceO(n)

Why it costs this much

Each index is pushed once and popped at most once, so the while loop inside the for loop does at most 2n operations in total.

Code

def next_greater(nums):
    res, stack = [-1] * len(nums), []
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            res[stack.pop()] = x     # each index is popped at most once
        stack.append(i)              # and pushed exactly once
    return res

Common pitfalls

Decide whether the stack stays strictly or non-strictly ordered (< versus <=). That choice changes how ties behave.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list