Get Minimum Element From The Stack
In this class, We discuss Get Minimum Element From The Stack.
Readers can prepare a full competitive coding course to crack product development companies. Click Here.
The reader should have basic coding skills to work with competitive coding. Click here.
Question:
Given N elements.
Our task is to implement a stack that provides a minimum element in the stack in O(1) time.
The time complexity of push and pop functions is O(1).
We need to write the function push, pop and get minimum.
The push function will push the element in the stack.
The pop function will pop the element from the stack.
The get minimum function has to display the minimum element from the stack.
Examples and step-by-step explanations are provided in the video.
Code:
class stack:
def __init__(self):
self.s=[]
self.minEle=None
def push(self,x):
if len(self.s)==0:
self.s.append(x)
self.minEle=x
elif x<self.minEle:
temp=(2*x)-self.minEle
self.s.append(temp)
self.minEle=x
else:
self.s.append(x)
def pop(self):
k=0
if len(self.s)==0:
return -1
else:
z=self.s.pop()
if z<self.minEle:
k=self.minEle
self.minEle=((2*k)-z)
else:
k=z
return k
def getMin(self):
if len(self.s)==0:
return -1
else:
return self.minEle
ob=stack()
while(True):
x=int(input(“enter your option 1. Push 2. Pop 3. quit”))
if(x==1):
y=int(input(“enter the element to insert”))
ob.push(y)
print(“element inserted”)
elif(x==2):
z=ob.pop()
print(z)
elif(x==3):
z=ob.getMin()
print(z)
else:
print(“wrong option”)