-3

Please see the code at the link below: https://stackoverflow.com/a/20614037/1676147

My thoughts:

Time complexity here would depend on two factors: 1) Number of recursive calls: O(n) where n is the number of characters in the original input string

2) The work involved in the two for loops: O(n!)?

Basically, the first for loop is iterating each string in the set 'permSet' The number of permutations for an n-character string can be n!. Thus, this set would contain n! strings. Correct?

The second for loop places one character (variable 'a' in the code) at each of the potential positions in each of these strings.

I am confused at this step.

Community
  • 1
  • 1

1 Answers1

-1

Your analysis is correct. For a string of length N, you have N-1 recursions, with string length of M, one each for lengths 1 through N-1. Each recursion deals with a list of size (M-1)!, and inserts the next character at each of M positions (0 through M-1).

Each call has time M * (M-1)!, or M! Sum these over M = 1 to N.

1! + 2! + 3! + ... + N!

This sum is O(n!).

Prune
  • 76,765
  • 14
  • 60
  • 81