Min Stack in Python

PythonServer Side ProgrammingProgramming

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):
      self.min=float('inf')
      self.stack = []
   def push(self, x):
      if x<=self.min:
         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:
         self.min = self.stack[-1]
         self.stack.pop()
   def top(self):
      return self.stack[-1]
   def getMin(self):
      return self.min
m = MinStack()
m.push(-2)
m.push(0)
m.push(-3)
print(m.getMin())
m.pop()
print(m.top())
print(m.getMin())

Input

m = MinStack()
m.push(-2)
m.push(0)
m.push(-3)
print(m.getMin())
m.pop()
print(m.top())
print(m.getMin())

Output

-3
0
-2
raja
Published on 16-Jan-2020 13:57:37
Advertisements