[
stack
monotonic deque
design
]
Leetcode 0155 Min Stack
Problem statement
https://leetcode.com/problems/min-stack/
Solution
Here we need to maintain two stacks: one is original one and another is min_stack, where we keep elements in descending order.
Complexity
It is O(1) for all operations for time and O(n) for space after n queries.
Code
class MinStack:
def __init__(self):
self.stack_main = []
self.stack_min = []
def push(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]
def top(self):
return self.stack_main[-1]
def getMin(self):
return self.stack_min[-1]