Skip to content
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

Monotonic stack and queue #504

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
28 changes: 28 additions & 0 deletions pydatastructs/miscellaneous_data_structures/stack.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,31 @@ def __str__(self):
elements.append(str(current_node))
current_node = current_node.next
return str(elements[::-1])


class MonotonicStack(Stack):
__slots__ = ["stack"]
def __new__(cls, *args, **kwargs):
raise_if_backend_is_not_python(
cls, kwargs.get('backend', Backend.PYTHON))
obj = object.__new__(cls)
obj.stack = ArrayStack()
obj.stack.push((1e9 , 1e9 ))

return obj

def push(self , element):
self.stack.push((element , max(element , self.stack.peek[1] )))

def pop(self):
self.stack.pop()

def __sizeof__(self):
return self.stack.__sizeof__()

def max(self):
return self.stack.peek[0]

def is_empty(self):
return self.stack.__sizeof__() ==1