15% off all plans & roadmaps Use code
See plansLeetCode 496 · Solution & editorial
The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
Next Greater Element I is a Stack Patterns problem, in the Monotonic Stack subpattern. The pattern covers parentheses matching, monotonic stack, histogram, and expression evaluation
Master monotonic stack for next greater element, daily temperatures, and stock span problems.
The reference solution runs in O(N + M) time and O(N) space.
Next Greater Element I has been reported in interviews at Amazon, Microsoft.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Next Greater Element I is a Stack Patterns problem, in the Monotonic Stack subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.