Skip to content

Commit fef88a9

Browse files
committed
Basic Implementation of min stack bas whenever popping keep an array where you store all previous min and jab bhi min pop then update min with the previous min basic
1 parent c66c2f2 commit fef88a9

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

‎155. Min Stack.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class MinStack(object):
2+
3+
def __init__(self):
4+
self.stack = []
5+
self.min_arr = []
6+
self.min = 2**31
7+
self.min_arr.append(self.min)
8+
def push(self, val):
9+
"""
10+
:type val: int
11+
:rtype: None
12+
"""
13+
if(val<=self.min):
14+
self.min = val
15+
self.min_arr.append(val)
16+
self.stack.append(val)
17+
18+
def pop(self):
19+
"""
20+
:rtype: None
21+
"""
22+
top = self.stack[len(self.stack)-1]
23+
if(top==self.min):
24+
self.min_arr.pop()
25+
self.min = self.min_arr[len(self.min_arr)-1]
26+
return self.stack.pop()
27+
28+
29+
def top(self):
30+
"""
31+
:rtype: int
32+
"""
33+
return self.stack[len(self.stack)-1]
34+
35+
36+
def getMin(self):
37+
"""
38+
:rtype: int
39+
"""
40+
if not self.min_arr:
41+
return 0
42+
return self.min
43+
44+
45+
46+
# Your MinStack object will be instantiated and called as such:
47+
# obj = MinStack()
48+
# obj.push(val)
49+
# obj.pop()
50+
# param_3 = obj.top()
51+
# param_4 = obj.getMin()

0 commit comments

Comments
 (0)