Skip to content

Commit 7346a7a

Browse files
Add Stack which support Min() using two stacks in Python
Implemented a new Minstack class which works like a stack and gives minimum of stack in O(1) using an extra auxiliary stack
1 parent a71618f commit 7346a7a

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
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+
# pushing new element
8+
def push(self, x):
9+
self.st.append(x)
10+
11+
# If minSt is empty or new element is smaller than
12+
# 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
13+
if not self.minSt or x <= self.minSt[-1]:
14+
self.minSt.append(x)
15+
16+
# Pop the top element
17+
def pop(self):
18+
if not self.st:
19+
return None
20+
value = self.st.pop()
21+
if value == self.minSt[-1]:
22+
self.minSt.pop()
23+
return value
24+
25+
# Return top element
26+
def peek(self):
27+
if not self.st:
28+
return None
29+
return self.st[-1]
30+
31+
# Get the minimum element
32+
def getMin(self):
33+
if not self.minSt:
34+
return None
35+
return self.minSt[-1]
36+
37+
38+
if __name__ == '__main__':
39+
st = MinStack()
40+
# making new minstack object
41+
#adding new elements
42+
st.push(18)
43+
st.push(19)
44+
st.push(29)
45+
st.push(15)
46+
st.push(16)
47+
48+
print(st.getMin())
49+
# should return 15

0 commit comments

Comments
 (0)