Link: 232. Implement Queue using Stacks - Easy
Track:
Question
Restate
Edge Case
- Pop / peek when
outstackis empty → need to transfer frominstack
Method 1 - Lazy Transfer
Method 2
Method
Approach
pop/peek:
- If
outstackis not empty → use it directly - If
outstackis empty → move all elements frominstacktooutstack(this reverses order, making the oldest element on top)
Complexity
- Time Complexity
push: O(1)pop: amortized O(1), worst-case O(n) when transferringpeek: 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 FalseHistory
- Feb-21-2026 Peeked