Algorithms | Analysis of Algorithms (Recurrences) | Question 3
What is the worst case time complexity of following implementation of subset sum problem.
(sum == 0)
(n == 0 && sum != 0)
(set[n-1] > sum)
isSubsetSum(set, n-1, sum);
isSubsetSum(set, n-1, sum) ||
isSubsetSum(set, n-1, sum-set[n-1]);
(A) O(n * 2^n)
(C) O(n^2 * 2^n)
Explanation: Following is the recurrence for given implementation of subset sum problem
T(n) = 2T(n-1) + C1
T(0) = C1
Where C1 and C2 are some machine specific constants.
The solution of recurrence is O(2^n)
We can see it with the help of recurrence tree method
/ \ / \
T(n-2) T(n-2) T(n-2) T(n-2)
/ \ / \
C1 C1 C1 C1
/ \ / \ / \ / \
If we sum the above tree level by level, we get the following series
T(n) = C1 + 2C1 + 4C1 + 8C1 + ...
The above series is Geometrical progression and there will be n terms in it.
So T(n) = O(2^n)
Quiz of this Question