edited by
1,258 views
7 votes
7 votes

A list of $n$ arrays, each of length $n$, is passed to an algorithm like merge-sort. The algorithm recursively divides a set of arrays into two parts until there are only two arrays.

If there are two arrays, then, as a base case, the algorithm combines or merges both in cost of $\mathrm{O}(\mathrm{p}+\mathrm{q})$ where $\mathrm{p}$ and $q$ are sizes of arrays.

What will be the time complexity recurrence relation of such algorithm?

Let $T(n)$ be time taken for $n$ arrays.

  1. $T(n)=2 T(n / 2)+n^ 2$
  2. $T(n)=2 T(n / 2)+n$
  3. $T(n)=2 T(n / 2)+n^ 3$
  4. None of these
edited by

1 Answer

4 votes
4 votes

Answer: D

Let $T(k)$ be the running time to merge $k$ arrays, where each of them has $n$ elements. We have the following recursion:
$$T(k)=2 T(k / 2)+O(k n)$$
Again, we can use the recursion tree method to solve this recursion. Also, you can observe that $n$ is independent of $k$, therefore, this is exactly similar to the recursion we saw for the running time of Merge sort, with an extra $n$ at each level. So, we have:
$$T(k)=O(n k \log k).$$

This question is inspired from one of the popular GATE PYQ: https://gateoverflow.in/1762/Gate-cse-2012-question-39

For this GATE PYQ if we put $k=n$ in the above time complexity AFTER solving reccurance then we get $$T(k)=2 T(k / 2)+O(k\times n) =O(nk \log k) =  O(n^2 \log n) $$

The amazing and important point is: We can not put $k=n$ before solving recurrence, putting $k=n$ before solving recurrence will get you the wrong answer. (You should know why it is the case if you can not understand then spend a few hours in understanding and then tag   under PYQ comment section.)

Putting $k=n$ before solving recuurance: 

$$T(k)=2 T(k / 2)+O(k\times n) \\\implies T(n)=2 T(n/ 2)+O(n^2) = O(n^2)  \color{red}{\text{ WRONG}} $$

Hence Option A is wrong here. In fact we can not write recurrence relation directly.

Answer:

Related questions

2 votes
2 votes
1 answer
3