#232

Implement Queue using Stacks

Easy
StackDesignQueueStackQueue
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

By using two stacks efficiently, we can ensure that each operation is amortized O(1). We only transfer elements when necessary, keeping operations fast.

⚙️

Algorithm

3 steps
  1. 1Step 1: For push, simply push the element onto stack1.
  2. 2Step 2: For pop and peek, check if stack2 is empty. If it is, transfer all elements from stack1 to stack2 (this reverses their order). Then, pop or peek from stack2.
  3. 3Step 3: For empty, check if both stacks are empty.
solution.py20 lines
1class MyQueue:
2    def __init__(self):
3        self.stack1 = []
4        self.stack2 = []
5
6    def push(self, x):
7        self.stack1.append(x)
8
9    def pop(self):
10        self.peek()  # Ensure stack2 has the current front
11        return self.stack2.pop()
12
13    def peek(self):
14        if not self.stack2:
15            while self.stack1:
16                self.stack2.append(self.stack1.pop())
17        return self.stack2[-1]
18
19    def empty(self):
20        return not self.stack1 and not self.stack2

Complexity note: The amortized time complexity for each operation is O(1) because we only transfer elements when stack2 is empty, leading to efficient usage of both stacks.

  • 1Using two stacks allows us to maintain FIFO order by reversing the order of elements when necessary.
  • 2Amortized analysis helps us understand that even though some operations can be costly, they are infrequent.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.