Created
October 28, 2020 15:58
-
-
Save codecakes/c82ceae7ea3662ae9d1519cdcfbdae4d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from Stack import MyStack | |
class MinStack(MyStack): | |
def __init__(self): | |
super().__init__() | |
self.__min = None | |
self.__last_min_stack = MyStack() | |
def push(self, value): | |
if self.__last_min_stack.is_empty(): | |
self.__min = min( | |
value, self.__min or float('inf')) | |
elif value < self.__last_min_stack.top(): | |
self.__min = value | |
if self.__min != self.__last_min_stack.top(): | |
self.__last_min_stack.push(self.__min) | |
return super().push(value) | |
def pop(self): | |
val = super().pop() | |
if not self.__last_min_stack.is_empty() and ( | |
val == self.__last_min_stack.top()): | |
self.__last_min_stack.pop() | |
self.__min = self.__last_min_stack.top() | |
return val | |
# Returns minimum value from newStack in O(1) Time | |
def min(self): | |
return self.__min |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment