Right-to-Left Traversal
By traversing backwards, we process the elements that appear on the "right side" first, storing them in the stack for future leftward elements to query.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given an array, find the first strictly greater element that is to the right of each element. If none exists, return -1. This is the classic Monotonic Stack problem.
By traversing backwards, we process the elements that appear on the "right side" first, storing them in the stack for future leftward elements to query.
If the stack's top element is `<= nums[i]`, we pop it. Why? Because `nums[i]` is both LARGER and MORE TO THE LEFT. It completely "blocks" the popped element from ever being the NGE for anything further left!
After finding the NGE from the stack, we push `nums[i]` onto the stack. The stack naturally maintains a Monotonic Decreasing order.