Skip to content

stacks/minimum element in constant time #11909

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
76 changes: 76 additions & 0 deletions data_structures/stacks/min_ele_const_time.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""
Given an set of numbers in a stack,

Check failure on line 2 in data_structures/stacks/min_ele_const_time.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

data_structures/stacks/min_ele_const_time.py:2:36: W291 Trailing whitespace
find the minimum value from the stack at O(1)

Problem: https://leetcode.com/problems/min-stack/description/
"""

stack: list[int] = []
min_stack: list[int] = []


def push(value: int) -> None:
"""
Push into the main stack and track the minimum.
If the value to insert < minimum, then push to min stack
Returns None

>>>

Check failure on line 18 in data_structures/stacks/min_ele_const_time.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

data_structures/stacks/min_ele_const_time.py:18:8: W291 Trailing whitespace
"""
if len(stack) == 0:
min_stack.append(value)
stack.append(value)
return

if value < min_stack[-1]:
min_stack.append(value)
stack.append(value)


def pop() -> None:
"""
Pop from the stack.

Check failure on line 32 in data_structures/stacks/min_ele_const_time.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

data_structures/stacks/min_ele_const_time.py:32:24: W291 Trailing whitespace
If the popped value is the same as the min stack top,
pop from the min stack as well

Returns None

>>>

Check failure on line 38 in data_structures/stacks/min_ele_const_time.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

data_structures/stacks/min_ele_const_time.py:38:8: W291 Trailing whitespace
"""
if len(stack) == 0:
print("Nothing on stack")
return

top = stack.pop()
if len(min_stack) > 0 and top == min_stack[-1]:
min_stack.pop()


def get_min() -> int:
"""
Return the minimum element of the main stack by

Check failure on line 51 in data_structures/stacks/min_ele_const_time.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

data_structures/stacks/min_ele_const_time.py:51:52: W291 Trailing whitespace
returning the top of the minimum stack

Returns the minimum element (int)

>>> push(10)
>>> push(20)
>>> push(5)
>>> push(30)
>>> push(1)
>>> get_min()
1
>>> pop()
>>> get_min()
5
>>> pop()
>>> get_min()
10
"""
return min_stack.pop()


if __name__ == "__main__":
from doctest import testmod

testmod()
Loading