Maintained by Vikas Dulgunde, software engineer
You are designing a stack with one extra power: at any moment you can ask for the smallest value currently stored, and that answer must come back instantly rather than by scanning the whole stack.
Instead of wiring up a class with separate methods, this version hands you the calls as data. You receive an array of operation names ("push", "pop", "top", "getMin") and a parallel array of argument lists. A "push" call carries one number in its argument list; the other three carry an empty list.
Walk through the operations in order and produce an array of results, one entry per operation. Use null for any call that returns nothing (push and pop), the current top value for "top", and the current minimum for "getMin".
You are promised that pop, top, and getMin only ever run while the stack holds at least one element, so you never have to defend against an empty stack.
After pushing -2, 0, -3 the minimum is -3. Pop removes -3, so the top is now 0 and the minimum climbs back to -2.
With 5 then 3 on the stack the minimum is 3. Popping 3 leaves only 5, so the minimum becomes 5 again.
A single pushed value is both the top and the minimum.
Visible test cases
The hard part is getMin. Scanning the stack on every query would be O(n) per call, so you need to know the answer in advance without searching.
What if every element remembered the minimum of the stack at the moment it was pushed? Then the minimum of the whole stack is just whatever the top element recorded.
Keep a second stack that runs in lockstep with the main one: each time you push a value, also push min(value, current recorded minimum). Popping both stacks together keeps the recorded minimum correct.
Store values in a plain stack and compute the minimum by looping over all of them whenever getMin is asked.
Maintain a second stack where each slot holds the minimum of everything at or below it, so the current minimum is always the top of that stack.