I think pop() function solution is not correct;
We should always keep sorted stack on min_stack.
Please check my solution;
class MinStack:
# Constructor
def init(self):
self.main_stack = MyStack()
self.min_stack = MyStack()
def pop(self):
result = self.main_stack.pop()
tmp_list = []
while not self.min_stack.is_empty() and self.min_stack.peek() != result:
tmp_list.append(self.min_stack.pop())
min_val = self.min_stack.pop()
while len(tmp_list) > 0:
self.min_stack.push(tmp_list.pop())
return result
# Pushes value into new stack
def push(self, value):
if self.min_stack.is_empty():
self.min_stack.push(value)
else:
top = self.min_stack.peek()
if value < top:
self.min_stack.push(value)
else:
tmp_list = []
while not self.min_stack.is_empty() and self.min_stack.peek() < value:
tmp_list.append(self.min_stack.pop())
self.min_stack.push(value)
while len(tmp_list) > 0:
self.min_stack.push(tmp_list.pop())
self.main_stack.push(value)
return True
# Returns minimum value from new stack in constant time
def min(self):
return self.min_stack.peek()