Link: 232. Implement Queue using Stacks - Easy
Track:

Question

Restate

Edge Case

  • Pop / peek when outstack is empty → need to transfer from instack

Method 1 - Lazy Transfer
Method 2

Method

Approach

pop/peek:

  • If outstack is not empty → use it directly
  • If outstack is empty → move all elements from instack to outstack (this reverses order, making the oldest element on top)

Complexity

  • Time Complexity
    • push: O(1)
    • pop: amortized O(1), worst-case O(n) when transferring
    • peek: amortized O(1), worst-case O(n)
    • empty: O(1)
  • Space Complexity: O(n)

Code

class MyQueue:
 
    def __init__(self):
        self.instack = []
        self.outstack = []
 
    def push(self, x: int) -> None:
        self.instack.append(x)
 
    def pop(self) -> int:
        if not self.outstack:
            while self.instack:
                val = self.instack.pop()
                self.outstack.append(val)
        val = self.outstack.pop()
        return val
 
    def peek(self) -> int:
        if not self.outstack:
            while self.instack:
                val = self.instack.pop()
                self.outstack.append(val)
        return self.outstack[-1]
 
    def empty(self) -> bool:
        if not self.instack and not self.outstack:
            return True
        else:
            return False

History

  • Feb-21-2026 Peeked