4

All Unique Permutations

Difficulty: EASY
Contributed By
Himanshu Tanwar
Avg. time to solve
15 min
Success Rate
85%

Problem Statement
Suggest Edit

You are given an array Arr consisting of N integers. Your task is to find all the unique permutations of the given array. For e.g if the array is {1, 1, 2}, the unique permutations of this array are {1, 1, 2}, {1, 2, 1}, {2, 1, 1}. Note that the total number of permutations of {1,1,2} is equal to 6 but out of those {1,1,2} and {1,2,1} occur twice.

Note:
1. There might be duplicates present in the array.
2. The order of the permutations in the output does not matter.
3. Do not use any kind of in-built library functions to find the answer.
Input Format:
The first line contains the integer N, denoting the size of the array.

The second line contains N space-separated integers denoting the array elements.
Output Format:
The output contains K lines, where each line contains N space-separated integers denoting one of the unique permutations of the given array.

Output for each test case must be in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= N <= 6

Time Limit: 1 sec
Sample Input 1:
3
1 1 2
Sample Output 1:
1 1 2
1 2 1
2 1 1
Explanation for Sample Input 1:
The three unique permutations are  {1, 1, 2}, {1, 2, 1}, {2, 1, 1}. Note that {1, 2, 1}, {2, 1, 1} {1, 1, 2} is also acceptable answer.
Sample Input 2:
3
1 2 3
Sample Output 2:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Explanation for Sample Input 2:
The six unique permutations are  {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}. Note that the order of permutations does not matter, you can return them in any order.
Reset Code
Full screen
copy-code
Console