Permutations in Java: Explanation & Practice

Generate all permutations of an array

Problem summary

Given an array of distinct integers, return all possible permutations. A permutation is a rearrangement of all elements.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        
        // Backtracking: try each unused element at each position
        // Use visited array or swap technique
        // Print all permutations
    }
}

Expected output and test cases

  • [1,2,3] → 6 permutations
    [1,2,3]
    [1,3,2]
    [2,1,3]
    [2,3,1]
    [3,1,2]
    [3,2,1]
  • [0,1] → 2 permutations
    [0,1]
    [1,0]
  • [1] → just [1]
    [1]

Hints

  1. For each position, try all unused elements
  2. Mark element as used, recurse, then unmark (backtrack)
  3. Base case: when current permutation has all elements
  4. Total permutations = n!

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler