Track the running minimum
Updated
The current stack min is min of all values still on the stack, not of all values ever pushed (popped values leave). You can recompute in O(n) by scanning, or store it in O(1) with a min field / min stack.
What to focus on
After push 4,1,9 the min is 1. After pop of 9, min is still 1. After pop of 1, min becomes 4.
Worked examples
three
a = [4, 1, 9]- min 1
Result: 1
after pop 9
a = [4, 1]- min 1
Result: 1
after pop 1
a = [4]- min 4
Result: 4
Try it
Write stackMin(a). a is the stack, written [bottom, ..., top]. Return the min of values still on the stack. Scanning is O(n). The next skills make it O(1). Min of [4, 1, 9] is 1. After popping 9 it is still 1. After popping 1 it is 4.
The stack is non-empty. Values are integers.