Skip to content

Create min_stack.py #2458

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions data_structures/stacks/min_stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
class MinStack:
""" Designing a Stack that can return Minimum element in Constant time"""

def __init__(self):
""" Creating stack minStack and size Variable"""
self.stack = []
self.minStack = []
self.size = 0
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please see #2477 (comment) and implement .__iter__() and .__len__() methods for this class. .__iter__() should return values in min-to-max order.


def push(self, data: int) -> None:
"""
Push helps to put a element a the end of the stack
>>> s = MinStack()
>>> s.push(1)
>>> assert s.size == 1
"""
if self.size == 0:
self.minStack.append(data)
elif data <= self.minStack[-1]:
self.minStack.append(data)
self.stack.append(data)
self.size = self.size + 1

def pop(self) -> None:
"""Removes the topmost element from the Stack
>>> s = MinStack()
>>> s.push(1)
>>> s.push(2)
>>> assert s.pop() == 2
"""
top = self.stack.pop()
self.size = self.size - 1
if top <= self.minStack[-1]:
self.minStack.pop()
return top

def top(self) -> None:
"""Returns the top element from the stack
>>> s = MinStack()
>>> s.push(3)
>>> s.push(2)
>>> assert s.top() == 2
"""
return self.stack[-1]

def get_min(self):
"""Returns the top element from the Minstack
>>> s = MinStack()
>>> s.push(5)
>>> assert s.get_min() == 5
"""
return self.minStack[-1]


# Code execution starts here
if __name__ == "__main__":

# Creating a min Stack
stack = MinStack()

stack.push(6)
print(stack.get_min()) # prints 6

stack.push(7)
print(stack.get_min()) # prints 6

stack.push(8)
print(stack.get_min()) # prints 6

stack.push(5)
print(stack.get_min()) # prints 5

stack.push(3)
print(stack.get_min()) # prints 3

stack.pop()
print(stack.get_min()) # prints 5

stack.push(10)
print(stack.get_min()) # prints 5

stack.pop()
print(stack.get_min()) # prints 5