VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-all-possible-permutations-of-an-array-vector-without-duplicates-using-backtracking/

⇱ All Permutation of an Array with Distinct Elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

All Permutation of an Array with Distinct Elements

Last Updated : 24 Sep, 2025

Given an array arr[], generate all possible permutations of the elements in the array.
Note: All elements in the array are distinct.

Examples:

Input: arr[] = [1, 2, 3]
Output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Explanation: There are 6 possible permutations (3! =6) of the array.

Input: arr[] = [0]
Output: [[0]]

[Approach] Using Recursion and Backtracking - O(n!) Time and O(n) Space

The idea is to fix one element at a time and recursively generate permutations for the rest. At each step, we swap the current element with another, explore further recursively, and then backtrack by swapping back.

We simply start at the first index, swap it with each possible choice, and recurse for the next index. After each recursive call, we backtrack by swapping back, so the array is restored for the next possibility. Repeating this until the end ensures every permutation is covered exactly once.

👁 aaa

Pseudo-code Idea:

Base case: If idx == n, store the current arrangement as one valid permutation.

Recursive choices: For every index idx, we fix one element by swapping it with each element from idx to the last index.

  • Swap arr[idx] with arr[i].
  • Recurse with (idx + 1) to the remaining array.
  • Backtrack by swapping arr[idx] and arr[i] again to restore the original state.

Output
1 2 3 
1 3 2 
2 1 3 
2 3 1 
3 2 1 
3 1 2 
Comment