GATE / CS ARCHIVE

GATE CSE 2022 / QUESTION 62

GATE CSE 2022 Q62

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

GATE 2022, Q62 2 marks · NAT
Report issue

Stacks & Queues

Question 62, GATE 2022: Q1 initially contains four elements in front-to-back order 1,2,3,4 and Q2 is empty. Only Enqueue and Dequeue on either queue are permitted, with no extra storage. End with Q1 empty and Q2 front-to-back 4,3,2,1. What minimum number of Enqueue operations on Q1 is necessary?
Tap to enlarge
Answer & solution

Official answer: 0

No enqueue into Q1 is necessary. Move its front item to Q2, then rotate Q2 by moving each of its previously present items from front to back. Starting with Q2 empty, the successive states after these steps are [1], [2, 1], [3, 2, 1], [4, 3, 2, 1]. Each insertion is Enqueue(Q2, Dequeue(Q1)), and rotations are Enqueue(Q2, Dequeue(Q2)); Q1 is never enqueued. Since the count cannot be negative, the minimum is 0. As in the allowed operation model, a dequeued value can be passed directly to enqueue without an auxiliary storage data structure.

Construction using only queue operations: after transferring item k from Q1 to Q2, rotate Q2 exactly k−1 times by Enqueue(Q2,Dequeue(Q2)). Before rotation Q2=[k−1,…,1,k], and afterward [k,k−1,…,1]. Induction establishes reversal after four transfers. The rotations cost enqueues on Q2, which the objective does not count.

Original paper, page 40 · Answer key