Imagine you have a collection of colored beads, some colors repeating, and you want to find all unique ways to arrange them on a string without repeating the same pattern twice.
Given a collection of numbers that might contain duplicates, return all possible unique permutations in any order.
Input: An array of integers nums.
Output: A list of lists, where each list is a unique permutation of nums.
1 ≤ nums.length ≤ 8-10 ≤ nums[i] ≤ 10
Edge cases: All elements are the same → only one unique permutationArray with no duplicates → all permutations are uniqueEmpty array → returns an empty list or list with empty permutation
def permuteUnique(nums: list[int]) -> list[list[int]]:public List<List<Integer>> permuteUnique(int[] nums)vector<vector<int>> permuteUnique(vector<int>& nums)function permuteUnique(nums)
def permuteUnique(nums):
# Write your solution here
pass
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
// Write your solution here
return new ArrayList<>();
}
}
#include <vector>
using namespace std;
vector<vector<int>> permuteUnique(vector<int>& nums) {
// Write your solution here
return {};
}
function permuteUnique(nums) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: [[1,1,2],[1,1,2],[1,2,1],[2,1,1],[2,1,1]]Duplicates not skipped during backtracking, causing repeated permutations.✅ Sort input and skip nums[i] if nums[i] == nums[i-1] and used[i-1] is false during recursion.
Wrong: []Empty input returns empty list instead of list with empty permutation.✅ Return [[]] when input is empty to represent one empty permutation.
Wrong: [[5],[5],[5]]Single element input returns duplicates due to incorrect duplicate skipping or recursion.✅ Ensure base case returns single permutation [[nums[0]]] without duplicates.
Wrong: [[2,2,2,2],[2,2,2,2],[2,2,2,2]]All identical elements produce multiple duplicate permutations due to missing skip condition.✅ Skip duplicates by checking if nums[i] == nums[i-1] and used[i-1] is false.
Wrong: [[1,2,2,3],[1,2,3,2],[1,3,2,2]]Greedy approach misses permutations by not exploring all branches.✅ Use full backtracking with used array and duplicate skipping to generate all permutations.