Question
Let denote a queue containing sixteen numbers and be an empty stack. returns the element at the head of the queue without removing it from . Similarly returns the element at the top of without removing it from . 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 _____.
Official answer and solution
- Official answer
- 256
- From
- Official GATE 2016 answer key
Solution
Model the algorithm as an insertion process that maintains elements sorted on the stack, and identify the worst-case initial order of the queue.
The algorithm processes elements using a queue and stack :
- If is empty or , the front element of is dequeued and pushed onto .
- If , the top element of is popped and appended back to the tail of .
This mechanism simulates sorting: elements on stack are kept in non-decreasing order from bottom to top. When a new element from is smaller than , all elements on that are strictly greater than that element must be popped back into before the smaller element can be placed on .
The worst case occurs when the queue initially contains elements in strictly decreasing order: , where .
- For the first element : is empty, so is dequeued and pushed to ( iteration). .
- For the second element ():
- is popped from and enqueued to ( iteration).
- is now empty is dequeued from and pushed to ( iteration).
- Now is dequeued and pushed to ( iteration).
Total iterations to insert when 1 element was on the stack: iterations. Cumulative iterations for 2 elements: .
In general, when elements are already sorted on and the next element at the front of is smaller than all of them:
- It takes iterations to pop all elements from into .
- It takes iteration to dequeue the new element and push it onto the empty stack .
- It takes iterations to dequeue each of the elements back from and push them onto .
Thus, placing the -th element takes iterations.
Summing over all elements from to :
For elements:
256
Miscounting the loop iterations by considering only the push operations () or neglecting that popped elements must be re-dequeued back into the stack.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2016 Computer Science and Information Technology (CS) Session 1
- Question
- 51 of 65, printed as CS Q.41
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.