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.

  1. 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)

  2. Apartfromthepushandpop,thestackalsoimplementsanothermethodcall minimumval() that returns the minimum value in the current stack.

  3. 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.

  4. 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!