Solving the recurrence relation T(n) = 2T(n/2)+1 with recursion

Viewed 1333

I'm trying to find the big O of T(n) = 2T(n/2) + 1. I figured out that it is O(n) with the Master Theorem but I'm trying to solve it with recursion and getting stuck.

My solving process is

T(n) = 2T(n/2) + 1 <= c * n
(we know that T(n/2) <= c * n/2) 
2T(n/2) + 1 <= 2 * c * n/2 +1 <= c * n
Now I get that 1 <= 0.
I thought about saying that 
T(n/2) <= c/2 * n/2 

But is it right to do so? I don't know if I've seen it before so I'm pretty stuck.

1 Answers

I'm not sure what you mean by "solve it with recursion". What you can do is to unroll the equation.

So first you can think of n as a power of 2: n = 2^k.
Then you can rewrite your recurrence equation as T(2^k) = 2T(2^(k-1)) + 1.

Now it is easy to unroll this:

T(2^k) = 2 T(2^(k-1)) + 1
       = 2 (T(2^(k-2) + 1) + 1
       = 2 (2 (T(2^(k-3) + 1) + 1) + 1
       = 2 (2 (2 (T(2^(k-4) + 1) + 1) + 1) + 1
       = ... 

This goes down to k = 0 and hits the base case T(1) = a. In most cases one uses a = 0 or a = 1 for exercises, but it could be anything.

If we now get rid of the parentheses the equation looks like this:

T(n) = 2^k * a + 2^k + 2^(k-1) + 2^(k-2) + ... + 2^1 + 2^0

From the beginning we know that 2^k = n and we know 2^k + ... + 2 + 1 = 2^(k+1) -1. See this as a binary number consisting of only 1s e.g. 111 = 1000 - 1.

So this simplifies to

T(n) = 2^k * a + 2^(k+1) - 1 
     = 2^k * a + 2 * 2^k - 1 
     = n * a + 2 * n - 1 
     = n * (2 + a) - 1

And now one can see that T(n) is in O(n) as long as a is a constant.

Related