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

# Implement Queue using Stacks Python Solution

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

LeetCode 232, Easy. Topics: Stack, Design, Queue. [View on LeetCode](https://leetcode.com/problems/implement-queue-using-stacks/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 232   # by problem number
lcpy gen -s implement_queue_using_stacks   # by problem name
```

## Problem

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).

Implement the `MyQueue` class:

* `void push(int x)` Pushes element x to the back of the queue.
* `int pop()` Removes the element from the front of the queue and returns it.
* `int peek()` Returns the element at the front of the queue.
* `boolean empty()` Returns `true` if the queue is empty, `false` otherwise.

### Examples

```
Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]
```

**Explanation:**

```
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
```

### Constraints

* 1 \<= x \<= 9
* At most 100 calls will be made to push, pop, peek, and empty.
* All the calls to pop and peek are valid.

**Notes:**

* You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid.
* Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.

**Follow-up:** Can you implement the queue such that each operation is amortized `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class MyQueue:
    # Time: O(1)
    # Space: O(n)
    def __init__(self) -> None:
        self.input_stack: list[int] = []
        self.output_stack: list[int] = []

    # Time: O(1)
    # Space: O(1)
    def push(self, x: int) -> None:
        self.input_stack.append(x)

    # Time: O(1) amortized
    # Space: O(1)
    def pop(self) -> int:
        self._move_to_output()
        return self.output_stack.pop()

    # Time: O(1) amortized
    # Space: O(1)
    def peek(self) -> int:
        self._move_to_output()
        return self.output_stack[-1]

    # Time: O(1)
    # Space: O(1)
    def empty(self) -> bool:
        return not self.input_stack and not self.output_stack

    def _move_to_output(self) -> None:
        if not self.output_stack:
            while self.input_stack:
                self.output_stack.append(self.input_stack.pop())


# Amortized O(1) Explanation:
# Example with 4 push + 4 pop operations:
#
# push(1)  # input: [1], output: []           - O(1)
# push(2)  # input: [1,2], output: []         - O(1)
# push(3)  # input: [1,2,3], output: []       - O(1)
# push(4)  # input: [1,2,3,4], output: []     - O(1)
#
# pop()    # Move all 4 to output: input: [], output: [4,3,2,1] then pop 1  - O(4)
# pop()    # output: [4,3,2], just pop 2                                     - O(1)
# pop()    # output: [4,3], just pop 3                                       - O(1)
# pop()    # output: [4], just pop 4                                         - O(1)
#
# Total cost: 4 + 4 + 1 + 1 + 1 = 11 operations for 8 calls = 1.4 per operation
# Key: Each element moves exactly once from input to output, so expensive O(n)
# transfer is "spread out" over multiple cheap O(1) operations = amortized O(1)
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(1) | O(n)  |

## Tags

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