From 84392c661f624af9f419086be6e24d820506dc5c Mon Sep 17 00:00:00 2001 From: Shuvojit Samanta <142198651+shuvojitss@users.noreply.github.com> Date: Fri, 1 Nov 2024 19:04:36 +0530 Subject: [PATCH 1/2] Create Min_Stack.py --- .../Stack/Min_Stack.py | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Algorithms_and_Data_Structures/Stack/Min_Stack.py diff --git a/Algorithms_and_Data_Structures/Stack/Min_Stack.py b/Algorithms_and_Data_Structures/Stack/Min_Stack.py new file mode 100644 index 0000000000..9e015f61b3 --- /dev/null +++ b/Algorithms_and_Data_Structures/Stack/Min_Stack.py @@ -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() From 982de096945d6813483a1684bdde1776d2a650fa Mon Sep 17 00:00:00 2001 From: shuvojitss Date: Fri, 1 Nov 2024 13:35:31 +0000 Subject: [PATCH 2/2] updating Project-Structure.md --- Project-Structure.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Project-Structure.md b/Project-Structure.md index e37926277b..b19a156a94 100644 --- a/Project-Structure.md +++ b/Project-Structure.md @@ -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)