WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Coding Interview Essentials Β· Time and Space Complexity Analysis Β· question 23 of 120

How do you determine the time complexity of a recursive function?

πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview β€” then scores it.
πŸ“ž Practice Coding Interview Essentials β€” free 15 min
πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

All 120 Coding Interview Essentials questions Β· All topics