easyStackStack

Implement Queue using Stacks

easyTime: O(1) amortized for push and popSpace: O(n)

Signals to notice

implement FIFO using two LIFO structuresamortized O(1) operationsdata structure design

Brute force first

Use one stack and move all elements on every dequeue — per operation. Every dequeue reverses the entire stack to access the bottom element. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Use two stacks: an 'inbox' for pushes and an 'outbox' for pops. Only transfer from inbox to outbox when outbox is empty. Each element is moved at most twice in its lifetime — amortized. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

The outbox always has elements in FIFO order (oldest on top). When it's empty, pour the inbox into it — this reversal converts LIFO to FIFO order. Elements are never moved back. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

Transferring between stacks on every operation instead of only when the outbox is empty. The amortized guarantee depends on lazy transfer — move only when you must. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Stack Pattern