SDE & MLE Prep

232. Implement Queue using Stacks

Problem

Implement a FIFO queue MyQueue (push, pop, peek, empty) using only two stacks and standard stack operations.

Example: push 1, push 2 → peek() = 1, pop() = 1, empty() = false

Constraints: follow-up: amortised O(1) per operation.

Push onto in. For pop/peek, if out is empty, pour all of in into out (reversing order). Each element moves at most once → amortized O(1).

Complexity: amortized O(1).

class MyQueue:
    def __init__(self):
        self.inp, self.out = [], []

    def push(self, x: int) -> None:
        self.inp.append(x)

    def _move(self):
        if not self.out:
            while self.inp:
                self.out.append(self.inp.pop())

    def pop(self) -> int:
        self._move()
        return self.out.pop()

    def peek(self) -> int:
        self._move()
        return self.out[-1]

    def empty(self) -> bool:
        return not self.inp and not self.out