edited by
522 views
3 votes
3 votes

Consider the function given below ?

Assume T(0) = 0

int fun( int n )
{
    if ( n <= 0 ) return 0;
    int i = random( n - 1 );
    return fun(i) + fun(n - i - 1);
}


random(n) returns an integer in the range [0, n] in constant time

What is the time complexity of the above function?

  1. $\Theta (n^{2})$  
  2. $\Theta (n)$
  3. $\Theta (n\log n)$
  4. None
edited by

1 Answer

Best answer
1 votes
1 votes
Recurrence relation for this is

$T\left ( n \right )=\left\{\begin{array}  {lcl} T(n -1)+T(1)+1 & \text{if} \; n>0\\1 & \text{if}\; n=0 \end{array}\right. $

In the worst case, the random function gives $0 \text { or } n$ in each call.

So, time complexity of this recurrence is $T(n) = \Theta (n)$
selected by

Related questions

1 votes
1 votes
2 answers
1
Nitesh_Yadav asked Apr 11, 2022
275 views
What is the time complexity of the below mentioned recursive function.int f(n){ if(n!=1){ return f(n/2)+f(n/2);}elsereturn 10;} O(n)O(n^2)O(log n)O(n logn)
64 votes
64 votes
8 answers
2
Kathleen asked Sep 21, 2014
26,649 views
In the following C function, let $n \geq m$.int gcd(n,m) { if (n%m == 0) return m; n = n%m; return gcd(m,n); }How many recursive calls are made by this function?$\Theta(\...