def permutation(str): #str = string input
if len(str) == 0:
return [""]
result = []
for i, char in enumerate(str):
for p in permutation(str[:i] + str[i + 1 :]):
result.append(char + p)
return result
I am confused in asymptotic analysis (time complexity) in this code does it have an O(n!) or O(n*n!) because the recursive call is in the loop. I am still confused does the big O notation only based on regular notation like logarithmic, linear, quadratic, exponential, factorial, etc. Or could beyond that like a combination not only based on the regular notation
I already tried to calculate it and see some explanation in youtube but still couldn't understand well.
Let the time complexity of the function be
T(n), wherenis the length of the input string.For the case where
nis not 0, we need to consider the following parts:For the outer loop, it needs to be repeated
ntimes.For the outer loop body, the time complexity of each recursive call is
T(n - 1). (I omitted theO(n)time complexity of constructing the input, considering thatT(n - 1)is at least(n - 1)!, which should not affect the results.)For inner loop, since the output size of the permutation is
n!, it needs to be repeated(n - 1)!times (the input length for recursive calls isn - 1).For the inner loop body, due to the length of
pbeingn - 1, the time complexity ofchar + pisO(n).In summary, we can conclude that: