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

Example

Let us see the following implementation to get better understanding −

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

Input

["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output

[null,null,null,null,-3,null,0,-2]
raja
Published on 16-Jan-2020 09:27:37
Advertisements