Question
Problem 2: We want to implement an efficient stack (lets call this class EffStack) data structure where all the operations have complexity of O(1) or
Problem 2:
We want to implement an efficient stack (lets call this class EffStack) data structure where all the operations have complexity of O(1) or constant.
-
Thestackimplementstheusualpush,popandpeekfunctions.Thestackuses a List to store the data in the stack. We always push positive values to the stack. (You can use append and pop list methods for pushing and popping)
-
Apartfromthepushandpop,thestackalsoimplementsanothermethodcall minimumval() that returns the minimum value in the current stack.
-
Note as all the operations in the stack in O(1), you cannot use loop to scan for the minimum item or use library function min to get the minimum value from a list.
-
Youcanhavealocalvariabletostorethecurrentminimumvalue.
Code body:
class EffStack: def __init__(self, maxlen=10):
self.maxlen = maxlen self.minimum = None self.array = []
#This method returns if a stack is empty or not def isEmpty(self):
# If top equals to None then stack is empty if len(self.array) == 0:
return True elser:eturn False
# This method returns the minimum value on the stack def minimumval(self):
# Your code goes here
# This method returns the value at the top of stack def peek(self):
# Your code goes here
# This method adds a new value at top of the stack def push(self,value):
# Your code goes here
# This method is used to pop top of stack def pop(self):
# Your code
Sample Input/Output:
S = EffStack() S.push(18) S.push(19) S.push(20) S.push(17) S.push(50) S.peek() # displays 50 S.minimumval() #displays 17 S.pop() #displays 50 S.pop() #displays 17 S.minimumval() #displays 18
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started