Skip to content
Official PYQ · 2006

GATE CS 2006 Q49 — Arrays, Stacks and Queues

Explain with AI

An implementation of a queue QQ, using two stacks S1S1 and S2S2, is given below: 

void insert (Q, x) { 
    push (S1, x); 
} 
void delete (Q) { 
    if (stack-empty(S2)) then 
        if (stack-empty(S1)) then { 
            print(“Q is empty”); 
            return; 
        } 
        else while (!(stack-empty(S1))){ 
            x=pop(S1); 
            push(S2,x); 
        } 
    x=pop(S2);
}

Let nn insert and m(≤n)m(\leq n) delete operations be performed in an arbitrary order on an empty queue QQ. Let xx and yy  be the number of push and pop operations  performed respectively in the process. Which one of the following is true for all mm and nn?

Choose one option
View worked solution

Answer: A

To find the number of push operations (xx) and pop operations (yy), let us track the movement of elements between the two stacks S1S1 and S2S2:

  1. Push Operations (xx):
    • Each of the nn insert operations performs exactly 11 push onto S1S1. This contributes nn pushes.
    • During the mm delete operations, some kk elements are transferred from S1S1 to S2S2. Each transferred element requires 11 push onto S2S2.
    • Since mm successful deletes are performed, at least mm elements must be transferred to S2S2, so k≥mk \ge m.
    • Since only nn elements are ever inserted, at most nn elements can be transferred, so k≤nk \le n.
    • Thus, the total number of pushes is x=n+kx = n + k. Since m≤k≤nm \le k \le n, we have: n+m≤x≤2nn + m \le x \le 2n
  2. Pop Operations (yy):
    • The kk elements transferred from S1S1 to S2S2 must be popped from S1S1. This contributes kk pops.
    • Each of the mm delete operations pops exactly 11 element from S2S2. This contributes mm pops.
    • Thus, the total number of pops is y=k+my = k + m. Since m≤k≤nm \le k \le n, we have: 2m≤y≤n+m2m \le y \le n + m

Combining these bounds, we get n+m≤x≤2nn+m \le x \le 2n and 2m≤y≤n+m2m \le y \le n+m, which matches Option A.

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

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