In Gayle Laakman\'s book \"Cracking the Coding Interview\", chapter VI (Big O), example 12, the problem states that given the following Java code for computing a string\'s permu
According to your video where we have string with 3 characters (ABC
), the number of permutations is 6 = 3!
, and 6
happens to be equal to 1 + 2 + 3
. However, if we have a string with 4 characters (ABCD
), the number of permutations should be 4 * 3!
as D
could be in any position from 1 to 4. With each position of D
you can generate 3!
permutations for the rest. If you re-draw the tree and count the number of permutations you will see the difference.
According to your code, we have n! = str.length()!
permutations, but in each call of the permutations, you also run a loop from 0 to n-1. Therefore, you have O(n * n!)
.
Update in response to the edited question
Firstly, in programming, we often have either 0->n-1
or 1->n
not 0->n
.
Secondly, we don't count the number of nodes in this case as if you take a look at the recursion tree in the clip again, you will see nodes duplicated. The permutations in this case should be the number of leaves which are unique among each other.
For instance, if you have a string with 4 characters, the number of leaves should be 4 * 3! = 24
and it would be the number of permutations. However, in your code snippet, you also have a 0->n-1 = 0->3
loop in each permutation, so you need to count the loops in. Thus, your code complexity in this case is O(n *n!) = O(4 * 4!)
.