Loading section...

Queue from Two Stacks: Amortized O(1)

Concepts: pyQueueFromStacks, pyAmortized

This is a classic design problem with a trick that looks expensive but is not: implement a FIFO queue using only two stacks. The trick: use one stack for enqueuing ('inbox') and one for dequeuing ('outbox'). When you need to dequeue but the outbox is empty, pour the entire inbox into the outbox (reversing the order). This costs O(n) for that one operation but every element is moved at most once total, making the amortized cost O(1) per operation. Explaining Amortized O(1) Out Loud The interviewer will ask: 'Isn't the pop operation O(n) when we refill?' Your answer: 'The _refill is O(n) in the worst case for that single call. But each element can only be transferred from inbox to outbox once. So if we push n elements, the total cost of all refill operations is O(n) spread across all n deque