Whenever I see a recursive solution, or I write recursive code for a problem, it is really difficult for me to figure out the time complexity, in most of the cases I just say its exponential? How is it exponential actually? How people say it is 2^n, when it is n!, when it is n^n or n^k.
I have some questions in mind –
- let say find all permutations of a string (O(n!))
- find all sequences which sum up to k in an array (exponential, how exactly do I calculate).
- Find all subsets of size k whose sum is 0 (will k come somewhere in complexity , it should come right?).
Can any1 help me how to calculate the exact complexity of such questions, I am able to wrote code for them, but its hard understanding the exact time complexity.
Let
F(a, n, k)be the number of all subsets ofS ⊂ {0, 1, ..., n-1}so thatThen we can compute
F(array, length of array, k)recursively by splitting the problem in two subproblems (forn > 0).The subsets of
{0, 1, ..., n-1}can be partitioned into two classes, those that containn-1and those that don’t.We obtain the recursion
Let
T(n)be the time necessary to computeF(_,n,_)(the underscores indicating thatT(n)does only depend onn, not on the array or onk[although for specific arrays andkfaster algorithms are possible]. The recursion forFthen immediately impliesfor
n > 0.For
n == 0, we can compute the solution in constant time,so we have
T(n) = 2^n * T(0)inductively.If the subsets shall not only be counted, but output, the complexity becomes
O(n * 2^n)and that bound is tight (for an array of all0s, withk == 0, all subsets meet the condition, and printing them takesΘ(n * 2^n)time).Yes, the complexity of that problem depends on
nandk.Let
F(a,n,k,s)be the number of subsetsS ⊂ {0, 1, ..., n-1}of cardinalityksuch thatFor
k == 0, we again have a constant time answer, there is one such subset (the empty set) ifs == 0, and none otherwise. Fork > nthe set{0, 1, ..., n-1}has no subsets of cardinalityk, soF(a,n,k,s) = 0ifk > n.If
0 < k <= n, we can, like above, consider the subsets containingn-1and those that don’t separately, givingand for the time complexity we find
That recursion is known from the binomial coefficients, and we have
(with
T(n,0) = 1).Once again, if the sets shall not only be counted, but output, the time complexity increases, here all sets have cardinality
k, so it becomes