Open In App

Print All Distinct Permutations of an Array

Last Updated : 24 Apr, 2025
Summarize
Comments
Improve
Suggest changes
Share
14 Likes
Like
Report

Given an array arr[], Print all distinct permutations of the given array.

Examples:

Input: arr[] = [1, 3, 3]
Output: [[1, 3, 3], [3, 1, 3], [3, 3, 1]]
Explanation: Above are all distinct permutations of given array.

Input: arr[] = [2, 2]
Output: [[2, 2]]
Explanation: Above are all distinct permutations of given array.

Approach: Using BackTracking

  • We will use backtracking to build all possible permutations by recursively adding unused elements to the current path, marking them as visited.
  • To avoid duplicates we will sort the array first, and skip an element if it's the same as the previous one and the previous hasn’t been used—this prevents generating repeated permutations.

Step by Step Implementation:

  • Sort the input array to handle duplicates easily.
  • Use a visited[] array to track used indices in the current path.
  • Iterate through each element:
    • Skip if already visited.
    • Skip duplicates if the previous identical element wasn’t used.
  • Add element to path, mark as visited, and recurse.
  • If path is complete, store it in the result.
  • Backtrack by removing the last element and unmarking it.
C++
Java Python C# JavaScript

Output
1 3 3 
3 1 3 
3 3 1 

Time Complexity: O(n! * n), n! comes from the total number of permutations in the worst case (when all elements are distinct) and n accounts for the time taken to copy each complete permutation (which has n elements) into the result array.
Auxiliary Space: O(n), depth of recursion equals the number of elements and also for visited and curr array.


All Unique Permutations of an array | DSA Problem

Similar Reads