Open In App

Print all Permutation of Array using JavaScript

Permutations of Array are a fundamental concept in combinatorics and algorithms, showcasing all possible arrangements of its elements.

Examples:

Input: nums = [1, 2, 3]
Output: [ [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2] ]
Explanation: There are 6 possible permutations

Input: nums = [1, 3]
Output: [ [1, 3], [3, 1] ]
Explanation: There are 2 possible permutations

Below are the approaches to Print all permutations of arrays using JavaScript.

Using Recursion

Example: The below example uses Recursion to Print all permutations of an array using JavaScript.

let arr = [1, 2, 3];
let res = [];

function approach1Fn(arr, start) {
    if (start === arr.length - 1) {
        res.push([...arr]);
        return;
    }
    for (let i = start; i < arr.length; i++) {
        [arr[start], arr[i]] = [arr[i], arr[start]];
        approach1Fn(arr, start + 1);
        [arr[start], arr[i]] = [arr[i], arr[start]]; 
    }
}
approach1Fn(arr, 0);
console.log(res);

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

Time Complexity: O(n!), where n is the number of elements in the array.

Space Complexity: O(n!)

Using Iterative Method

Example: The below example uses the Iterative Method to Print all permutations of an array using JavaScript.

let arr = [1,3];
let res = [[]];
for (let num of arr) {
    const temp = [];
    for (let arr of res) {
        for (let i = 0; i <= arr.length; i++) {
            const newArr = [...arr];
            newArr.splice(i, 0, num);
            temp.push(newArr);
        }
    }
    res = temp;
}
console.log(res);

Output
[ [ 3, 1 ], [ 1, 3 ] ]

Time Complexity: O(n!), where n is the number of elements in the array.

Space Complexity: O(n!)

Article Tags :