The Direction Change
For NEXT Greater Element, we usually iterate right-to-left. For PREVIOUS Greater Element, we naturally iterate left-to-right, because the history we care about is on the left.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given an array, find the first strictly greater element to the left of each element. This relies on a Monotonic Decreasing Stack but traversed Left-to-Right.
For NEXT Greater Element, we usually iterate right-to-left. For PREVIOUS Greater Element, we naturally iterate left-to-right, because the history we care about is on the left.
By popping any element that is `<=` the current element, we ensure the stack strictly decreases from bottom to top. The top of the stack is always the closest greater element.
If an element `A` is smaller than the current element `B`, `A` can NEVER be the "Previous Greater" for any future elements, because `B` blocks it. Thus, it's safe to pop `A` forever.