The time complexity of recursive functions is a little different than iterative functions. The time complexity of a recursive function is determined by the "Master Theorem".
## The Master Theorem
Given a recursive relation every function of the following type:
T(n) = a*T(n/b) + f(n)
We can determine the time complexity by comparing f(n) with nlogb(a):
- If f(n) is O(nc), where cβ<βlogb(a), then the time complexity is Ξ(nlogb(a)).
- If f(n) is Ξ(ncβ *β logk(n)) where cβ=βlogb(a), (for some k β₯ 0), then time complexity is Ξ(ncβ *β log(kβ +β 1)(n))
- If f(n) is Ξ©(nc), where cβ>βlogb(a), if aβ *β f(n/b)ββ€βkβ *β f(n) for some constant k < 1 and sufficiently large n, then time complexity is Ξ(f(n)).
Letβs look at examples for each.
## Example 1:
T(n) = 2T(n/2) + n
Here, a=2, b=2, and f(n)=n. We have cβ=βlogb(a)β=βlog2(2)β=β1. In this case, f(n)β=βnβ=βnc, so we are in the second situation of the Master Theorem. Thus, the time complexity is:
$$\begin{aligned}
Ξ(n^c * log^{(k+1)}(n)) = Ξ(n * log(n))\end{aligned}$$
Here, k=0 as there no log term with f(n).
## Example 2:
T(n) = 2T(n/2) + log(n)
Again, a=2, b=2 but this time f(n)=log(n). Thus c, still 1<log(n) which means we are in the first situation of the Master Theorem. Hence, the time complexity would be Ξ(nlogb(a))β=βΞ(n).
## Example 3:
T(n) = 2T(n/2) + n^2
Here, a=2, b=2, and f(n)β=βn2. Hence cβ=β2β>βlogb(a)β=β1. Following the rules of Master theorem, we are now in the third case of the Master Theorem. For that, we must ensure that aβ *β f(n/b)ββ€βkβ *β f(n). We find that f(n/b)β=βn2/4 and aβ *β f(n/b)β=β2β *β (n2/4) which is 1/2β *β n2 that is less than n2 for sufficiently large n. Thus, the Master theorem applies here and the time complexity is Ξ(f(n))β=βΞ(n2).
Please note that the Master Theorem covers many, but not all, recurrences. There can be situations where the given form does not meet any condition of the Master Theorem.