File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments