Skip to content

Solving Recurrence Relations

Let's try to solve this following recurrence:

\[ T(n) = \begin{cases} 2 \cdot T\left( \frac{n}{2} \right) + cn & \text{if } n > 1 \\ 1 & \text{if } n =1 \end{cases} \]

Info

Usually, we omit the the case of \(T(1) = 1\) but I leave it in for completeness

Also, I write \(O(n)\) as \(cn\) to make the calculations more sane.

Before we actually do anything I like unrolling partially the recursive formula.

\[ \begin{align} T(n) &= 2 \cdot T\left( \frac{n}{2} \right) + cn \\ T\left( \frac{n}{2} \right) &= 2 \cdot T\left( \frac{n}{4} \right) + \frac{cn}{2} \\ T\left( \frac{n}{4} \right) &= 2 \cdot T\left( \frac{n}{8} \right) + \frac{cn}{4} \\ \end{align} \]

First Principles

Warning

Please let me know if you have a nicer name for this, I don't see this technique being given a name.

The idea is to convert the recursive formula into an explicit one, then solve it from there.

Let's first try to have 3 expressions of \(T(n)\). We achieve this by substituting all the equations into each other.

Info

Depending on skill level you probably don't need 3 equations of \(T(n)\). You might need less (or more).

We can see we got 3 equations of \(T(n)\)

\[ \begin{aligned} T(n) &= 2 \cdot T\left( \frac{n}{2} \right) + cn \\ T(n) &= 4 \cdot T\left( \frac{n}{4} \right) + 2cn \\ T(n) &= 8 \cdot T\left( \frac{n}{8} \right) + 3cn \\ \end{aligned} \]

Now what follows is you'll try to generalise the equation for \(T(n)\) in terms of another variable (I like the variable \(x\)). If you can't see the general formula just stare harder.

The formula I came up with is:

\[ T(n) = 2^{x} \cdot T\left( \frac{n}{2^{x}} \right) + x(cn) \]

In the base case when \(T(1) = 1\), \(\frac{n}{2^{x}} = 1 \implies x = \log_{2}n\). Let's sub \(x = \log_{2}n\) into the general equation:

\[ \begin{aligned} T(n) &= 2^{\log_{2}n} \cdot T(1) + cn\log_{2}n \\ &= n + cn \log_{2} n \in O(n \log n) \end{aligned} \]

Info

It is possible to come up with a different general formula such as:

\[ T(n) = x \cdot T\left( \frac{n}{x} \right) + cn\log_{2}x \]

Recursion Tree Method

For the recursive tree, identify these 2 things, the number of subproblems and also time taken for each subproblem.

Using those information, you can draw the tree as such

You can see each row does \(cn\) work and the height is \(\log_{2}n\)

Info

You're trying to ask yourself how many times can u divide by 2 before you hit the base case.

\[ \frac{n}{2^{x}} = 1 \implies x = \log_{2}n \]

Master Theorem

If you want a faster way to solve recurrence relations, you can use the master theorem. Even though you can get the answer using the master theorem, I would encourage you to understand the methods described above to gain the intuition to why the master theorem works.