Skip to content
CodeItRaw
Stacks & Queues

Lesson 3/4

"Which is the first larger element to the right of each one?" is easy and slow with two nested loops. The trick: keep the elements that have not found their answer yet waiting on a stack. When a new element arrives, whoever on top of the stack is smaller than it has just found its answer.

answer = []
waiting = []
for v in values:
while waiting and waiting[-1] >= v:
waiting.pop()
answer.append(waiting[-1] if waiting else -1)
waiting.append(v)
The same idea in the mirror: the nearest smaller value to the left of each element. The newcomer throws out those larger than or equal to it (they can be nobody's nearest smaller any more); what is left on top is the value it was looking for. In the tasks you will look to the right, and the arriving element will answer for those that wait.

The values on the stack always stay ordered one way from bottom to top (the arrival throws out whatever breaks the order), hence the name. Do not let the nested while scare you: each element goes on the stack once and comes off at most once, so the total work never passes 2n.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Monotonic Stack

    Code reading · Predict the Output

  2. 02

    Next Greater

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list