232. Implement Queue using Stacks
At a Glance
- Topic: Stack
- Pattern: Two Stacks
- Difficulty: Easy
- LeetCode: 232
Problem Statement
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).
Implement the MyQueue class:
void push(int x) Pushes element x to the back of the queue.
int pop() Removes the element from the front of the queue and returns it.
int peek() Returns the element at the front of the queue.
boolean empty() Returns true if the queue is empty, false otherwise.Notes:
You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.Example 1:
Input ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, nu...
Approach & Solution Steps
Use two stacks, one for enqueuing and one for dequeuing. When dequeuing, if the dequeue stack is empty, transfer all elements from the enqueue stack to reverse their order.
Optimal JS Solution
class MyQueue {
constructor() {
this.in = [];
this.out = [];
}
push(x) {
this.in.push(x);
}
pop() {
this.peek();
return this.out.pop();
}
peek() {
if (this.out.length === 0) {
while (this.in.length > 0) this.out.push(this.in.pop());
}
return this.out[this.out.length - 1];
}
empty() {
return this.in.length === 0 && this.out.length === 0;
}
}Edge Cases & Pitfalls
- Always consider empty or null inputs.
- Watch out for off-by-one index errors.
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?