🧩 Objective
Write a recursive method for generating all permutations of an input string. Return them as a set.
See: Recursive String Permutations - Interview Cake
🔎 Questions
1: How does the problem change if the string can have duplicate characters?
- The solution below works with duplicate characters because the index of the original input is used to generate unique combinations of the original input minus the character at the given index. Therefore, there may be duplicate characters, however, their unique indexes will generate the correct solution.
2: What is the space and time complexity?
Time Complexity: \$O(n^2)\$ because there is one iteration through the input for which index to examine, and a second iteration, placing the character at each position of the input to generate various combinations. Therefore, \$n x n\$. This follows the rule, do X for each time of Y. See: Time complexity of all permutations of a string - GeeksforGeeks
Space Complexity: Is the space complexity also quadratic \$O(n^2)\$ because the unique permutations stored in a Set would grow quickly based on the size of the initial input?
3: How to optimize the time and space complexity?
Time Complexity: I do not see further time complexity optimizations.
Space Complexity: I do not see further space complexity optimizations because the solution syntactically is recursive, but performs iteratively. The recursive part of the code,
allPerm
performs after each iteration through the input. Therefore, there are no methods saved onto the JVM's call stack.
🚀 Code
- Iterate through each char and move the char to each position of the input String.
- Add each version to a
Set
.
fun allPerm(input: String, lookAtIndex: Int, set: HashSet<String>): HashSet<String> {
if (lookAtIndex <= input.length - 1) {
for (i in 0 .. input.length - 1) {
val combo = input.substring(0, lookAtIndex) +
input.substring(lookAtIndex + 1)
set.add(combo.substring(0, i) + input.get(lookAtIndex) +
combo.substring(i))
}
allPerm(input, lookAtIndex + 1, set)
}
return set
}
See: GitHub
abcdefghijklmnopqrstuvwxyz
and think about how many different combinations that will return. Then consider if this is more than, less than, or equal toO(n^2)
. \$\endgroup\$aaaaaaaaaaaaaaaaaaaaaa
and think about how many different combinations that will return. Now consider if you can make any performance improvement. \$\endgroup\$abc
? Does it add the permutationcba
to the set for that input? \$\endgroup\$cba
. I'll add that to the test and begin debugging to understand whycba
is not covered in the algorithm. \$\endgroup\$