Question

Given..

T(0) = 3 for n <= 1

T(n) = 3T(n/3) + n/3 for n > 1

So the answer's suppose to be O(nlogn).. Here's how I did it and it's not giving me the right answer:

T(n) = 3T(n/3) + n/3

T(n/3) = 3T(n/3^2) + n/3^2

Subbing this into T(n) gives..

T(n) = 3(3T(n/3^2) + n/3^2) + n/3

T(n/3^2) = 3(3(3T(n/3^3) + n/3^3) + n/3^2) + n/3

Eventually it'll look like..

T(n) = 3^k (T(n/3^k)) + cn/3^k

Setting k = lgn..

T(n) = 3^lgn * (T(n/3^lgn)) + cn/3^lgn

T(n) = n * T(0) + c

T(n) = 3n + c

The answer's O(n) though..What is wrong with my steps?

Was it helpful?

Solution

T(n) = 3T(n/3) + n/3
T(n/3) = 3T(n/9) + n/9

T(n) = 3(3T(n/9) + n/9) + n/3
     = 9T(n/9) + 2*n/3      //statement 1

T(n/9)= 3T(n/27) + n/27
T(n)  = 9 (3T(n/27)+n/27) + 2*n/3 // replacing T(n/9) in statement 1
      =  27 T (n/27) + 3*(n/3)

T(n)  = 3^k* T(n/3^k) + k* (n/3) // eventually

replace k with log n to the base 3.

T(n)  = n T(1) + (log n) (n/3);
// T(1) = 3
T(n)  = 3*n + (log n) (n/3);
Hence , O (n* logn)

OTHER TIPS

Eventually it'll look like.. T(n) = 3^k (T(n/3^k)) + cn/3^k

No. Eventually it'll look like

T(n) = 3^k * T(n/3^k) + k*n/3

You've opened the parenthesis inaccurately.

These types of problems are easily solved using the masters theorem. In your case a = b = 3, c = log3(3) = 1 and because n^c grows with the same rate as your f(n) = n/3, you fall in the second case.

Here you have your k=1 and therefore the answer is O(n log(n))

This question can be solved by Master Theorem:
In a recursion form :
enter image description here

where a>=1, b>1, k >=0 and p is a real number, then:

  1. if a > bk, then
    first case of master theorem

  2. if a = bk

       a.) if p >-1, then 
    

2.a case of master theorem

       b.) if p = -1, then 

enter image description here

       c.) if p < -1, then 

enter image description here
3. if a < bk
a.) if p >=0, then

enter image description here
b.) if p<0, then T(n) = O(nk)

So, the above equation

   T(n) = 3T(n/3) + n/3  

a = 3, b = 3, k =1, p =0    

so it fall into 2.a case, where a = bk
So answer will be

O(n⋅log(n)) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top