Simulate a FIFO Queue with Two Stacks
Stacks & QueuesAuto-graded · 19 test casesLast updated
Tests whether you can emulate first-in-first-out ordering using only two LIFO stacks and explain the amortized cost of each operation.
Simulate a FIFO Queue with Two Stacks
You are given a sequence of operations that describe an abstract queue. Your job is to execute each operation in order, using exactly two LIFO stacks as the only internal storage. You may not use a queue, deque, linked list, or any array operation that removes or inserts at the front.
Each operation is encoded as a list of integers:
[1, value]— addvalueto the back of the queue.[2]— remove the value at the front of the queue and record it.[3]— read the value at the front of the queue without removing it, and record it.
Return a list of all recorded values, in the order the corresponding operations were encountered. The input is guaranteed never to issue a remove or read on an empty queue.
Constraints
0 <= len(operations) <= 500_000-1_000_000_000 <= value <= 1_000_000_000for every add operation.- Every operation is one of the three valid forms described above.
- Target O(1) amortized time per operation and O(q) space for
qvalues currently held in the queue. - Allowed stack primitives: append to the end, pop from the end, and read the last element. Front-insertion and front-removal are not permitted.
Examples
Example 1
Input: simulate_queue_with_stacks([[1, 10], [1, 20], [3], [2], [1, 30], [2], [2]])
Output: [10, 10, 20, 30]
Example 2
Input: simulate_queue_with_stacks([])
Output: []
Hints
Hint 1
A single stack reverses the order of whatever you push onto it. What happens to the order if you pour one stack into a second stack?
Hint 2
Keep one stack exclusively for incoming values and one stack exclusively for outgoing values. When should you move elements from one to the other?
Hint 3
Transferring elements between stacks is only safe when the outgoing stack is completely empty. If you transfer at any other time, newer values will jump ahead of older ones and FIFO order breaks. Convince yourself why, then think about what that rule means for the total number of moves each element makes over its lifetime.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea: two stacks with separate roles
A stack reverses whatever you push onto it. If you then pour that stack into a second stack, the order reverses a second time — and the original arrival order is restored, with the oldest element now sitting on top of the second stack.
That observation drives the whole design:
incomingcollects every newly added value. Each addition is a single append — O(1), no conditions.outgoingserves every remove and peek. Its top is always the oldest value currently in the queue.
When a remove or peek arrives and outgoing is empty, pop everything from incoming and push it onto outgoing. The oldest element in incoming was at the bottom; after the transfer it is on top of outgoing, exactly where it should be.
The critical constraint is to transfer only when outgoing is completely empty. If outgoing still held older values and you poured incoming on top, newer elements would appear before older ones and FIFO order would be broken.
Why it stays correct
Maintain this invariant throughout: every element in outgoing is older than every element in incoming, and outgoing holds its elements with the oldest on top.
- Add: appending to
incomingplaces a newer element above everything already there. The invariant is preserved. - Remove or peek,
outgoingnon-empty: the top ofoutgoingis the globally oldest value. Popping or reading it leaves the rest ofoutgoingin the same relative order. Invariant holds. - Remove or peek,
outgoingempty: the full queue lives inincomingwith the oldest at the bottom. Reversing it intooutgoingputs the oldest on top and leavesincomingempty. The invariant is restored, and it is safe to serve.
Complexity
Time — O(1) amortized per operation, O(n) total.
A transfer of k elements costs O(k), but each value crosses from incoming to outgoing at most once over its entire lifetime. Counting all operations across n elements: each value is pushed onto incoming once, popped from incoming once, pushed onto outgoing once, and popped from outgoing at most once — four stack operations total, regardless of how many other operations happen in between. So n operations cost O(n) in total.
The worst-case cost for a single operation is O(q), where q is the current queue length (a full transfer). Amortized cost and worst-case cost are different things; be ready to explain both.
Space — O(q) for the q values currently held, since each lives in exactly one of the two stacks at any moment.
Edge cases
- Empty input: the loop never executes and the function returns
[]. - Repeated peeks: the first peek may trigger a transfer; subsequent peeks read
outgoing[-1]directly and return the same value without any movement. - Interleaved adds and removes: new values accumulate in
incomingwhileoutgoingstill has elements to serve. The transfer is deliberately deferred untiloutgoingdrains, which is exactly what keeps newer values behind older ones. - Negative values and duplicates: values are stored and returned without inspection, so no special handling is needed.
- Large input (up to 500,000 ops):
list.appendandlist.pop()(from the end) are both O(1) in Python. Never uselist.pop(0)orlist.insert(0, ...), which are O(n) and also violate the stack-only constraint.
Reference solution
from typing import List
def simulate_queue_with_stacks(operations: List[List[int]]) -> List[int]:
incoming = [] # new values land here; most-recent on top
outgoing = [] # values served from here; oldest on top
results = []
for op in operations:
if op[0] == 1:
# Add to back: always a single O(1) push.
incoming.append(op[1])
else:
# Before serving, refill outgoing — but only when it is empty.
# Transferring onto a non-empty outgoing stack would put newer
# elements above older ones and destroy FIFO order.
if not outgoing:
while incoming:
outgoing.append(incoming.pop())
if op[0] == 2:
# Remove and record the front value.
results.append(outgoing.pop())
else:
# Record the front value without removing it.
results.append(outgoing[-1])
return results