Min Stack in Python

A Min Stack is a special data structure that supports all standard stack operations (push, pop, top) plus retrieving the minimum element in constant O(1) time. This is achieved by storing the previous minimum value alongside each new minimum.

Algorithm

The key insight is to store the previous minimum when pushing a new minimum value ?

  • Initialize the stack with min element as infinity
  • For push(x): if x ? current min, store the old min in stack first, then update min to x
  • For pop(): if popped element equals current min, restore the previous min from stack
  • For top(): return the top element without removing it
  • For getMin(): return the current minimum value

Implementation

class MinStack:
    def __init__(self):
        self.min = float('inf')
        self.stack = []
    
    def push(self, x):
        if x <= self.min:
            # Store the previous minimum before updating
            self.stack.append(self.min)
            self.min = x
        self.stack.append(x)
    
    def pop(self):
        t = self.stack[-1]
        self.stack.pop()
        if self.min == t:
            # Restore the previous minimum
            self.min = self.stack[-1]
            self.stack.pop()
    
    def top(self):
        return self.stack[-1]
    
    def getMin(self):
        return self.min

# Example usage
m = MinStack()
m.push(-2)
m.push(0)
m.push(-3)
print("Current min:", m.getMin())
m.pop()
print("Top element:", m.top())
print("Current min:", m.getMin())
Current min: -3
Top element: 0
Current min: -2

How It Works

When pushing -2, 0, -3 sequentially ?

  • Push(-2): Stack: [inf, -2], min = -2
  • Push(0): Stack: [inf, -2, 0], min = -2 (no change)
  • Push(-3): Stack: [inf, -2, 0, -2, -3], min = -3 (stored previous min -2)
  • Pop(): Removes -3, restores min = -2, Stack: [inf, -2, 0]

Time and Space Complexity

Operation Time Complexity Space Complexity
push(x) O(1) O(1)
pop() O(1) O(1)
top() O(1) O(1)
getMin() O(1) O(1)

Conclusion

The Min Stack efficiently maintains the minimum element by storing previous minimums when needed. This approach ensures all operations run in constant time while using minimal extra space.

Updated on: 2026-03-25T07:16:20+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements