awelgorithms

Pop and restore the previous min

Updated

Pop the pair. The new top's min is the restored minimum. You do not recompute from scratch. The pair already stored it.

What to focus on

Popping a non-min leaves min unchanged (the new top copied it). Popping the current min reveals the previous pair's min.

Worked examples

pop non-min

a = [(4,4), (1,1), (9,1)], pop
  1. remove (9,1)
  2. top (1,1)
  3. min still 1

Result: min 1

pop min

a = [(4,4), (1,1)], pop
  1. remove (1,1)
  2. top (4,4)
  3. min 4

Result: min 4

pop to one

a = [(4,4), (1,1), (9,1)], pop pop
  1. remove 9 then 1
  2. top (4,4)

Result: min 4

Try it

Write popMin(a). a is the stack of (value, min) pairs. Pop the pair. The new top's min is the restored minimum. From [(4,4),(1,1),(9,1)] pop once (min stays 1) then pop the 1 (min becomes 4). Two pops leave min 4.

The pair stack has at least two items before each pop in the drill, except the last example which leaves one. Values are integers.