-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path155. Min Stack.py
More file actions
31 lines (25 loc) · 845 Bytes
/
Copy path155. Min Stack.py
File metadata and controls
31 lines (25 loc) · 845 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# https://leetcode.com/problems/min-stack
# Monotonic stack
# Note: a simpler (and essentially equivalent) alternative is tracking the prefix sum
class MinStack:
def __init__(self):
self.stack = []
self.minima = [] # monotonically decreasing, non strict
def push(self, val: int) -> None:
self.stack.append(val)
if not self.minima or val <= self.minima[-1]:
self.minima.append(val)
def pop(self) -> None:
removed = self.stack.pop()
if removed == self.minima[-1]:
self.minima.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.minima[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()