*****Min Stack (Leetcode 155)
Problem Link: https://leetcode.com/problems/min-stack/
It can be solved using two stacks. One is general stack and another one is stack which stores minimum value for the general stack.
But, it can be solved using only one stack using the below code.
class MinStack:
def __init__(self):
self.s=[]
self.minn=float('inf')
def push(self, val: int) -> None:
# If the curr_val is less than minn
# append the minn to stack and set minn to curr_val.
# Then, append curr_val
if(val<=self.minn):
self.s.append(self.minn)
self.minn=val
self.s.append(val)
def pop(self) -> None:
# If the val to be popped is minn,
# pop one elemet first.
# And then, pop one more element and
# set it to minn
if(len(self.s)>0):
if(self.s[-1]==self.minn):
self.s.pop()
self.minn=self.s.pop()
else:
self.s.pop()
def top(self) -> int:
if(len(self.s)>0):
return self.s[-1]
def getMin(self) -> int:
if(len(self.s)>0):
return self.minn
Last updated