Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve: T(n) = T(n - 1) + n

I have the following worked out:

T(n) = T(n - 1) + n = O(n^2)

Now when I work this out I find that the bound is very loose. Have I done something wrong or is it just that way?

like image 904
Tony The Lion Avatar asked May 02 '10 09:05

Tony The Lion


People also ask

What is the time complexity of recurrence relation T n )= t n 1 )+ n?

It is O(n^2) .

What is the solution to the recurrence t'n't n 2 )+ n?

this is a Geometric series with log(n) terms and each term gets halved. Hence answer is O(N).

How do you solve a recurrence equation?

These types of recurrence relations can be easily solved using Master Method. For recurrence relation T(n) = 2T(n/2) + cn, the values of a = 2, b = 2 and k =1. Here logb(a) = log2(2) = 1 = k.

What is the complexity of a recurrence relation T n 2T n 1 1?

Time Complexity =O(1).


2 Answers

You need also a base case for your recurrence relation.

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

To solve this, you can first guess a solution and then prove it works using induction.

T(n) = (n + 1) * n / 2 + c - 1

First the base case. When n = 1 this gives c as required.

For other n:

  T(n)
= (n + 1) * n / 2 + c - 1
= ((n - 1) + 2) * n / 2 + c - 1
= ((n - 1) * n / 2) + (2 * n / 2) + c - 1
= (n * (n - 1) / 2) + c - 1) + (2 * n / 2)
= T(n - 1) + n

So the solution works.

To get the guess in the first place, notice that your recurrence relationship generates the triangular numbers when c = 1:

T(1) = 1:

*

T(2) = 3:

*
**

T(3) = 6:

*
**
***

T(4) = 10:

*
**
***
****

etc..

Intuitively a triangle is roughly half of a square, and in Big-O notation the constants can be ignored so O(n^2) is the expected result.

like image 152
Mark Byers Avatar answered Sep 18 '22 12:09

Mark Byers


Think of it this way:
In each "iteration" of the recursion you do O(n) work.
Each iteration has n-1 work to do, until n = base case. (I'm assuming base case is O(n) work)
Therefore, assuming the base case is a constant independant of n, there are O(n) iterations of the recursion.
If you have n iterations of O(n) work each, O(n)*O(n) = O(n^2).
Your analysis is correct. If you'd like more info on this way of solving recursions, look into Recursion Trees. They are very intuitive compared to the other methods.

like image 44
Rubys Avatar answered Sep 17 '22 12:09

Rubys