What is the minimum number of stacks of size required to implement a queue of size ?
View worked solution
Answer: B
To implement a queue (which follows First-In-First-Out or FIFO order) using stacks (which follow Last-In-First-Out or LIFO order), we need to reverse the order of the elements.
- With one stack: We cannot reverse the order of elements dynamically to support both enqueue and dequeue operations in a FIFO manner. Thus, one stack is insufficient.
- With two stacks ( and ): We can successfully simulate a queue of size :
- Enqueue: Push the incoming element onto .
- Dequeue: If is empty, pop all elements from and push them one by one into (this reverses their order, making the oldest element sit at the top of ). Then, pop the top element from . If is not empty, simply pop the top element from .
Since the maximum number of elements in the queue at any time is , two stacks of size are sufficient to handle all operations without overflow.
Therefore, the minimum number of stacks required is two.
Free practice · Your answers on this page are not saved.
