All Unique Permutations of an array | Practice | GeeksforGeeks

Given an array arr[] of length n. Find all possible unique permutations of the array.

Example 1:
Input: 
n = 3
arr[] = {1, 2, 1}
Output: 
1 1 2
1 2 1
2 1 1
Explanation:
These are the only possible unique permutations
for the given array.

Example 2:
Input: 
n = 2
arr[] = {4, 5}
Output: 
4 5
5 4


Your Task:
You don't need to read input or print anything. You only need to complete the function uniquePerms() that takes an integer n, and an array arr of size n as input and returns a sorted list of lists containing all unique permutations of the array.

Expected Time Complexity:  O(n*n!)
Expected Auxilliary Space: O(n*n!)
 
Constraints:
1 ≤ n ≤ 9
1 ≤ arri ≤ 10
0
nikil19b1011793 weeks ago
set<vector<int>>st; void recurPermute(vector<vector<int>>&res,vector<int>&ds,int freq[],vector<int>&arr){     if(ds.size()==arr.size()){         if(st.find(ds)==st.end()){             res.push_back(ds);             st.insert(ds);         }                  return;     }     for(int i=0;i<arr.size();i++){         if(freq[i]==0){             ds.push_back(arr[i]);             freq[i]=1;             recurPermute(res,ds,freq,arr);             freq[i]=0;             ds.pop_back();         }     } }   vector<vector<int>> uniquePerms(vector<int> arr ,int n) {       // code here       vector<vector<int>>res;       vector<int>ds;       int freq[20]={0};       recurPermute(res,ds,freq,arr);       sort(res.begin(),res.end());              return res;   }
+2
lindan1232 months ago
 set<vector<int>>s;
    vector<vector<int>> ans;
    void help(vector<int>arr,int i,int n)
    {
        if(i==n)
        {
            s.insert(arr);
            return;
        }
       for(int x=i;x<=n;x++)
       {
           swap(arr[i],arr[x]);
           help(arr,i+1,n);
           swap(arr[i],arr[x]);
       }
    }
    vector<vector<int>> uniquePerms(vector<int> arr ,int n) {
        
        sort(arr.begin(),arr.end());
        help(arr,0,n-1);
        
        for(auto x: s)
        {
            ans.push_back(x);
        }
        sort(ans.begin(),ans.end());
        
        return ans;
    }
Time Taken : 1.2sec
Cpp
0
cs21m0593 months ago
vector<vector<int>> uniquePerms(vector<int> arr ,int n) {       // code here       map<vector<int> , int> m;              vector<vector<int>> ans;              sort(arr.begin() , arr.end());                     do       {           if(m.find(arr) == m.end())           {               ans.push_back(arr);           }           m[arr]++;                  }while(next_permutation(arr.begin() , arr.end()));              return ans;       
 
0
saket727403 months ago
My correct java solution which passed 100% test cases
 
static void permutation(ArrayList<Integer> arr, int l, int r, Set<ArrayList<Integer>> a){       if(l == r){           //System.out.println(arr);           // ArrayList<Integer> b = new ArrayList<>();           // b.addAll(arr);           a.add(new ArrayList<Integer>(arr));           return ;       }       for(int i=l;i<=r;i++){           arr = interchangeInt(arr, l, i);           permutation(arr, l+1, r, a);           arr = interchangeInt(arr, l, i);       }   }      static ArrayList<Integer> interchangeInt(ArrayList<Integer> arr, int a, int b){       int temp = arr.get(a);       int l = arr.get(b);       arr.set(a, l);       arr.set(b, temp);       return arr;   }      static ArrayList<ArrayList<Integer>> uniquePerms(ArrayList<Integer> arr , int n) {       // code here       Set<ArrayList<Integer>> set = new HashSet<>();       permutation(arr, 0, n-1, set);       ArrayList<ArrayList<Integer>> A = new ArrayList<ArrayList<Integer>>(set);       Collections.sort(A, new Comparator<ArrayList<Integer>>(){           @Override           public int compare(ArrayList<Integer> a, ArrayList<Integer> b){               int comp = 0;               for(int i=0;i<Math.min(a.size(), b.size());i++){                   comp = Integer.compare(a.get(i), b.get(i));                   if(comp != 0)                       return comp;               }               return Integer.compare(a.size(), b.size());           }       });       return A;   }
+1
amruthack11013 months ago
@gfg please fix this issue, the code is giving correct output in other text editors but not here
static ArrayList<ArrayList<Integer>> m1 = new ArrayList<>();
static HashMap<ArrayList,Integer> m= new HashMap<>();
static ArrayList<ArrayList<Integer>> uniquePerms(ArrayList<Integer> arr , int n) {
        
        //ArrayList<ArrayList<Integer>> res=new ArrayList<>();
        Collections.sort(arr);
        int[] nums=new int[n];
        for(int i=0;i<n;i++){
            nums[i]=arr.get(i);
        }
        boolean[] visited = new boolean[nums.length];
        findPermutations(nums, new ArrayList<>(), visited);
        
        return m1;
    }
    static void findPermutations(int[] nums, ArrayList<Integer> cl, boolean[] visited) {
        if (cl.size() == nums.length) {
        	if(!m.containsKey(cl)){
                m.put( (cl) ,1 );
                m1.add(new ArrayList<>(cl));
            }
        return;
        }
        for(int i = 0; i < nums.length; i++) {
            if (!visited[i]) {
                visited[i] = true;
                cl.add(nums[i]);
                findPermutations(nums, cl, visited);
                cl.remove(cl.size() - 1);
                visited[i] = false;
            }
        }
    }
0
krishnagautam58993 months ago
  set<vector<int>>ans; //use set for unique elements   void help(vector<int>&nums,int idx,int n){       if(idx==n){           ans.insert(nums);           return ;       }              for(int i=idx;i<n;i++){           swap(nums[idx],nums[i]);           help(nums,idx+1,n);           swap(nums[idx],nums[i]);           }   }   vector<vector<int>> uniquePerms(vector<int> arr ,int n) {       // code here       vector<vector<int>>v;       help(arr,0,n);       for(auto &it:ans){           v.push_back(it);       }       return v;   }
+4
ghazanferwahab23 months ago
Dear @gfg fix ur compiler my code is fiving perfect answer yet it is showing that it is not acceptiong for the test case
 6
 2 1 2 3 4 5
This is very frustating and i am getting AC in leetcode for the same question My code:
 static ArrayList<ArrayList<Integer>> uniquePerms(ArrayList<Integer> arr , int n) {       // code        Collections.sort(arr);       int a1[]=new int [arr.size()];       for(int i=0;i<arr.size();i++)           a1[i]=arr.get(i);       ArrayList<ArrayList<Integer>> ans=new ArrayList<>();       solve(0,a1.length,a1,ans);       return ans;   }   static void solve(int ind,int l,int nums[],ArrayList<ArrayList<Integer>>a){       if(ind==l){           List<Integer>ds=new ArrayList<>();           for(int i=0;i<l;i++)               ds.add(nums[i]);           if(!a.contains(ds))           a.add(new ArrayList<Integer>(ds));       }       for(int i=ind;i<l;i++){           swap(i,ind,nums);           solve(ind+1,l,nums,a);           swap(i,ind,nums);       }       return;   }   static void swap(int i,int j,int nums[]){       int t=nums[i];       nums[i]=nums[j];       nums[j]=t;   }
+1
karunakarmutthi3 months ago
what is wrong with my code it was showing TLE at 102 test case but Succesfuly Executed at leetcode and interviewBit
class Solution {   static ArrayList<ArrayList<Integer>> uniquePerms(ArrayList<Integer> arr , int n) {       Collections.sort(arr);       ArrayList<Integer> cur=new ArrayList<>();       ArrayList<ArrayList<Integer>> res=new ArrayList<>();       boolean[] map=new boolean[n];       recur(cur,map,arr,res,n);       return res;   }   public static  void recur(ArrayList<Integer> curr,boolean[] map,ArrayList<Integer> arr,ArrayList<ArrayList<Integer>> res,int n){       if(n==curr.size()){           if(!res.contains(curr))           res.add(new ArrayList<Integer>(curr));       }       for(int i=0;i<n;i++){           if(map[i]==false){               map[i]=true;               curr.add(arr.get(i));               recur(curr,map,arr,res,n);               curr.remove(curr.size()-1);               map[i]=false;           }       }          }};
   
0
keshavkumarshivanshu34 months ago
best of best time- 0.03********
void solve(map<int,int> &mp,vector<int> tmp,int n,vector<vector<int>> &ans){
      if(tmp.size()==n){
          ans.push_back(tmp);
          return;
      }
      for(auto i=mp.begin();i!=mp.end();i++){
          if(i->second > 0){
              tmp.push_back(i->first);
              i->second--;
              solve(mp,tmp,n,ans);
              tmp.pop_back();
              i->second++;
          }
      }
  }
    vector<vector<int>> uniquePerms(vector<int> arr ,int n) {
        // code here
        map<int,int> mp;
        for(auto i:arr) mp[i]++;
        vector<vector<int>> ans;
        vector<int> tmp;
        solve(mp,tmp,n,ans);
        return ans;
    }
+1
rayalravi20014 months ago
c++  solution
 
void solve(vector<int> arr, int l , int r,set<vector<int>> &ans ){       if(l==r){           ans.insert(arr);           return;       }              for(int i=l; i<r; i++){           swap(arr[i],arr[l]);           solve(arr,l+1,r,ans);           swap(arr[i],arr[l]);       }       return;   }    vector<vector<int>> uniquePerms(vector<int> arr ,int n) {       // code here       int l = 0;       int r = arr.size();       set<vector<int>> ans;       solve(arr,l,r,ans);       vector<vector<int>> v(ans.size());       copy(ans.begin(), ans.end(), v.begin());       // for(int i=0; i<ans.size();i++){       //     v.insert(ans[i]);       // }       return v;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.