GATE CSE
First time here? Checkout the FAQ!
x
+2 votes
50 views

 

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??

asked in Algorithms by Veteran (13.1k points)   | 50 views

1 Answer

+1 vote
Best answer

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)

answered by Active (1.8k points)  
selected by


Top Users May 2017
  1. akash.dinkar12

    3598 Points

  2. pawan kumarln

    2314 Points

  3. Bikram

    1958 Points

  4. Arjun

    1942 Points

  5. sh!va

    1682 Points

  6. Debashish Deka

    1296 Points

  7. Devshree Dubey

    1282 Points

  8. Arunav Khare

    1122 Points

  9. Angkit

    1072 Points

  10. LeenSharma

    1028 Points

Monthly Topper: Rs. 500 gift card
Top Users 2017 May 29 - Jun 04
  1. Arjun

    292 Points

  2. Arunav Khare

    246 Points

  3. Rupendra Choudhary

    116 Points

  4. Arnab Bhadra

    108 Points

  5. pawan kumarln

    108 Points


22,912 questions
29,252 answers
65,411 comments
27,750 users