Skip to content

Commit 1934b68

Browse files
committed
added minimum value at constant time in stacks
1 parent e9e7c96 commit 1934b68

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
Given an set of numbers in a stack, find the minimum value from the stack at O(1)
3+
"""
4+
5+
stack = []
6+
min_stack = []
7+
8+
9+
def push(value: int):
10+
"""
11+
Push into the main stack and track the minimum.
12+
If the value to insert < minimum, then push to min stack
13+
Returns None
14+
"""
15+
if len(stack) == 0:
16+
min_stack.append(value)
17+
stack.append(value)
18+
return
19+
20+
if value < min_stack[-1]:
21+
min_stack.append(value)
22+
stack.append(value)
23+
24+
25+
def pop():
26+
"""
27+
Pop from the stack. If the popped value is the same as the min stack top,
28+
pop from the min stack as well
29+
30+
Returns None
31+
"""
32+
if len(stack) == 0:
33+
print("Nothing on stack")
34+
return
35+
36+
top = stack.pop()
37+
if len(min_stack) > 0 and top == min_stack[-1]:
38+
min_stack.pop()
39+
40+
41+
def get_min():
42+
"""
43+
Return the minimum element of the main stack by returning the top of the minimum stack
44+
45+
Returns the minium element (int)
46+
47+
>>> push(10)
48+
>>> push(20)
49+
>>> push(5)
50+
>>> push(30)
51+
>>> push(1)
52+
>>> get_min()
53+
1
54+
>>> pop()
55+
>>> get_min()
56+
5
57+
>>> pop()
58+
>>> get_min()
59+
10
60+
"""
61+
return min_stack.pop()
62+
63+
64+
if __name__ == "__main__":
65+
from doctest import testmod
66+
67+
testmod()

0 commit comments

Comments
 (0)