GATE / CS ARCHIVE

GATE CSE 2001 / QUESTION 2.16

Implementing a queue with stacks

Data Structures · Stacks & Queues · Full GATE CSE 2001 paper

GATE 2001, Q2.16 2 marks · MCQ
Report issue

Stacks & Queues

Question 2.16, GATE 2001: Under the usual stack-only auxiliary-storage model, what is the minimum number of size-n stacks needed to implement a size-n queue: one, two, three, or four?
Tap to enlarge
Your answer
Answer & solution

Answer: B under the standard auxiliary-storage model (no official key was published)

Step 1: Push new elements onto an input stack. To dequeue, pop from an output stack; when that stack is empty, move all input elements to it. The reversal places the oldest element on top, so two stacks suffice.

Step 2: With only one LIFO stack and O(1) other element storage, reaching the oldest of n elements requires removing and retaining n−1 newer elements somewhere, so the usual general implementation needs the second stack.

Hence B in this model. A recursive “one explicit stack” implementation uses the call stack as another unbounded stack; allowing an auxiliary array or such hidden storage changes what is being counted.

Original paper, page 6