Skip to content

Commit 77b768e

Browse files
Update min_stack_with_twostacks.py
Refactor MinStack: add type hints ,return type, snake_case, and doctests which were missing.
1 parent f2930d8 commit 77b768e

1 file changed

Lines changed: 45 additions & 30 deletions

File tree

Lines changed: 45 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,65 @@
11
class MinStack:
2-
def __init__(self):
3-
self.st = []
4-
# main stack for storing elements
5-
self.minSt = []
6-
# auxiliary stack for finding minimum in O(1) time space O(N) because of this auxiliary stack using
7-
8-
# pushing new element
9-
def push(self, x):
10-
self.st.append(x)
11-
12-
# If minSt is empty or new element is smaller than
13-
# the top of minSt, push it because if it is empty then coming element will be minimum and if coming element is smaller than previous
14-
if not self.minSt or x <= self.minSt[-1]:
15-
self.minSt.append(x)
16-
17-
# Pop the top element
18-
def pop(self):
2+
"""
3+
A Stack data structure that supports retrieving the minimum element in O(1) time using an auxiliary stack .
4+
5+
>>> st = MinStack()
6+
>>> st.push(18)
7+
>>> st.push(19)
8+
>>> st.push(29)
9+
>>> st.push(15)
10+
>>> st.push(16)
11+
>>> st.get_min()
12+
15
13+
>>> st.pop()
14+
16
15+
>>> st.get_min()
16+
15
17+
>>> st.pop()
18+
15
19+
>>> st.get_min()
20+
18
21+
>>> st.peek()
22+
29
23+
"""
24+
25+
def __init__(self) -> None:
26+
"""Initialize the stack and auxiliary min stack."""
27+
self.st: list[int] = []
28+
self.min_st: list[int] = []
29+
30+
def push(self, value: int) -> None:
31+
"""Push a value onto the stack."""
32+
self.st.append(value)
33+
if not self.min_st or value <= self.min_st[-1]:
34+
self.min_st.append(value)
35+
36+
def pop(self) -> int | None:
37+
"""Pop the top element from the stack. Return None if empty."""
1938
if not self.st:
2039
return None
2140
value = self.st.pop()
22-
if value == self.minSt[-1]:
23-
self.minSt.pop()
41+
if value == self.min_st[-1]:
42+
self.min_st.pop()
2443
return value
2544

26-
# Return top element
27-
def peek(self):
45+
def peek(self) -> int | None:
46+
"""Return the top element without removing it. Return None if empty."""
2847
if not self.st:
2948
return None
3049
return self.st[-1]
3150

32-
# Get the minimum element
33-
def getMin(self):
34-
if not self.minSt:
51+
def get_min(self) -> int | None:
52+
"""Return the minimum element in the stack. Return None if empty."""
53+
if not self.min_st:
3554
return None
36-
return self.minSt[-1]
55+
return self.min_st[-1]
3756

3857

3958
if __name__ == "__main__":
4059
st = MinStack()
41-
# making new minstack object
42-
# adding new elements
4360
st.push(18)
4461
st.push(19)
4562
st.push(29)
4663
st.push(15)
4764
st.push(16)
48-
49-
print(st.getMin())
50-
# should return 15
65+
print(st.get_min()) # should print 15

0 commit comments

Comments
 (0)