Stack with O(1) minimum
Design a stack that, besides push, pop and top, returns its smallest element in constant time. A question about the memory–time trade-off.
An editor with undo history keeps values on a stack and keeps asking for the smallest one. Scanning the whole stack each time is too slow – we need a MinStack where every operation runs in O(1).
Task
| Operation | Behaviour |
|---|---|
push(x) | pushes the integer x |
pop() | removes and returns the top element |
top() | returns the top element without removing it |
getMin() | returns the smallest element on the stack |
size | number of elements |
pop, top and getMin on an empty stack report an error:
| Language | Names | Empty stack |
|---|---|---|
| JS/TS | push, pop, top, getMin, getter size | Error('Stack is empty') |
| Python | push, pop, top, get_min, len(stack) | IndexError |
| C# | Push, Pop, Top, GetMin, property Count | InvalidOperationException |
| Java | push, pop, top, getMin, size() | IllegalStateException |
| Go | NewMinStack(), Push, Pop, Top, Min, Len | second result ok == false |
Example
| Operations | Result |
|---|---|
push(5), push(3), push(7) | top() = 7, getMin() = 3 |
push(2) | getMin() = 2 |
pop() | returns 2, getMin() = 3 |
pop(), pop() | return 7 and 3, getMin() = 5 |
Constraints
- Up to 100,000 operations per test, values in the 32-bit
intrange. - The minimum can repeat (e.g.
push(1),push(1),pop()– the minimum is still 1).
Expected complexity
Every operation O(1), O(n) memory.