Skip to content
Official PYQ · 2006

GATE CS 2006 Q53 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Consider the following C-function in which a[n]a[n] and b[m]b[m] are two sorted integer arrays and c[n+m]c[n+m] be another integer array,

void xyz(int a[], int b [], int c []){ 
    int i,j,k; 
    i=j=k=0; 
    while ((i<n) && (j<m)) 
        if (a[i] < b[j]) c[k++] = a[i++]; 
        else c[k++] = b[j++]; 
}

Which of the following condition(s) hold(s) after the termination of the while loop?

  1. j<m,k=n+j−1j< m,k=n+j-1 and a[n−1]<b[j]a[n-1]< b[j] if i=ni=n
  2. i<n,k=m+i−1i<n,k=m+i-1 and b[m−1]≤a[i]b[m-1]\leq a[i] if j=mj=m
Choose one option
View worked solution

Answer: D

To determine which conditions hold after the termination of the while loop, we can analyze the loop variables ii, jj, and kk.

In every iteration of the loop, exactly one of ii or jj is incremented, and kk is always incremented. Since all three variables are initialized to 00, the loop invariant relation is:

k=i+jk = i + j

Let's evaluate the two cases upon loop termination:

  • Case 1: i=ni = n (and j<mj < m)
    Substituting i=ni = n into our invariant gives k=n+jk = n + j. Statement (i) claims that k=n+j−1k = n + j - 1, which is incorrect.
  • Case 2: j=mj = m (and i<ni < n)
    Substituting j=mj = m into our invariant gives k=m+ik = m + i. Statement (ii) claims that k=m+i−1k = m + i - 1, which is also incorrect.

Since the relation for kk is incorrect in both statements, neither condition (i) nor (ii) holds true upon termination.

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

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions