ExampleDifficulty: Intermediate2 min

Monotonic Stack Example: How Far Back Each Building's View Reaches

Looking west along a street, a building sees over every shorter building until the first taller one, so the answer is a distance to the previous greater.

The monotonic stack also finds the nearest earlier larger value, by reading the answer when each position is pushed instead of when it is popped. A street of seven buildings runs west to east with heights 5 3 2 4 6 1 3 in storeys, and a viewer on each roof looks west. They see over every shorter building until the first taller one, and the question is how many buildings each viewer sees over.

Nothing in the question says greater, but each answer is the distance to the previous taller building. Pop every waiting building shorter than the current one, since none of them can block a view from further east either. Whatever is left on top is the first taller building to the west, at index top, so the viewer sees over i − top − 1 buildings; with nothing left, they see over all i buildings to the west. The answer is a distance, so the stack holds indices.

How many buildings does the viewer on the fifth building, height 6, see over?

4: every building to its west is shorter, so nothing is left on the stack once it pops them. The steps show every building.

Previous taller building along the street 5 3 2 4 6 1 3

Building 0, height 5: none taller to the west

text
5 3 2 4 6 1 3
^
stack (indices): 0
answer: 0 _ _ _ _ _ _

Building 1, height 3: building 0 is taller

text
5 3 2 4 6 1 3
  ^
stack (indices): 0 1
answer: 0 0 _ _ _ _ _

Building 2, height 2: building 1 is taller

text
5 3 2 4 6 1 3
    ^
stack (indices): 0 1 2
answer: 0 0 0 _ _ _ _

Building 3, height 4: pops 2 and 1, building 0 is taller

text
5 3 2 4 6 1 3
      ^
stack (indices): 0 3
answer: 0 0 0 2 _ _ _

Building 4, height 6: pops 3 and 0, none taller

text
5 3 2 4 6 1 3
        ^
stack (indices): 4
answer: 0 0 0 2 4 _ _

Building 5, height 1: building 4 is taller

text
5 3 2 4 6 1 3
          ^
stack (indices): 4 5
answer: 0 0 0 2 4 0 _

Building 6, height 3: pops 5, building 4 is taller

text
5 3 2 4 6 1 3
            ^
stack (indices): 4 6
answer: 0 0 0 2 4 0 1

The run prints 0 0 0 2 4 0 1. The stack's order is the same as for the next greater value, decreasing towards the top; what changed is when the answer is read. The next greater reads a position's answer when it is popped, and the previous greater reads it when it is pushed, from whatever is left beneath. The pass is O(n) time and O(n) extra space, by the same push-once, pop-once count.