01. All Unique Permutations of an Array
β GFG solution to the All Unique Permutations of an Array problem: generate all distinct permutations of an array that may contain duplicates using efficient algorithms. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an array arr[]
that may contain duplicates. Your task is to find all possible distinct permutations of the array in sorted order.
A permutation is a rearrangement of all elements of the array. Since the array may contain duplicate elements, some permutations might be identical. We need to generate only the unique permutations and return them in lexicographically sorted order.
π Examples
Example 1
Input: arr[] = [1, 3, 3]
Output: [[1, 3, 3], [3, 1, 3], [3, 3, 1]]
Explanation: These are the only possible distinct permutations for the given array.
Example 2
Input: arr[] = [2, 3]
Output: [[2, 3], [3, 2]]
Explanation: These are the only possible distinct permutations for the given array.
π Constraints
$1 \le \text{arr.size()} \le 9$
β
My Approach
The optimal approach uses STL's next_permutation
function which efficiently generates permutations in lexicographically sorted order:
STL Next Permutation
Sort the Array:
First, sort the input array to get the smallest lexicographical permutation.
This ensures we start from the beginning and generate permutations in sorted order.
Generate Permutations:
Use
next_permutation()
function which rearranges elements into the next lexicographically greater permutation.It returns
true
if a next permutation exists,false
otherwise.
Store Results:
Add each permutation to the result vector.
Continue until
next_permutation()
returnsfalse
.
Automatic Duplicate Handling:
next_permutation()
inherently skips duplicate permutations when the array is sorted.This is because it always generates the next unique lexicographical arrangement.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n! Γ n), where n is the size of the array. We generate n! permutations, and each permutation takes O(n) time to copy into the result.
Expected Auxiliary Space Complexity: O(1), excluding the space used to store the output. We only use a constant amount of additional space for the algorithm itself, as
next_permutation
works in-place.
π§βπ» Code (C++)
class Solution {
public:
vector<vector<int>> uniquePerms(vector<int>& arr) {
sort(arr.begin(), arr.end());
vector<vector<int>> res;
do {
res.push_back(arr);
} while (next_permutation(arr.begin(), arr.end()));
return res;
}
};
β Code (Java)
class Solution {
public static ArrayList<ArrayList<Integer>> uniquePerms(int[] arr) {
Arrays.sort(arr);
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
do {
ArrayList<Integer> perm = new ArrayList<>();
for (int num : arr) perm.add(num);
res.add(perm);
} while (nextPermutation(arr));
return res;
}
private static boolean nextPermutation(int[] nums) {
int n = nums.length;
int i = n - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) i--;
if (i < 0) return false;
int j = n - 1;
while (nums[j] <= nums[i]) j--;
swap(nums, i, j);
reverse(nums, i + 1, n - 1);
return true;
}
private static void swap(int[] nums, int i, int j) {
int t = nums[i]; nums[i] = nums[j]; nums[j] = t;
}
private static void reverse(int[] nums, int i, int j) {
while (i < j) swap(nums, i++, j--);
}
}
π Code (Python)
class Solution:
def uniquePerms(self, arr):
arr.sort()
res = []
def next_permutation(nums):
n = len(nums)
i = n - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i < 0:
return False
j = n - 1
while nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
nums[i + 1:] = reversed(nums[i + 1:])
return True
res.append(arr[:])
while next_permutation(arr):
res.append(arr[:])
return res
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated