Generating all possible permutations of array in JavaScript


In the given problem statement we are asked to generate every possible permutation of the array given as input by the in JavaScript going from brute force method to optimized solution .

What is an array in JavaScript ?

If you are familiar with any other programming language like C, C++, or Java, you must have heard the term 'array.'

In programming, an array is a collection of similar data elements under one roof.

Now, an important question arises: if arrays are generally the same in all languages, then how does JavaScript make arrays more unique and usable?

Let's understand the overall working of arrays in JavaScript.

An array is an object that stores multiple elements. Since an array is also an object, it has some properties and methods that make working with arrays easier in JavaScript.

Example

Following is the syntax to define Arrays in JavaScript : -

const arrayExample  = [ 10 , 30 , 50 ,60 ];
console.log(arrayExample);

Output

[10, 30, 50, 60]

What is Permutation of Array in JavaScript ?

Permutation of Array refers to the shuffling and ordering of elements present in an array . It generates all possible ways or arrangements of elements using the array as input source of it.

If we have an array of n elements in javascript , it generates n! possible ways to order and output elements.

The permutation of elements is the core of solving problem statement where the input and output can be visualized as follows :

const arr = [ 1 , 2 , 3 ] ;

// generate all permutation 

[ 1 , 2 , 3 ] 
[ 1 , 3 , 2 ]
[ 2 ,1 , 3  ]
[ 2 , 3 , 1 ]
[ 3 , 1 , 2 ]
[ 3 , 2 , 1 ]

Logic Behind Finding Permutation

The logic of finding permutations of array elements is similar to finding the permutation in mathematics , where we will see it with the coding perspective such that taking an array for say , [1,2,3] we will perform some steps in a repeated manner.

Like , we will separate the first element of the array and let it combine with the other elements present already in chronological order , it results back [ 1 , 2 , 3 ] . Then the same separated element is combined with the swapped order (2,3) of chronological order resulting in a new permutation set of [ 1 , 3 , 2 ] .

The following logic is repeated every time until the length of the array is exhausted taking in help of recursion technique to generate different steps of permutation with one core separated element.

Algorithm

Step 1 : Declare a function named generatePermutation taking in an array of elements as an input .

Step 2 : Declare the final result array where all permutations of given elements present in array input have different combinations . For now declare it with an empty array.

Step 3 : The function we have declared just above in Step 1 is actually a recursive function with best of two base cases saying if length of array is 0 called as empty array now , there would be no permutation of it , and if the length of the array is 1 saying the array has only single element where permutation of single element is always be a single element hence resulting the same array with one element only .

These are the two base cases where the entire working of function ends up to avoid endless loop and ambiguity of code.

Step 4 : Now forwarding , declare a for loop that will traverse you to the end of the array where each iteration saves the current element depending on the first value of i . And then the javascript method like slice is used to separate out the other elements from the current element stored in first part of the step 4 and concat method is used to combine whatever just happened resulting in one permutation combination of elements present in array .

Step 5 : The following Step 4 needs to be recursively done for that particular current element we have just saved in step 4 by swapping the other elements using recursion such that generating a second combination of elements present in array.

Step 6 : The second nested loop results in permutation of swapped elements to generate different combinations of elements which is then concatenated with current element to implement Step 5

Step 7 : This is how nested loop and recursion will work for every element in the array to generate combinations and ordering of different permutations of elements present in array provided as an input source by the user.

Example

function generatePermutation (arr)
{
   let resultArr = [];
   if(arr.length === 0) return [];
   if(arr.length ===1) return [arr];
   
   for(let i =0 ; i<arr.length ; i++)
   {
     const currentElement = arr[i];
     
     const otherElements = arr.slice(0,i).concat(arr.slice(i+1));
     const swappedPermutation = generatePermutation(otherElements);
     
     for(let j =0 ; j < swappedPermutation.length ; j++)
     {
       const finalSwappedPermutation = 
       [currentElement].concat(swappedPermutation[j]);
       
       resultArr.push(finalSwappedPermutation);
     }
   }
   
   return resultArr;
}

const arr = [1,2,3];
const finalPermutedArray = generatePermutation(arr);
console.log(finalPermutedArray);

Output

[
  [ 1, 2, 3 ],
  [ 1, 3, 2 ],
  [ 2, 1, 3 ],
  [ 2, 3, 1 ],
  [ 3, 1, 2 ],
  [ 3, 2, 1 ]  ]

The following mentioned code is the straight forward code one can think of while looking at the problem statement , later you can ofcourse optimize it to the better quality of space and time making it more efficient and high quality.

In the above code we have declared a function taking in the array input . Then we go step by step , following first to splice the first element of every iteration and combining the other elements present in array to form a new separated Array followed by generating the permutations of separated Array using recursion and splice and concat javascript method to combine with the current element we have stored of each iteration to produce final results of different permutation of a particular array given as input.

Time Complexity

In the above algorithm we have initially used for loop that goes for length of the array resulting O(n) in worst case followed by splice method that takes O(1) for best case to separate out every first element of each iteration and concat method that concatenates the left over elements till length resulting O(n) adding yo O(n) + O(1) + O(n) = O(2n) = O(n) where constant does not matter followed by nested loop to traverse the left over elements resulting O(n) in worst case resulting O(n^2) worst time complexity .

The space complexity taken is O(1) only.

Conclusion

This is how we can solve the above problem statement thinking logically and in the context of coding taking help of nested loops and javascript methods like splice and concat with the recursion pillar to solve the case of generating different permutations of elements present in an array.

Updated on: 22-Aug-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements