-
Notifications
You must be signed in to change notification settings - Fork 206
/
Min_Stack.py
61 lines (56 loc) · 1.46 KB
/
Min_Stack.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class MinStack:
def __init__(self):
self.st = []
self.mini = float('inf')
def push(self, value: int):
val = value
if not self.st:
self.mini = val
self.st.append(val)
else:
if val < self.mini:
self.st.append(2 * val - self.mini)
self.mini = val
else:
self.st.append(val)
print(f"Element Pushed: {value}")
def pop(self):
if not self.st:
print("Stack is empty, cannot pop")
return
el = self.st.pop()
if el < self.mini:
print(f"Element popped: {self.mini}")
self.mini = 2 * self.mini - el
else:
print(f"Element popped: {el}")
def top(self) -> int:
if not self.st:
print("Stack is empty")
return -1
el = self.st[-1]
if el < self.mini:
top_element = self.mini
else:
top_element = el
print(f"Top Most Element is: {top_element}")
return top_element
def getMin(self) -> int:
if not self.st:
print("Stack is empty")
return -1
print(f"Minimum Element in the stack is: {self.mini}")
return self.mini
# Sample input as per the question
stack = MinStack()
stack.push(9)
stack.push(15)
stack.getMin()
stack.push(1)
stack.getMin()
stack.pop()
stack.getMin()
stack.push(4)
stack.getMin()
stack.pop()
stack.top()