Polski

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.

easy · typescript · javascript · python · csharp · java · go · 10 XP

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

OperationBehaviour
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
sizenumber of elements

pop, top and getMin on an empty stack report an error:

LanguageNamesEmpty stack
JS/TSpush, pop, top, getMin, getter sizeError('Stack is empty')
Pythonpush, pop, top, get_min, len(stack)IndexError
C#Push, Pop, Top, GetMin, property CountInvalidOperationException
Javapush, pop, top, getMin, size()IllegalStateException
GoNewMinStack(), Push, Pop, Top, Min, Lensecond result ok == false

Example

OperationsResult
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 int range.
  • 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.