Open In App

JavaScript Program to Print all Permutations of Given String

In this article, we will see how to write a program that prints all permutations of a given string. Permutation refers to each of several possible ways in which a set or number of things can be ordered or arranged. There are N! permutations for a string of length N.

Examples:

Input: S = “XY”
Output: “XY”, “YX”

Examples of Print all Permutations of Given String

1.Using Backtracking

Backtracking is an algorithmic technique for solving problems recursively by trying to build a solution incrementally, one piece at a time, removing those solutions that fail to satisfy the constraints of the problem at any point in time.

Example: Here is the practical implementation of the above method.

function generatePermutations(str) {
    const permutations = [];
    function permute(str, left, right) {
        if (left == right) {
            permutations.push(str);
        } else {
            for (let i = left; i <= right; i++) {
                str = swap(str, left, i);
                permute(str, left + 1, right);
                str = swap(str, left, i);
            }
        }
    }
    function swap(a, i, j) {
        const charArray = a.split("");
        const temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
        return charArray.join("");
    }
    permute(str, 0, str.length - 1);
    return permutations;
}
const str = "ABC";
const permutations = generatePermutations(str);
console.log("Permutations:");
console.log(...permutations);

Output
Permutations:
ABC ACB BAC BCA CBA CAB

2.Using Iteration

The idea is to generate sorted permutations of the String. It uses the concept of lexicographically next greater permutation.

Example: Here is the practical implementation of the above method.

function generatePermutations(inputString) {
    const uniquePermutations = [];

    function 
        generateUniquePermutations(arr, currentIndex) {
        if (currentIndex === arr.length - 1) {
            uniquePermutations.push(arr.join(""));
        } else {
            for (let i = currentIndex; 
                i < arr.length; i++) {
                [arr[currentIndex], arr[i]] = 
                    [arr[i], arr[currentIndex]];
                generateUniquePermutations(
                    [...arr], currentIndex + 1);
            }
        }
    }

    generateUniquePermutations(inputString.split(""), 0);
    return uniquePermutations;
}

const inputString = "CABC";
const uniquePermutations = 
    generatePermutations(inputString);

for (let i = 0; 
    i < uniquePermutations.length; i++) {
    console.log(uniquePermutations[i]);
}

Output
CABC
CACB
CBAC
CBCA
CCAB
CCBA
ACBC
ACCB
ABCC
ABCC
ACCB
ACBC
BCAC
BCCA
BACC
BACC
BCCA
BCAC
CCAB
CCBA
CACB
CABC
CBCA
CBAC

3.Using Heap's Algorithm

Heap's algorithm is an efficient method for generating all permutations of a string.

Example: Here is the practical implementation of the above method.

function swap(strArr, i, j) {
  const temp = strArr[i];
  strArr[i] = strArr[j];
  strArr[j] = temp;
}

function permute(str, n = str.length, strArr = str.split('')) {
  if (n === 1) {
    console.log(strArr.join(''));
  } else {
    for (let i = 0; i < n; i++) {
      permute(str, n - 1, strArr);
      if (n % 2 === 0) {
        swap(strArr, i, n - 1);
      } else {
        swap(strArr, 0, n - 1);
      }
    }
  }
}

const str = 'abcd';
permute(str);

Output
abcd
bacd
cabd
acbd
bcad
cbad
dbca
bdca
cdba
dcba
bcda
cbda
dacb
adcb
cdab
dcab
acdb
cadb
dabc
adbc
bdac
dbac
abdc
badc
Article Tags :