Skip to content
Official PYQ · 2022

GATE CS 2022 Q52 — Arrays, Stacks and Queues

Explain with AI

Consider the queues Q1Q_{1} containing four elements and Q2Q_{2} containing none (shown as the Initial State\textsf{Initial State} in the figure). The only operations allowed on these two queues are Enqueue (Q, element)\textsf{Enqueue (Q, element)} and Dequeue (Q).\textsf{Dequeue (Q)}. The minimum number of Enqueue\textsf{Enqueue} operations on Q1Q_{1} required to place the elements of Q1Q_{1} in Q2Q_{2} in reverse order (shown as the Final State\textsf{Final State} in the figure) without using any additional storage is________________.

 

View worked solution

Answer: 0

We can reverse the elements of Q1Q_1 into Q2Q_2 using 00 Enqueue operations on Q1Q_1. This is achieved by systematically transferring elements from Q1Q_1 to Q2Q_2 and rotating Q2Q_2 using only its own Enqueue and Dequeue operations.

Let the initial state of Q1Q_1 be [1,2,3,4][1, 2, 3, 4] (where 11 is at the front and 44 is at the rear) and Q2Q_2 be empty [][]. We want the final state of Q2Q_2 to be [4,3,2,1][4, 3, 2, 1] (where 44 is at the front and 11 is at the rear).

The step-by-step process is as follows:

  1. Insert 1st element:
    • Dequeue(Q1)→1\text{Dequeue}(Q_1) \to 1, Enqueue(Q2,1)\text{Enqueue}(Q_2, 1). Now, Q2=[1]Q_2 = [1].
  2. Insert 2nd element and rotate:
    • Dequeue(Q1)→2\text{Dequeue}(Q_1) \to 2, Enqueue(Q2,2)\text{Enqueue}(Q_2, 2). Now, Q2=[1,2]Q_2 = [1, 2].
    • Dequeue(Q2)→1\text{Dequeue}(Q_2) \to 1, Enqueue(Q2,1)\text{Enqueue}(Q_2, 1). Now, Q2=[2,1]Q_2 = [2, 1].
  3. Insert 3rd element and rotate:
    • Dequeue(Q1)→3\text{Dequeue}(Q_1) \to 3, Enqueue(Q2,3)\text{Enqueue}(Q_2, 3). Now, Q2=[2,1,3]Q_2 = [2, 1, 3].
    • Dequeue(Q2)→2\text{Dequeue}(Q_2) \to 2, Enqueue(Q2,2)\text{Enqueue}(Q_2, 2). Now, Q2=[1,3,2]Q_2 = [1, 3, 2].
    • Dequeue(Q2)→1\text{Dequeue}(Q_2) \to 1, Enqueue(Q2,1)\text{Enqueue}(Q_2, 1). Now, Q2=[3,2,1]Q_2 = [3, 2, 1].
  4. Insert 4th element and rotate:
    • Dequeue(Q1)→4\text{Dequeue}(Q_1) \to 4, Enqueue(Q2,4)\text{Enqueue}(Q_2, 4). Now, Q2=[3,2,1,4]Q_2 = [3, 2, 1, 4].
    • Dequeue(Q2)→3\text{Dequeue}(Q_2) \to 3, Enqueue(Q2,3)\text{Enqueue}(Q_2, 3). Now, Q2=[2,1,4,3]Q_2 = [2, 1, 4, 3].
    • Dequeue(Q2)→2\text{Dequeue}(Q_2) \to 2, Enqueue(Q2,2)\text{Enqueue}(Q_2, 2). Now, Q2=[1,4,3,2]Q_2 = [1, 4, 3, 2].
    • Dequeue(Q2)→1\text{Dequeue}(Q_2) \to 1, Enqueue(Q2,1)\text{Enqueue}(Q_2, 1). Now, Q2=[4,3,2,1]Q_2 = [4, 3, 2, 1].

Throughout this entire process, we only performed Dequeue\text{Dequeue} operations on Q1Q_1. No Enqueue\text{Enqueue} operations were performed on Q1Q_1. Thus, the minimum number of Enqueue\text{Enqueue} operations on Q1Q_1 is 0.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Arrays, Stacks and Queues questions