Min Stack in Python

Here we will see how to make a stack, that can perform push, pop, top, and retrieve the min element in constant time. So the functions will be push(x), pop(), top() and getMin()

To solve this, we will follow these steps −

  • Initialize the stack by min element as infinity
  • For push operation push(x)
    • if x < min, then update min := x,
    • push x into stack
  • For pop operation pop()
    • t := top element
    • delete t from stack
    • if t is min, then min := top element of the stack
  • For top operation top()
    • simply return the top element
  • for getMin operation getMin()
    • return the min element


Let us see the following implementation to get better understanding −

class MinStack(object):
   def __init__(self):
      initialize your data structure here.
      self.stack = []
   def push(self, x):
      :type x: int
      :rtype: None
      if x<=self.min:
         self.min = x
   def pop(self):
      :rtype: None
      t = self.stack[-1]
      if self.min == t:
         self.min = self.stack[-1]
   def top(self):
      :rtype: int
      return self.stack[-1]
   def getMin(self):
      :rtype: int
      return self.min




Published on 16-Jan-2020 09:27:37