SDE & MLE Prep

225. Implement Stack using Queues

Problem

Implement a LIFO stack MyStack (push, pop, top, empty) using only queue operations: push to back, peek/pop from front, size and is-empty.

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

Constraints: follow-up: use a single queue.

One queue: after pushing x, rotate the previous n−1 elements behind it so x is at the front. Push O(n), pop/top O(1).

Complexity: push O(n), others O(1).

class MyStack:
    def __init__(self):
        self.q = deque()

    def push(self, x: int) -> None:
        self.q.append(x)
        for _ in range(len(self.q) - 1):
            self.q.append(self.q.popleft())

    def pop(self) -> int:
        return self.q.popleft()

    def top(self) -> int:
        return self.q[0]

    def empty(self) -> bool:
        return not self.q