232. Implement Queue Using Stacks¶
Edited by Charles
Easy · Python · Stack
Problem
Read the original problem on LeetCode.
The official page contains the problem statement, examples, and constraints.
Explanation, examples & other approaches
Core idea
Queue: first in first out; Stack: first in last out. Create two arrays, inStack and outStack respectively for pushing and popping.
Original study notes follow, including intermediate snippets and earlier attempts.
Note:
- Queue: first in first out; Stack: first in last out.
- Create two arrays, inStack and outStack respectively for pushing and popping.
- For pop(), we need to ensure outStack is not empty. Thus, we use peek() to reversely stuff the elements in inStack to outStack. Thus, we simply call outStack.pop().
- For peek(), we need to ensure outStack is not empty, since the last element is always the front of the queue. As long as outStack is empty, we reverse and move all elements so far in inStack to outStack.
- For empty(), we need to both check inStack and outStack are empty.
Study record
| Field | Value |
|---|---|
| Attempts | 1 |
| Mastery | ❚ |
| The Latest Attempt | January 9, 2026 |
| Feedback | Strongly Recommended for Multiple Attempts |
Python solution¶
class MyQueue:
def __init__(self):
self.inStack = []
self.outStack = []
def push(self, x: int) -> None:
self.inStack.append(x)
def pop(self) -> int:
self.peek()
return self.outStack.pop()
def peek(self) -> int:
if not self.outStack:
while self.inStack:
self.outStack.append(self.inStack.pop())
return self.outStack[-1]
def empty(self) -> bool:
return not self.inStack and not self.outStack
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()