The GATE Grind

GATE 2016 CS – Question 51

Programming and Data Structures · Stacks and Queues · 2 marks · Numerical answer

Let $Q$ denote a queue containing sixteen numbers and $S$ be an empty stack. $\texttt{Head}(Q)$ returns the element at the head of the queue $Q$ without removing it from $Q$. Similarly $\texttt{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 ________.

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 256

Explanation

Each iteration either moves the head of the queue onto the stack or moves the top of the stack back to the end of the queue, so the numbers keep circulating until the stack can take them in order. For 16 numbers in the worst arrangement, each of the 16 numbers can be moved at most 16 times, which gives $16 \times 16 = 256$ iterations. This matches the official key.