GATE CS 2006 · Arrays & Matrix Representation

MCQ · 1 mark · Problem PROG-DSTR-0211

An implementation of a queue Q, using two stacks S1 and S2, 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 n insert and m (\(\le n\)) delete operations be performed in an arbitrary order on an empty queue Q, each delete being made when Q is not empty. Let x and y be the number of push and pop operations performed respectively in the process. Each option below gives bounds on x and y. Which one gives the tightest bounds that are true for all m and n?
  1. A
    \(m+n \leq x\leq 2n\) and \(2m \leq y \leq n+m\)
  2. B
    \(m+n \leq x\leq 2n\) and \(2m \leq y \leq 2n\)
  3. C
    \(2m\leq x\leq 2n\) and \(2m \leq y \leq n+m\)
  4. D
    \(2m \leq x\leq 2n\) and \(2m \leq y \leq 2n\)

Solve it on GATE DA practice →More Basic Data Structures problems

Show the worked solutionEvery element is pushed onto S1 once: \(n\) pushes. An element is moved to S2 (one pop from S1 and one push onto S2) at most once. Let t be the number of elements moved; every deleted element was moved first, so \(m \le t \le n\).\[x = n + t \;\Rightarrow\; n+m \le x \le 2n\]\[y = t + m \;\Rightarrow\; 2m \le y \le n+m\]Both ends are reached: t = m for the order (insert, delete) repeated m times and then the other inserts; t = n when all n inserts come before the first delete.Options B, C and D are also true (because \(n+m \le 2n\) and \(n+m \ge 2m\)), but their ranges are wider. Option A gives the tightest bounds.Answer: A

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com