-
-
Notifications
You must be signed in to change notification settings - Fork 50.5k
Expand file tree
/
Copy pathmin_stack.py
More file actions
74 lines (62 loc) · 2.04 KB
/
min_stack.py
File metadata and controls
74 lines (62 loc) · 2.04 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""
Description:
Design a stack that supports push, pop, top, and retrieving the minimum element
in constant time.
Operations:
1. push(x) -> Push element x onto the stack.
2. pop() -> Removes the top element from the stack.
3. top() -> Get the top element.
4. get_min() -> Retrieve the minimum element in the stack.
Example:
min_stack = MinStack()
min_stack.push(-2)
min_stack.push(0)
min_stack.push(-3)
print(min_stack.get_min()) # Output: -3
min_stack.pop()
print(min_stack.top()) # Output: 0
print(min_stack.get_min()) # Output: -2
Time Complexity:
- push: O(1)
- pop: O(1)
- top: O(1)
- get_min: O(1)
Space Complexity:
- O(n) extra space for the auxiliary stack
"""
class MinStack:
def __init__(self):
"""
Initialize two stacks:
- main_stack: stores all elements
- min_stack: stores the current minimum element at each level
"""
self.main_stack: list[int] = []
self.min_stack: list[int] = []
def push(self, x: int) -> None:
"""Push element x onto stack."""
self.main_stack.append(x)
if not self.min_stack or x <= self.min_stack[-1]:
self.min_stack.append(x)
def pop(self) -> None:
"""Remove the element on top of the stack."""
if self.main_stack:
val = self.main_stack.pop()
if val == self.min_stack[-1]:
self.min_stack.pop()
def top(self) -> int | None:
"""Get the top element of the stack."""
return self.main_stack[-1] if self.main_stack else None
def get_min(self) -> int | None:
"""Retrieve the minimum element in the stack."""
return self.min_stack[-1] if self.min_stack else None
# Example usage
if __name__ == "__main__":
min_stack = MinStack()
min_stack.push(-2)
min_stack.push(0)
min_stack.push(-3)
print("Current Min:", min_stack.get_min()) # Output: -3
min_stack.pop()
print("Top Element:", min_stack.top()) # Output: 0
print("Current Min:", min_stack.get_min()) # Output: -2