Skip to content
Official PYQ · 2016

GATE CS 2016 Set 1 Q41 — Arrays, Stacks and Queues

Explain with AI

Let QQ denote a queue containing sixteen numbers and SS be an empty stack. Head(Q)Head(Q) returns the element at the head of the queue QQ without removing it from QQ. Similarly Top(S)Top(S) returns the element at the top of SS without removing it from SS. 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 _______.

View worked solution

Answer: 256

The given algorithm sorts the elements of the queue QQ into the stack SS in ascending order (with the largest element at the top of SS). To find the maximum possible number of iterations of the while loop, we consider the worst-case input, which occurs when the queue QQ is initially sorted in descending order: Q=[n,n−1,ext…,1]Q = [n, n-1, ext{…}, 1].

Let kk be the number of elements currently sorted in the stack SS. When we want to insert the next element from QQ (which is smaller than all elements currently in SS):

  1. We must pop all kk elements from SS and enqueue them back to QQ to reach the bottom of the stack. This takes kk iterations (each performing a Pop and Enqueue).
  2. We then dequeue the new smallest element from QQ and push it onto the empty stack SS. This takes 11 iteration.
  3. Finally, we must move the kk elements back from QQ to SS. Since they are already sorted and larger than the top of SS, they are pushed directly. This takes kk iterations (each performing a Dequeue and Push).

Thus, the number of iterations required to insert the (k+1)(k+1)-th element is: T(k+1)=k+1+k=2k+1T(k+1) = k + 1 + k = 2k + 1

Summing this cost for all nn elements (from k=0k = 0 to n−1n-1): Total Iterations=∑k=0n−1(2k+1)=n2\text{Total Iterations} = \sum_{k=0}^{n-1} (2k + 1) = n^2

For n=16n = 16 elements, the maximum possible number of iterations is: 162=25616^2 = 256

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

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