String permutations using recursion.

This technical problem deals with how to print all possible permutations of a given string using recursion. For example, if the input string is "abc", the output would be all six possible permutations of the string: "abc", "acb", "bac", "bca", "cab", and "cba".

Problem

Print all possible permutations of a given string.
Example input:
"abc"
Example output:
"abc"
"acb"
"bac"
"bca"
"cab"
"cba"

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The optimal solution is to use recursion.
// The base case is when the string is empty.
// The recursive case is when the string is not empty.
// In the recursive case, we loop through the string and for each character, we add it to the beginning of the string and call the function recursively.
// We then remove the character from the beginning of the string and continue the loop.
// This solution is optimal because it is O(n!) time complexity.

function permutations(str) {
  if (str.length === 0) {
    return;
  }

  for (let i = 0; i < str.length; i++) {
    let char = str[i];
    str = char + str.slice(0, i) + str.slice(i + 1);
    permutations(str);
    str = str.slice(1);
  }
}

permutations("abc");

A.I. Evaluation of the Solution

This is a good solution that uses recursion to generate all permutations of a given string. The time complexity of this solution is O(n!), which is optimal.

Evaluated at: 2022-12-05 02:15:42