The stack of waiting hours
transcript
For each hour, find the next slower hour. There are a hundred thousand hours. Rescanning costs five billion steps. The answer for each hour is a distance, not a value.
Keep the hours still waiting on a stack. Their values never rise from bottom to top. A new hour pops every smaller one. So the stack is always in order.
Hour two pops hour one. It waited one hour. Hour three pops hour two and hour zero. Hour zero waited three hours. Hours three and four wait for nothing, so they answer zero.
Each hour is pushed once. And popped once. So a hundred thousand hours take about two hundred thousand steps. That is a hundred thousand times faster.
Pop only strictly smaller values. An equal value keeps waiting. Hours left on the stack answer zero. Test a list where every value is equal.
Push once, pop once. About two n steps. Full breakdown in the lecture.