Hi all, I wrote some code to generate all permutations of a string. I am trying to determine the big (O) of my code.
I took at look at some solutions online and they took a different approach than I did.
Here is my code
const insert_at_each_index = (letter, perms) => {
const ans = [];
for (let i = 0; i < perms.length; i++) {
const perm = perms[i];
let j = 0;
for (let j = 0; j <= perm.length; j++) {
const first_chunk = perm.substring(0, j);
const last_chunk = perm.substring(j);
ans.push(`${first_chunk}${letter}${last_chunk}`);
}
}
return ans;
};
const perms = (s) => {
if (s.length === 1) {
return [s];
}
const first = s[0];
const rest = s.substring(1);
const rest_perms = perms(rest);
const ans = insert_at_each_index(first, rest_perms);
return ans;
};
Basically my approach was a recursive one:
- for a given string split the string into first letter and rest of the letters
- calculate all the permutations for the rest of the letters
- insert the first letter at every position possible in every permutation of the rest of the letters
- the result is all possible permutations of the given string
I have no idea how to determine the time complexity of this. And it looks like my approach was different than most of the solutions online. Can anyone help me out?
Thanks!