Master Theorem Examples

Let’s understand examples related to the master theorem.. We’ll solve some examples from each case.

Examples

The following are some examples of the master theorem. Let’s look at them one by one.

Example 1

This is the case of merge sort. Its time complexity is T(n)T(n) = 2T(n/2)2 T(n/2) + nn.

Solution

In this example, aa and bb are both equal to 2. So, logbalog_ba = log22log_22 = 1 which means that f(n)f(n) = n = Θ(nlog22.log0n)\Theta(n^{log_22}.log^0n). That means case 2 is applied and T(n)T(n) = Θ(nlog22.log0+1n)\Theta(n^{log_22}.log^{0+1}n). Its final time complexity is T(n)T(n) = Θ(n.log(n))\Theta(n.log(n)).

Example 2

This is a case of binary search. Its time complexity is T(n)T(n) = T(n/2)T(n/2) + kk.

Solution

In this example, aa is equal to 1 and bb is equal to 2. So, logbalog_ba = log21log_21 = 0 which means that f(n)f(n) = k = Θ(nlog21.log0n)\Theta(n^{log_21}.log^0n). That means case 2 is applied and T(n)T(n) = Θ(nlog21.log0+1n)\Theta(n^{log_21}.log^{0+1}n). Its final time complexity is T(n)T(n) = Θ(log(n))\Theta(log(n)).

Example 3

This is a case of binary tree traversal. Its time complexity is T(n)T(n) = 2T(n/2)T(n/2) + kk.

Solution

In this example, aa is equal to 2 and bb is also equal to 2. So, logbalog_ba = log22log_22 = 1 which means that f(n)f(n) = k = O(nlog221)O(n^{log_22-1}). That means case 1 is applied and T(n)T(n) = Θ(nlog22)\Theta(n^{log_22}). Its final time complexity is T(n)T(n) = Θ(n)\Theta(n).

Example 4

In this example, an algorithm has a time complexity of T(n)T(n) = 2T(n/2)T(n/2) + n2n^2.

Solution

In this example, aa is equal to 2 and bb is also equal to 2. So, logbalog_ba = log22log_22 = 1 which means that f(n)f(n) = n2n^2 = Ω(nlog22+1)\Omega(n^{log_22+1}). That means case 3 is applied and T(n)T(n) = Θ(f(n))\Theta(f(n)). Its final time complexity is T(n)T(n) = Θ(n2)\Theta(n^2).

Get hands-on with 1400+ tech skills courses.