Created
July 2, 2014 00:13
-
-
Save monkerek/e1d5656ee37ec8616b63 to your computer and use it in GitHub Desktop.
3.2 How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.
This file contains 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
# idea: use another stack to store current minimum value each time a new element is pushed in. | |
# pop top values from both 2 stacks when doing pop operation | |
# time complexity: O(1) | |
# space complexity: O(n) | |
class myStack: | |
def __init__(self): | |
self.__array = [] | |
self.__min = [] | |
self.__topIndex = -1 | |
def pop(self): | |
if self.__topIndex == -1: | |
print 'no element to pop' | |
return | |
self.__array.pop(self.__topIndex) | |
self.__min.pop(self.__topIndex) | |
self.__topIndex -= 1 | |
def push(self, element): | |
if self.__topIndex == -1 or element <= self.__min[self.__topIndex]: | |
self.__min.append(element) | |
else: | |
self.__min.append(self.__min[self.__topIndex]) | |
self.__array.append(element) | |
self.__topIndex += 1 | |
def min(self, order): | |
if self.__topIndex == -1: | |
print 'no element exists' | |
return -1 | |
return self.__min[self.__topIndex] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment