Generate All Permutations of Array in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to list all possible orders of an array grows as the array gets bigger.
How does the work increase when we add more items to the array?
Analyze the time complexity of the following code snippet.
function permute(arr) {
const result = [];
function backtrack(start = 0) {
if (start === arr.length) {
result.push(arr.slice());
return;
}
for (let i = start; i < arr.length; i++) {
[arr[start], arr[i]] = [arr[i], arr[start]];
backtrack(start + 1);
[arr[start], arr[i]] = [arr[i], arr[start]];
}
}
backtrack();
return result;
}
This code generates all possible orders (permutations) of the input array by swapping elements and exploring every option.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls combined with a loop that swaps elements to create new orders.
- How many times: The recursion explores every possible order, which grows very fast as the array size increases.
Each time we add one more item, the number of orders multiplies by that new number.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 6 (3 x 2 x 1) |
| 5 | 120 (5 x 4 x 3 x 2 x 1) |
| 7 | 5,040 (7 x 6 x 5 x 4 x 3 x 2 x 1) |
Pattern observation: The work grows by multiplying all numbers from 1 up to n, which is much faster than just doubling or squaring.
Time Complexity: O(n!)
This means the time needed grows extremely fast as the array gets bigger, because we must list every possible order.
[X] Wrong: "The time grows like n squared because of the nested loop inside recursion."
[OK] Correct: The recursion multiplies the work by n at each level, creating factorial growth, which is much faster than just squaring.
Understanding this growth helps you explain why generating all permutations is costly and when it's practical to use in real problems.
"What if we only wanted permutations of length k from n items? How would the time complexity change?"
Practice
Solution
Step 1: Understand permutations
Permutations are all possible ways to arrange elements in order.Step 2: Apply to array elements
Generating permutations means listing every possible order of the array's elements.Final Answer:
Listing all possible orders of the array elements -> Option BQuick Check:
Permutations = all orders [OK]
- Confusing permutations with sorting
- Thinking permutations remove duplicates
- Believing permutations find max element
Solution
Step 1: Recall JavaScript function syntax
Functions are declared with the keyword 'function', parameters inside parentheses separated by commas.Step 2: Check each option
function permute(arr, l, r) { } uses correct syntax: function name, parameters with commas, and braces. function permute(arr, l, r) => { } uses arrow syntax incorrectly. permute function(arr, l, r) { } has wrong order. function permute(arr l r) { } misses commas.Final Answer:
function permute(arr, l, r) { } -> Option DQuick Check:
Correct function syntax = function permute(arr, l, r) { } [OK]
- Using arrow syntax without proper parameters
- Missing commas between parameters
- Incorrect function keyword placement
function permute(arr, l, r) {
if (l === r) {
console.log(arr.join(''));
} else {
for (let i = l; i <= r; i++) {
[arr[l], arr[i]] = [arr[i], arr[l]];
permute(arr, l + 1, r);
[arr[l], arr[i]] = [arr[i], arr[l]];
}
}
}
permute(['A', 'B', 'C'], 0, 2);Solution
Step 1: Understand the recursive swapping
The function swaps elements starting from index l to r, generating all permutations by recursive calls.Step 2: Trace output for ['A','B','C']
All 6 permutations of 3 elements are printed: ABC, ACB, BAC, BCA, CAB, CBA.Final Answer:
ABC, ACB, BAC, BCA, CAB, CBA -> Option AQuick Check:
All 3-element permutations = ABC, ACB, BAC, BCA, CAB, CBA [OK]
- Missing swap back step causing wrong output
- Printing partial permutations only
- Confusing output order
function permute(arr, l, r) {
if (l === r) {
console.log(arr.join(''));
} else {
for (let i = l; i < r; i++) {
[arr[l], arr[i]] = [arr[i], arr[l]];
permute(arr, l + 1, r);
[arr[l], arr[i]] = [arr[i], arr[l]];
}
}
}
permute(['X', 'Y', 'Z'], 0, 2);Solution
Step 1: Check loop boundary
The loop runs from i = l to i < r, so it misses the last index r.Step 2: Correct loop condition
Changing to i <= r includes the last element, ensuring all permutations are generated.Final Answer:
The for loop should use i <= r instead of i < r -> Option AQuick Check:
Loop boundary must include r [OK]
- Using i < r misses last element
- Incorrect swap syntax causing errors
- Wrong base case stopping recursion early
['A', 'B', 'A'], how can you modify the permutation function to avoid printing duplicate permutations?Solution
Step 1: Understand duplicates in permutations
Duplicates cause repeated permutations when identical elements are swapped.Step 2: Skip swapping identical elements
Sorting the array and checking if the element was already swapped at the current recursion level avoids duplicates.Final Answer:
Sort the array and skip swapping identical elements at the same recursion level -> Option CQuick Check:
Skip identical swaps after sorting to avoid duplicates [OK]
- Removing duplicates loses valid permutations
- Using set only after generating all permutations (inefficient)
- Assuming duplicates are avoided automatically
Ready to prove it?
Pass the test and this pattern moves unknown
