Skip to contentKEEP THE CRAFTTHE SANCTUARY

Min Stack

Design a stack that can also return its smallest value in constant time.

The problem

Implement a MinStack class with these methods: push(val) adds val to the top, pop() removes the top element, top() returns the top element, and getMin() returns the smallest element currently in the stack. pop, top and getMin are only called when the stack is not empty. Every method must run in O(1) time.

Starter code

class MinStack:
    def __init__(self):
        pass

Public examples

  1. obj = MinStack() obj.push(-2) obj.push(0) obj.getMin() obj.pop() obj.top()gives[None, None, None, -2, None, -2]
  2. obj = MinStack() obj.push(3) obj.push(1) obj.getMin() obj.pop() obj.getMin()gives[None, None, None, 1, None, 3]
  3. obj = MinStack() obj.push(2147483647) obj.push(-2147483648) obj.top() obj.getMin()gives[None, None, None, -2147483648, -2147483648]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.