Generate All Permutations of Array in DSA Java - Time & Space Complexity
When we generate all permutations of an array, we want to know how the work grows as the array gets bigger.
We ask: How many steps does it take to list every possible order of the array?
Analyze the time complexity of the following code snippet.
public void permute(int[] nums, int start) {
if (start == nums.length) {
// print or store the permutation
return;
}
for (int i = start; i < nums.length; i++) {
swap(nums, start, i);
permute(nums, start + 1);
swap(nums, start, i); // backtrack
}
}
This code generates all possible orders (permutations) of the array by swapping elements and exploring each choice recursively.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls combined with a loop that swaps elements.
- How many times: The recursion explores every possible order, which is the factorial of the array size (n!).
As the array size grows, the number of permutations grows very fast because each new element can be placed in many positions.
| 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 factorially, which means it increases much faster than doubling or squaring.
Time Complexity: O(n * n!)
This means the time grows very fast because we generate every possible order, and each order takes linear time to process.
[X] Wrong: "Generating permutations is just like looping through the array once, so it should be O(n)."
[OK] Correct: Each element can be in many positions, so the number of permutations multiplies quickly, not just adds up.
Understanding this time complexity helps you explain why some problems with many possible answers take longer to solve, showing your grasp of algorithm limits.
"What if we only wanted permutations of length k from the array instead of all n elements? 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
Generating all permutations means listing every possible order of the array 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
- Mixing permutations with finding max element
Solution
Step 1: Check method signature syntax
In Java, method signature starts with access modifier, return type, method name, and parameters.Step 2: Validate options
public void generatePermutations(int[] arr, int start) correctly uses 'public void' and parameter types. void generatePermutations(int arr[], int start) public has wrong order. public int generatePermutations(int[] arr, int start) returns int but should be void. public static generatePermutations(int[] arr, int start) misses return type.Final Answer:
public void generatePermutations(int[] arr, int start) -> Option AQuick Check:
Correct Java method syntax = public void generatePermutations(int[] arr, int start) [OK]
- Missing return type in method signature
- Incorrect order of access modifier and return type
- Wrong return type for void methods
public class PermTest {
public static void permute(int[] arr, int start) {
if (start == arr.length - 1) {
for (int num : arr) System.out.print(num + " ");
System.out.println();
return;
}
for (int i = start; i < arr.length; i++) {
int temp = arr[start];
arr[start] = arr[i];
arr[i] = temp;
permute(arr, start + 1);
temp = arr[start];
arr[start] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] arr = {1, 2};
permute(arr, 0);
}
}Solution
Step 1: Trace recursive calls for arr = {1, 2}
Start with start=0, swap arr[0] with arr[0] (no change), recurse with start=1, print 1 2. Then swap back, swap arr[0] with arr[1], arr becomes {2,1}, recurse start=1, print 2 1.Step 2: Confirm output lines
Two lines printed: '1 2' and '2 1', each followed by newline.Final Answer:
1 2 \n2 1 \n -> Option AQuick Check:
All permutations of [1,2] = 1 2 and 2 1 [OK]
- Forgetting to swap back after recursion
- Printing before reaching last index
- Confusing order of swaps
public void permute(int[] arr, int start) {
if (start == arr.length) {
System.out.println(Arrays.toString(arr));
return;
}
for (int i = start; i < arr.length; i++) {
int temp = arr[start];
arr[start] = arr[i];
arr[i] = temp;
permute(arr, start + 1);
}
}Solution
Step 1: Analyze swapping logic
After swapping arr[start] and arr[i], the method calls recursion but does not swap back, so array stays changed for next iterations.Step 2: Identify missing swap back
To restore original array before next iteration, swap back is needed after recursive call.Final Answer:
Missing swap back after recursive call -> Option CQuick Check:
Swap back needed to restore array [OK]
- Not swapping back after recursion
- Incorrect base case index
- Misusing Arrays.toString for printing
Solution
Step 1: Understand duplicates in permutations
Duplicates cause repeated permutations if not handled. Sorting helps group duplicates together.Step 2: Skip swapping duplicates during recursion
By sorting and skipping swaps of same values at the same recursion level, duplicates are avoided efficiently.Final Answer:
Sort the array first and skip swapping duplicate elements during recursion -> Option DQuick Check:
Sort + skip duplicates = unique permutations [OK]
- Generating all then filtering duplicates (inefficient)
- Not sorting before recursion
- Only swapping if values differ misses some permutations
Ready to prove it?
Pass the test and this pattern moves unknown
