Data Structures19 sections · 729 units
Open in Course

Previous vs Next

Direction matters

You can also find "previous greater" or "previous smaller" by processing right to left:

1.1. Next greater: process left to right, pop when current > top

2.2. Previous greater: process right to left, pop when current > top

3.3. Next smaller: process left to right, pop when current < top

4.4. Previous smaller: process right to left, pop when current < top

The histogram problem implicitly uses both next smaller (right boundary) and previous smaller (left boundary from stack).