379 views
2 votes
2 votes

Consider the following program

foo(n)
{
  if (n == 1)
     P(n)
          else 
     Q() + foo(n-1); 
}


What is the time complexity for the given function, if the function ‘P’ and function ‘Q’ take O(n) and O(1) unit of time respectively.

  1.   O(n)
  2.   O(n2)
  3.   O(nlogn)
  4.   O(logn)

---------------------------------------------------------------------

T(n) =T(n-1) + C

T(n)= T(n-2) + c +c

T(n) =T(n-k) + c +c + c.......k times

put n-k =1

so,T(n) =O(n) +K*C       (T(1) =O(n))

hence,T(n) =O(n) +N-1*C

so,T(n) = O(n)

is this correct??

1 Answer

Best answer
1 votes
1 votes

Here for Base Case i.e., T(1) = O(n) ($\because$ it is given that P takes O(n) time)

In the statement Q() + foo(n-1) ===> Q() takes O(1) time.

So the recurrence relation is,

T(n) = T(n-1) + 1

     = T(n-2) +1 +1

        ...

     =T(n-k) + k

    =O(n) + n-1

which gives O(n)

selected by

Related questions

0 votes
0 votes
0 answers
1
Naveen Kumar 3 asked Nov 3, 2018
969 views
Suppose, we have an array of n elements. find the time complexity to search two elements x, y such that:-a) x+y < 100b) x+y 1000Also, state the algorithm/approach for th...
1 votes
1 votes
1 answer
2
Akriti sood asked Jan 23, 2017
1,308 views
What is the time complexity of the following function foo() void foo() { int i, j; for(i = 1; i <= n ; i++) for(j = i; j <= log(i); j++) printf(“gate”); } what is the...
2 votes
2 votes
1 answer
3
1 votes
1 votes
0 answers
4