📖 Scenario: You are working on a puzzle game where you need to find all possible ways to arrange a set of unique numbers. This helps the game generate different challenges for players.
🎯 Goal: Build a Java program that generates and prints all permutations of a given array of integers.
📋 What You'll Learn
Create an integer array with exact values
Create a helper method to generate permutations
Use recursion and swapping to generate permutations
Print each permutation on a separate line
💡 Why This Matters
🌍 Real World
Generating permutations is useful in games, puzzles, and solving problems where all possible arrangements need to be checked.
💼 Career
Understanding recursion and permutations is important for software engineers working on algorithms, testing, and combinatorial problems.
Progress0 / 4 steps
1
Create the integer array
Create an integer array called nums with these exact values: 1, 2, 3.
DSA Java
Hint
Use int[] nums = {1, 2, 3}; to create the array.
2
Add the permutation helper method signature
Add a static method called permute that takes three parameters: an integer array nums, an integer start, and an integer end. The method will generate permutations by swapping elements.
DSA Java
Hint
Define the method with the exact signature public static void permute(int[] nums, int start, int end).
3
Implement the permutation logic with recursion and swapping
Inside the permute method, implement the logic to generate all permutations of nums from index start to end. Use a base case to print the array when start == end. Use a for loop with variable i from start to end. Swap elements at start and i, recursively call permute with start + 1, then swap back to restore the array.
DSA Java
Hint
Use recursion with swapping and backtracking to generate permutations.
4
Call the permutation method and print all permutations
In the main method, call permute with nums, 0 as start, and nums.length - 1 as end to print all permutations.
1. What does generating all permutations of an array mean?
easy
A. Sorting the array in ascending order
B. Listing all possible orders of the array elements
C. Finding the largest element in the array
D. Removing duplicate elements from the array
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 B
Quick Check:
Permutations = all orders [OK]
Hint: Permutations = all ways to arrange elements [OK]
Common Mistakes:
Confusing permutations with sorting
Thinking permutations remove duplicates
Mixing permutations with finding max element
2. Which Java method signature correctly defines a function to generate permutations of an integer array?
easy
A. public void generatePermutations(int[] arr, int start)
B. void generatePermutations(int arr[], int start) public
C. public int generatePermutations(int[] arr, int start)
D. public static generatePermutations(int[] arr, int start)
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 A
Quick Check:
Correct Java method syntax = public void generatePermutations(int[] arr, int start) [OK]
Hint: Java method = access + return type + name + params [OK]
Common Mistakes:
Missing return type in method signature
Incorrect order of access modifier and return type
Wrong return type for void methods
3. What is the output of the following Java code snippet?
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);
}
}
medium
A. 1 2 \n2 1 \n
B. 1 2 \n1 2 \n
C. 2 1 \n1 2 \n
D. No output
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 A
Quick Check:
All permutations of [1,2] = 1 2 and 2 1 [OK]
Hint: Swap and recurse to generate permutations [OK]
Common Mistakes:
Forgetting to swap back after recursion
Printing before reaching last index
Confusing order of swaps
4. Identify the error in this Java method for generating permutations:
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);
}
}
medium
A. Using Arrays.toString incorrectly
B. Incorrect base case condition
C. Missing swap back after recursive call
D. Wrong loop range in for loop
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 C
Quick Check:
Swap back needed to restore array [OK]
Hint: Always swap back after recursion to restore array [OK]
Common Mistakes:
Not swapping back after recursion
Incorrect base case index
Misusing Arrays.toString for printing
5. You want to generate all permutations of an array with possible duplicate elements, but avoid printing duplicate permutations. Which approach is best?
hard
A. Use a HashSet to store and print only unique permutations after generating all
B. Only swap elements if they are different values
C. Generate all permutations without any checks and print all
D. Sort the array first and skip swapping duplicate elements during recursion
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 D
Quick Check:
Sort + skip duplicates = unique permutations [OK]
Hint: Sort array and skip duplicate swaps to avoid repeats [OK]
Common Mistakes:
Generating all then filtering duplicates (inefficient)
Not sorting before recursion
Only swapping if values differ misses some permutations
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.