Asked at
Next Greater Element
EasyVerifiedMonotonic StackStack~15 min
Given an array nums, return an array where each entry holds the next greater element to its right, or -1 if none exists.
Walk left to right with a monotonic stack of indices, resolving each as a larger value arrives.
The input is a single array nums.
Examples
in[2, 1, 2, 4, 3]
out[4, 2, 4, -1, -1]
For each element, the first greater value to its right; -1 if none.
in[4, 3, 2, 1]
out[-1, -1, -1, -1]
A strictly decreasing array has no greater element to the right.
Constraints
- 1 ≤ nums.length ≤ 10⁴
- 0 ≤ nums[i] ≤ 10⁹
- Target: O(n) time.
Get help
🔑
Sign in to solve
Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.