Queue Using Two Stacks
A Queue can be implemented using two Stacks by using one stack for incoming elements and another for outgoing elements. When Dequeue is requested and the output stack is empty, elements are transferred from the input stack to reverse their order, producing FIFO behavior.
Enqueue is O(1).
A single Dequeue can be O(n) when transfer is required.
Dequeue is amortized O(1) because each element moves from input to output at most once.
Auxiliary space is O(n).
This is a classic example of amortized analysis.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience