How to use Iterative Method In Javascript
- 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!)
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.
Table of Content
- Using Recursion
- Using Iterative Method