GATE Computer ScienceHardGATE CS (PYQ pattern)

A queue is implemented by two stacks (enqueue pushes onto IN; dequeue pops from OUT, first moving all elements of IN to OUT if OUT is empty). The operations in order are E E E D E E D D E D E E E D D D E E (E = enqueue, D = dequeue). How many individual element moves from IN to OUT take place?

  1. A. 7
  2. B. 11
  3. C. 16
  4. D. 9

Correct answer: D. 9

OUT is empty at operations 4, 10 and 16 (the 1st, 4th and 7th dequeues), and each time IN holds 3 elements, so 3 + 3 + 3 = 9 moves occur. The two elements enqueued last never leave IN, so the answer is 9, not 11.

More Algorithms questions

Exams that ask this topic