GATE / CS ARCHIVE

GATE CSE 2016 SET 1 / QUESTION 41

GATE CSE 2016 Set 1 Q41

Data Structures · Stacks & Queues · Full GATE CSE 2016 Set 1 paper

GATE 2016 Set 1, Q41 2 marks · NAT
Report issue

Stacks & Queues

Question 41, GATE 2016: Initially queue Q holds 16 numbers and stack S is empty. Head and Top inspect without removing. Repeat while Q is nonempty: if S is empty or Top(S)≤Head(Q), dequeue Q's head and push it on S; otherwise pop S's top and enqueue it at Q's tail. What is the maximum number of loop iterations?
Tap to enlarge
Answer & solution

Official answer: 256.0 : 256.0

Our answer: 256

Let F(n) be the maximum number of loop iterations with n queued values and no relevant stack entries. Until a minimum queued value is pushed, each value originally preceding that minimum is pushed at most once and popped at most once: popped items return behind the minimum. Thus this phase costs at most 2n−1 iterations. Once the minimum is pushed it never pops, leaving at most n−1 values to process above it. Hence F(n)≤2n−1+F(n−1), giving F(n)≤n². A strictly descending initial queue attains equality at each phase, because all preceding values are pushed and popped and return in descending order behind the minimum. Therefore F(16)=256.

Each loop iteration moves one item either from Q to S or from S to Q. For a descending input 16,15,...,1, the first phase moves 15 earlier values onto the stack and back off before finally pushing 1:31 moves. That 1 never leaves, and the remaining values are again descending, giving phases 29,27,...,1. Their sum is 162=256. The upper-bound argument counts at most one push and one pop before the next minimum is fixed, so the example achieves the maximum rather than merely a large runtime.

Original paper, page 16 · Answer key