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.
Table of Content
Using Recursion
- In this approach, we are using recursion to generate all permutations of the input array.
- Starting from the first element, we swap elements at different positions and recursively generate permutations until all possible combinations are explored, storing each permutation in the res array.
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
- In this approach, we are using an iterative method to generate all permutations of the input array.
- By inserting each array element at different positions in each existing permutation, we build up a new set of permutations until all combinations are explored and stored in the res array.
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!)