> ## 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.

# Min Stack Python Solution with Tests

> Tested Python solution for LeetCode 155 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 155, Medium. Topics: Stack, Design. [View on LeetCode](https://leetcode.com/problems/min-stack/description/).

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

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

## Problem

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the `MinStack` class:

* `MinStack()` initializes the stack object.
* `void push(int val)` pushes the element `val` onto the stack.
* `void pop()` removes the element on the top of the stack.
* `int top()` gets the top element of the stack.
* `int getMin()` retrieves the minimum element in the stack.

You must implement a solution with `O(1)` time complexity for each function.

### Examples

```
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]
```

**Explanation:**

```
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top();    // return 0
minStack.getMin(); // return -2
```

### Constraints

* `-2^31 <= val <= 2^31 - 1`
* Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks.
* At most `3 * 10^4` calls will be made to `push`, `pop`, `top`, and `getMin`.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class MinStack:
    # Time: O(1) for all operations
    # Space: O(n) where n is number of elements
    def __init__(self) -> None:
        self.stack: list[int] = []
        self.min_stack: list[int] = []

    # Time: O(1)
    # Space: O(1)
    def push(self, val: int) -> None:
        self.stack.append(val)
        if not self.min_stack or val <= self.min_stack[-1]:
            self.min_stack.append(val)

    # Time: O(1)
    # Space: O(1)
    def pop(self) -> None:
        if self.stack[-1] == self.min_stack[-1]:
            self.min_stack.pop()
        self.stack.pop()

    # Time: O(1)
    # Space: O(1)
    def top(self) -> int:
        return self.stack[-1]

    # Time: O(1)
    # Space: O(1)
    def get_min(self) -> int:
        return self.min_stack[-1]


# Example walkthrough: push(-2), push(0), push(-3), getMin(), pop(), top(), getMin()
#
# Initial: stack=[], min_stack=[]
#
# push(-2): stack=[-2], min_stack=[-2]  (first element, add to both)
# push(0):  stack=[-2,0], min_stack=[-2]  (0 > -2, don't add to min_stack)
# push(-3): stack=[-2,0,-3], min_stack=[-2,-3]  (-3 <= -2, add to min_stack)
# getMin(): return -3  (top of min_stack)
# pop():    stack=[-2,0], min_stack=[-2]  (-3 was min, remove from both stacks)
# top():    return 0  (top of main stack)
# getMin(): return -2  (top of min_stack after pop)
```

## Complexity

| Time                    | Space                              |
| ----------------------- | ---------------------------------- |
| O(1) for all operations | O(n) where n is number of elements |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
