[
stack
design
monotonic deque
]
BinarySearch 0727 Minimum Stack
Problem statement
https://binarysearch.com/problems/Minimum-Stack/
Solution
Equal to Leetcode 0155 Min Stack.
Complexity
It is O(1)
for all operations for time and O(n)
for space after n
queries.
Code
class MinimumStack:
def __init__(self):
self.stack_main = []
self.stack_min = []
def append(self, x):
self.stack_main.append(x)
if not self.stack_min or self.stack_min[-1] >= x:
self.stack_min.append(x)
def pop(self):
last = self.stack_main[-1]
del self.stack_main[-1]
if last == self.stack_min[-1]:
del self.stack_min[-1]
return last
def peek(self):
return self.stack_main[-1]
def min(self):
return self.stack_min[-1]