> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Max Stack Python Solution with Tests

> Tested Python solution for LeetCode 716 with 61 pytest cases. Generate a practice environment with lcpy.

LeetCode 716, [Hard](/catalog/hard). Topics: [Linked List](/catalog/topics/linked-list), [Stack](/catalog/topics/stack), [Design](/catalog/topics/design), Doubly-Linked List, [Ordered Set](/catalog/topics/ordered-set). [View on LeetCode](https://leetcode.com/problems/max-stack/description/).

Generate this problem as a practice environment: tested reference solution, 61 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 716   # by problem number
lcpy gen -s max_stack   # by problem name
```

## Problem

Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.

Implement the `MaxStack` class:

* `MaxStack()` Initializes the stack object.
* `void push(int x)` Pushes element x onto the stack.
* `int pop()` Removes the element on top of the stack and returns it.
* `int top()` Gets the element on the top of the stack without removing it.
* `int peekMax()` Retrieves the maximum element in the stack without removing it.
* `int popMax()` Retrieves the maximum element in the stack and removes it. If there is more than one maximum element, only remove the top-most one.

You must come up with a solution that supports `O(1)` for each `top` call and `O(logn)` for each other call.

### Examples

```
Input
['MaxStack', 'push', 'push', 'push', 'top', 'pop_max', 'top', 'peek_max', 'pop', 'top']
[[], [5], [1], [5], [], [], [], [], [], []]
Output
[null, null, null, null, 5, 5, 1, 5, 1, 5]
```

### Constraints

* -10^7 \<= x \<= 10^7
* At most 10^5 calls will be made to push, pop, top, peek\_max, and pop\_max.
* There will be at least one element in the stack when pop, top, peek\_max, or pop\_max is called.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/max_stack/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/max_stack/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import heapq
from itertools import count


class Node:
    def __init__(self, val: int = 0):
        self.val = val
        self.seq = 0
        self.prev: Node = self
        self.next: Node = self


class DoubleLinkedList:
    def __init__(self):
        self.head = Node()
        self.tail = Node()
        self.head.next = self.tail
        self.tail.prev = self.head

    def append(self, val: int) -> Node:
        node = Node(val)
        node.next = self.tail
        node.prev = self.tail.prev
        self.tail.prev = node
        node.prev.next = node
        return node

    @staticmethod
    def remove(node: Node) -> Node:
        node.prev.next = node.next
        node.next.prev = node.prev
        node.prev = node.next = node
        return node

    def pop(self) -> Node:
        return self.remove(self.tail.prev)

    def peek(self) -> int:
        return self.tail.prev.val


class MaxStack:
    # Time: push O(log n), pop O(n), top O(1),
    #       peek_max O(log n) amortized, pop_max O(log n) amortized
    # Space: O(n)
    def __init__(self):
        self.stk = DoubleLinkedList()
        self.sl: list[tuple[int, int, Node]] = []
        self.seq = count()

    def push(self, x: int) -> None:
        node = self.stk.append(x)
        node.seq = next(self.seq)
        heapq.heappush(self.sl, (-x, -node.seq, node))

    def pop(self) -> int:
        node = self.stk.pop()
        return node.val

    def top(self) -> int:
        return self.stk.peek()

    def peek_max(self) -> int:
        while True:
            neg_val, _, node = self.sl[0]
            if node.prev is not node:
                return -neg_val
            heapq.heappop(self.sl)

    def pop_max(self) -> int:
        while True:
            neg_val, _, node = heapq.heappop(self.sl)
            if node.prev is not node:
                break
        DoubleLinkedList.remove(node)
        return -neg_val
```

## Complexity

| Time | Space |
| - | - |
| push O(log n), pop O(n), top O(1), | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.