232. Implement Queue using Stacks
Asked at 12Apple46Microsoft46Bloomberg44Amazon37Google34Meta20Qualcomm76Arista Networks60ServiceNow55Infosys45Yandex36TikTok26
Problem
Implement a FIFO queue MyQueue (push, pop, peek, empty) using only two stacks and standard stack operations.
Example: push 1, push 2 → peek() = 1, pop() = 1, empty() = false
Constraints: follow-up: amortised O(1) per operation.
Push onto in. For pop/peek, if out is empty, pour all of in into out (reversing order). Each element moves at most once → amortized O(1).
Complexity: amortized O(1).
class MyQueue:
def __init__(self):
self.inp, self.out = [], []
def push(self, x: int) -> None:
self.inp.append(x)
def _move(self):
if not self.out:
while self.inp:
self.out.append(self.inp.pop())
def pop(self) -> int:
self._move()
return self.out.pop()
def peek(self) -> int:
self._move()
return self.out[-1]
def empty(self) -> bool:
return not self.inp and not self.out
q = MyQueue()
q.push(1); q.push(2)
assert q.peek() == 1 and q.pop() == 1 and not q.empty()
q.push(3)
assert q.pop() == 2 and q.peek() == 3 and q.pop() == 3 and q.empty()
class MyQueue {
private final Deque<Integer> in = new ArrayDeque<>(), out = new ArrayDeque<>();
public void push(int x) { in.push(x); }
private void move() { if (out.isEmpty()) while (!in.isEmpty()) out.push(in.pop()); }
public int pop() { move(); return out.pop(); }
public int peek() { move(); return out.peek(); }
public boolean empty() { return in.isEmpty() && out.isEmpty(); }
}
type MyQueue struct {
in, out []int // push onto in; pop from out, refilled (reversed) only when empty
}
func Constructor() MyQueue {
return MyQueue{}
}
func (this *MyQueue) Push(x int) {
this.in = append(this.in, x)
}
func (this *MyQueue) move() {
if len(this.out) == 0 {
for len(this.in) > 0 {
this.out = append(this.out, this.in[len(this.in)-1])
this.in = this.in[:len(this.in)-1]
}
}
}
func (this *MyQueue) Pop() int {
this.move()
x := this.out[len(this.out)-1]
this.out = this.out[:len(this.out)-1]
return x
}
func (this *MyQueue) Peek() int {
this.move()
return this.out[len(this.out)-1]
}
func (this *MyQueue) Empty() bool {
return len(this.in) == 0 && len(this.out) == 0
}