JavaScript Program to Print all Permutations of Given String
Last Updated :
31 May, 2024
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.
- This code initializes an empty array to store the permutations and defines a recursive function called permute to generate permutations.
- In the permute function, it swaps characters within the string to rearrange them, explores all possible permutations, and backtracks to explore other combinations.
- The process continues until it reaches a base case where a complete permutation is added to the result array. Finally, the code prints all generated permutations.
Example: Here is the practical implementation of the above method.
JavaScript
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);
OutputPermutations:
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.
- findCeil function finds the index of the smallest character in the string str which is greater than first and occurs in the range [l, h].
- generateNextPermutation function generates the next lexicographically greater permutation of the input string str using the same logic as the original code sortedPermutations function repeatedly generates and prints the next permutation until there are no more permutations to generate.
Example: Here is the practical implementation of the above method.
JavaScript
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]);
}
OutputCABC
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.
- First, we define a function that takes an array and two indices as arguments and swaps the elements at those indices in the array.
- Create a function that recursively generates permutations. If the length of the string is 1, print the permutation. Otherwise, iterate over each character and recursively generate permutations with the remaining characters.
- Initialize an array representation of the string. Call the permute function with the original string and its length. iterate over each character and recursively call the permute function with a reduced length and a swapped array to generate permutations.
Example: Here is the practical implementation of the above method.
JavaScript
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);
Outputabcd
bacd
cabd
acbd
bcad
cbad
dbca
bdca
cdba
dcba
bcda
cbda
dacb
adcb
cdab
dcab
acdb
cadb
dabc
adbc
bdac
dbac
abdc
badc
4: Using Iterative Method with Factorial Count
- Define a function
generatePermutations
that takes a string str
as input. - Initialize an empty array
permutations
to store all permutations. - Define a factorial function
factorial
to calculate the factorial of a given number. - Calculate the total number of permutations
totalPermutations
using the factorial of the string length. - Iterate from 0 to
totalPermutations
.- Initialize an empty string
currentPermutation
to store the current permutation. - Initialize a variable
temp
to store the current iteration index. - Split the input string
str
into an array of characters availableChars
. - Iterate backwards through the characters of the input string:
- Calculate the index of the next character in the permutation using
temp % (j + 1)
, where j
is the current index. - Update
temp
to Math.floor(temp / (j + 1))
. - Append the character at the calculated index to
currentPermutation
. - Remove the character at the calculated index from
availableChars
.
- Push the generated permutation
currentPermutation
to the permutations
array.
- Return the array of
permutations
.
Example:
JavaScript
function generatePermutations(str) {
const permutations = [];
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
const len = str.length;
const totalPermutations = factorial(len);
for (let i = 0; i < totalPermutations; i++) {
let currentPermutation = '';
let temp = i;
const availableChars = str.split('');
for (let j = len - 1; j >= 0; j--) {
const index = temp % (j + 1);
temp = Math.floor(temp / (j + 1));
currentPermutation += availableChars[index];
availableChars.splice(index, 1);
}
permutations.push(currentPermutation);
}
return permutations;
}
const str = "ABC";
const permutations = generatePermutations(str);
console.log("Permutations:");
console.log(...permutations);
OutputPermutations:
ABC BAC CAB ACB BCA CBA
Similar Reads
JavaScript Program to Calculate nPr (Permutations) In this article, we are going to learn how to calculate permutations (nPr) by using JavaScript. Calculating nPr, or permutations means finding the number of unique ordered arrangements of r items from a set of n distinct items. Where order matters and no item is repeated. The formula for calculating
3 min read
JavaScript Program to Print all Subsequences of a String A subsequence is a sequence that can be derived from another sequence by deleting zero or more elements without changing the order of the remaining elements. Subsequences of a string can be found with different methods here, we are using the Recursion method, Iteration method and Bit manipulation me
3 min read
JavaScript Program to Print all Possible Strings that can be Made by Placing Spaces In this article, We are going to see how can we print all possible strings that can be made by placing spaces. We will add spaces in between the strings and print every possible value. Example: Input: "ABCD"Output: 'A B C D' 'A B CD' 'A BC D' 'A BCD' 'AB C D' 'AB CD' 'ABC D' 'ABCD'Table of Content B
5 min read
JavaScript Program to Find Lexicographically Next Permutation Given an array of distinct integers, we want to find the lexicographically next permutation of those elements. In simple words, when all the possible permutations of an array are placed in a sorted order, it is the lexicographic order of those permutations. In this case, we have to find the next gre
5 min read
PHP Program to print all permutations of a given string A permutation also called an "arrangement number" or "order," is a rearrangement of the elements of an ordered list S into a one-to-one A permutation also called an "arrangement number" or "order," is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself
2 min read
Java Program to Print all Unique Words of a String Java program to print all unique words present in the string. The task is to print all words occurring only once in the string. Illustration: Input : Welcome to Geeks for Geeks. Output : Welcome to for Input : Java is great.Python is also great. Output : Java Python also Methods: This can be done in
4 min read
Check if two strings are permutation of each other Write a function to check whether two given strings are Permutation of each other or not. A Permutation of a string is another string that contains same characters, only the order of characters can be different. For example, "abcd" and "dabc" are Permutation of each other. We strongly recommend that
13 min read
Java Program to Iterate Over Characters in String Given string str of length N, the task is to traverse the string and print all the characters of the given string using java. Illustration: Input : str = âGeeksforGeeksâ Output : G e e k s f o r G e e k sInput : str = "GfG" Output : G f G Methods: Using for loops(Naive approach)Using iterators (Opti
3 min read
Different Ways to Generate Permutations of an Array Permutations are like the magic wand of combinatorics, allowing us to explore the countless ways elements can be rearranged within an array. Whether you're a coder, a math enthusiast, or someone on a quest to solve a complex problem, understanding how to generate all permutations of an array is a va
6 min read
Convert a String to Character Array in Java Converting a string to a character array is a common operation in Java. We convert string to char array in Java mostly for string manipulation, iteration, or other processing of characters. In this article, we will learn various ways to convert a string into a character array in Java with examples.E
2 min read