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 The maximum possible number of iterations of the while loop in the algorithm is ___.
GATE 2016 · Programming and Data Structures · Queue · medium
Answer: The maximum possible number of iterations of the while loop is 256.
- Identify the worst-case input: If Q = [16, 15, 14, ..., 2, 1], each new element to be pushed is smaller than all elements currently on S, so all current stack elements must be popped back to Q before the new element can be pushed. This maximizes the number of Pop operations.
- Count push iterations: Element 16 is pushed first: 0 pops before it. Element 15: top(S)=16 > 15, so 1 pop, then 15 is pushed. That popped 16 re-enters Q and will be pushed again later. In general, when we get to process element k (in decreasing order), there are already (16-k) elements on S all larger than k, so (16-k) pops occur before k is pushed. For k=16: 0 pops. For k=15: 1 pop. ... For k=1: 15 pops. Total pops = 0+1+2+...+15 = 120. Total pushes = 16 + 120 = 136.
- Count total iterations: Each while-loop iteration does exactly one operation (either push or pop). Total = 136 + 120 = 256.