Skip to content

Commit

Permalink
Merge pull request #999 from shuvojitss/pr-5
Browse files Browse the repository at this point in the history
 Added Min Stack program
  • Loading branch information
UTSAVS26 authored Nov 2, 2024
2 parents 18a658d + 982de09 commit 1d82b44
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
61 changes: 61 additions & 0 deletions Algorithms_and_Data_Structures/Stack/Min_Stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,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()
1 change: 1 addition & 0 deletions Project-Structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@
* [Balanced Parentheses Checker](Algorithms_and_Data_Structures/Stack/Balanced_parentheses_checker.py)
* [Infixtopostifix](Algorithms_and_Data_Structures/Stack/InfixToPostifix.py)
* [Infixtoprefix](Algorithms_and_Data_Structures/Stack/InfixToPrefix.py)
* [Min Stack](Algorithms_and_Data_Structures/Stack/Min_Stack.py)
* [Postfixtoinfix](Algorithms_and_Data_Structures/Stack/PostfixToInfix.py)
* [Postfixtoprefix](Algorithms_and_Data_Structures/Stack/PostfixToPrefix.py)
* [Prefixtoinfix](Algorithms_and_Data_Structures/Stack/PrefixToInfix.py)
Expand Down

0 comments on commit 1d82b44

Please sign in to comment.