GATE CS 2016 · Set-1 · Arrays & Matrix Representation

NAT · 2 marks · Problem PROG-DSTR-0131

Let Q denote a queue containing sixteen numbers and S be an empty stack. Head(Q) returns the element at the head of the queue Q without removing it from Q. Similarly Top(S) returns the element at the top of S without removing it from S. Consider the algorithm given below.
while Q is not Empty do
    if S is Empty OR Top(S) <= Head(Q) then
        x := Dequeue(Q);
        Push(S, x);
    else
        x := Pop(S);
        Enqueue(Q, x);
    end
end
The maximum possible number of iterations of the while loop in the algorithm is .

Numerical answer (NAT).

Solve it on GATE DA practice →More Basic Data Structures problems

Show the worked solution\[\boxed{\text{iterations} = n + 2\times(\text{number of pops}) \le n + 2\cdot\frac{n(n-1)}{2} = n^2}\]Each iteration either moves the head of Q onto S or moves the top of S back to the rear of Q. Every number ends on S, so there are \(n\) final pushes; each pop puts a number back in Q, and it costs one more push later.A number x is popped only when a smaller number y is at the head of Q, and after that y lies below x in S for good, so each pair \(y \lt x\) causes at most one pop: at most \(\dfrac{n(n-1)}{2}\) pops, and at most \(n^2\) iterations.A strictly decreasing queue (16, 15, ..., 1) reaches this bound: \(16^2 = 256\) iterations.Answer: 256

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com