HR Write-up: A Tale of Two Stacks

Can you efficiently emulate a queue with two stacks?

HR Write-up: A Tale of Two Stacks

Problem

Queues: A Tale of Two Stacks | HackerRank
Create a queue data structure using two stacks.

Solution

We can say that A is emulating B if and only if the outputs from A and B are always the same. So, how to emulate a queue with two stacks? The answer is simple: use one of the stacks as a temporary buffer and we pop elements from it and push to another stack. This way, the output orders of the queue and the second stack become the same.

We should minimize the times of transferring elements from stack 1 to stack 2. With that in mind, a sequence of operations should be carried out as shown in the picture below.