15% off all plans & roadmaps Use code
See plansLeetCode 503 · Solution & editorial
Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.
Next Greater Element II 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) time and O(n) space.
Next Greater Element II has been reported in interviews at Amazon, Bloomberg, Apple, Facebook.
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 II 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.