Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Generating all possible permutations of array in JavaScript
In JavaScript, generating all possible permutations of an array involves creating every unique arrangement of its elements. This is a common algorithmic problem that can be solved using recursion and array manipulation methods.
What is Array Permutation?
Array permutation refers to different arrangements of elements within an array. For an array with n elements, there are n! (factorial) possible permutations. Each permutation represents a unique ordering of the same elements.
// Input array const arr = [1, 2, 3]; // All possible permutations (3! = 6) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1]
Algorithm Logic
The permutation algorithm works by recursively selecting each element as the first element and finding all permutations of the remaining elements. This approach uses the divide-and-conquer principle:
- Select the first element from the array
- Generate all permutations of the remaining elements
- Combine the selected element with each permutation
- Repeat for each element in the array
Recursive Implementation
function generatePermutations(arr) {
let result = [];
// Base cases
if (arr.length === 0) return [];
if (arr.length === 1) return [arr];
for (let i = 0; i
[
[1, 2, 3],
[1, 3, 2],
[2, 1, 3],
[2, 3, 1],
[3, 1, 2],
[3, 2, 1]
]
Optimized Approach Using Heap's Algorithm
For better performance with larger arrays, we can use Heap's algorithm which generates permutations more efficiently:
function heapPermutation(arr) {
const result = [];
const n = arr.length;
function generate(k, array) {
if (k === 1) {
result.push([...array]);
return;
}
generate(k - 1, array);
for (let i = 0; i
Heap's algorithm result:
[
[1, 2, 3],
[2, 1, 3],
[3, 1, 2],
[1, 3, 2],
[2, 3, 1],
[3, 2, 1]
]
Performance Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive | O(n! × n) | O(n! × n) | Small arrays, easy to understand |
| Heap's Algorithm | O(n!) | O(n) | Larger arrays, optimal performance |
Practical Example with Strings
function stringPermutations(str) {
const chars = str.split('');
const permutations = generatePermutations(chars);
return permutations.map(perm => perm.join(''));
}
const word = "abc";
const stringPerms = stringPermutations(word);
console.log("String permutations:");
console.log(stringPerms);
String permutations: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Conclusion
Generating array permutations in JavaScript can be accomplished through recursive approaches or optimized algorithms like Heap's method. The recursive solution is intuitive and works well for small arrays, while Heap's algorithm provides better performance for larger datasets with O(n!) time complexity.
