How to recognise
for each element, the next or previous one that is greater or smaller: the next warmer day, the nearest taller bar.
How to solve problems like this
- Name what each element waits for: the next greater one or the next smaller one.
- Keep a stack of the indices still waiting. Indices, not values, so you can measure distances.
- For each new element, pop while it beats the top (greater, or smaller). Each popped index has found its answer.
- Push the new index. Indices left on the stack at the end have no answer: give them the default.
Where it's used
- Convex hull. Graham's scan, which GEOS and PostGIS use for ST_ConvexHull, goes round the points and keeps the hull's border on a stack. A new point pops the points that turned out to be inside, the way a monotonic stack pops the items a new one beats.
- Reading formulas. The shunting-yard algorithm keeps operators on a stack in order of priority. A new operator first pops every operator that binds at least as tightly. That is how calculators and formula parsers turn 2 + 3 × 4 into the order of work.