I wrote this solution of the all permutations of string. I have a question about time and space complexity of this solution. I am assuming that time complexity will be O(n³) since nested loop and recursion and space complexity will be O(n) because of recursion.
Is my assumption correct? If so, is there any better performance solution?
https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
Input: "ABC"
Output: [ 'ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA' ]
Thanks!
function permutation(string) {
// Basecase
if (string.length < 2) {
return string;
}
var permutations = []; // This array will hold our permutations
for (var i = 0; i < string.length; i++) {
var char = string[i];
// Cause we don't want any duplicates:
// if char is not matched, skip it this time
// otherwise it will generate duplicated string
if (string.indexOf(char) != i) {
continue;
}
var remainingString = string.slice(0,i) + string.slice(i+1,string.length);
var tempResult = permutation(remainingString)
for (var subPermutation of tempResult) {
var result = char + subPermutation
permutations.push(result)
}
}
return permutations;
}
console.log(permutation('ABC'))