Skip to content

visual walkthrough

Next Greater Element I

The simplest monotonic-stack question; learn the template here.

Solve on LeetCode

The idea

Every number in nums2 waits for the first bigger number to its right. A stack of waiting numbers solves all of them in one pass: each arriving number settles every smaller number on the stack.

Store the results in a map, then each query is a lookup.

Complexity

approachtimespace
Scan right for each queryO(n · m)O(1)
Monotonic stack + mapO(n + m)O(n)

More walkthroughs