Stacks and queues · Exercise 65 of 100
Minimum stack
Store two numbers at each stack position, the value pushed and the smallest value seen up to that position. For the first entry, use the value itself as the minimum, and for later entries, use the smaller of the new value and the previous minimum. Whenever the stack has an entry, reading the minimum from the top takes constant time, even after a pop.
Try it yourself
Starting with an empty minimum stack, push 9, 4, 4 and 7 in that order. Pop twice. What minimum does the stack report now?
One-step hint
Beside each pushed entry, record the minimum up to that depth, even for a repeated value. Cross out one entire entry per pop.
Worked solution
- The first 4 lowers the minimum from 9 to 4. The second 4 and the 7 each store 4 as their minimum too.
- The pops remove 7 and the second 4. The first 4 is back on top, so its stored minimum gives the answer 4.