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
).
Notes
- Only standard stack operations are allowed: push to top, peek/pop from top, size, and is empty.
- Simulating a stack using a list or deque is allowed.
Example
Input:
Approach
a. Approach
We use two stacks, stack1
and stack2
:
stack1
is used to store elements when pushing.
stack2
is used to reverse the order for dequeuing and peeking.
b. Steps
-
Push:
- Push the element onto
stack1
.
-
Pop:
- If
stack2
is empty:
- Transfer all elements from
stack1
to stack2
(reversing the order).
- Pop the top element from
stack2
.
-
Peek:
- If
stack2
is empty:
- Transfer all elements from
stack1
to stack2
.
- Return the top element of
stack2
.
-
Empty:
- Return
true
if both stack1
and stack2
are empty.
c. Time & Space Complexity
- Push: O(1) (constant time to push onto
stack1
).
- Pop: Amortized O(1) (elements are transferred only when
stack2
is empty).
- Peek: Amortized O(1) (same logic as
pop
).
- Empty: O(1) (constant time to check both stacks).
- Space Complexity: O(n), where n is the total number of elements in the queue.
d. Code Snippet