Home
DSA Patterns
Backtracking
Permutations II
Permutations II (LeetCode 47)
Permutations II (LeetCode 47): generate all unique permutations of numbers that may repeat: sort, then skip a value when its equal left neighbour is not yet in the path.
Problem Understanding
Permutations II: given numbers nums that may contain duplicates, return every unique permutation, in any order.
Example: nums = [1, 1, 2] returns [[1,1,2], [1,2,1], [2,1,1]]. Plain permutations would list each of these twice.
The Intuition: Use Equal Values in Order
Start from Permutations: choose an unused number, recurse, un-choose. With duplicates, two equal values can swap places and produce the same list twice.
The fix is a single rule after sorting:
- Skip
nums[i]ifnums[i] == nums[i − 1]andnums[i − 1]is not in the path.
That makes equal values always enter the path left to right, so there is only one way to place each group of twins. The same sort-and-skip idea removes duplicates in Subsets II and Combination Sum II.
Permutations II Visualization
EMPTY PATH
nums, sorted (used numbers tinted)
0
1
2
path
permutations (0)
None yet
Sort: [1, 1, 2]. Equal values now sit side by side
Next
Slot 1: choose 1 (index 0). Path [1]
nums
The sorted numbers are on top, with used ones tinted; a twin skipped by the rule turns red. The path is below, and the unique permutations collect beside the figure. Try Two pairs: 24 orderings collapse to 6.
Permutations II Dry Run
Input: nums = [1, 1, 2] (indexes 0, 1, 2)
| Path | Index tried | Action |
|---|---|---|
| [] | 0 (1) | choose |
| [1] | 1 (1) | choose: twin 0 is used |
| [1, 1] | 2 (2) | choose, record [1,1,2] |
| [1] | 2 (2) | choose, then index 1: record [1,2,1] |
| [] | 1 (1) | skip: twin 0 is unused |
| [] | 2 (2) | choose, then 0, 1: record [2,1,1] |
Answer: 3 unique permutations.
Permutations II LeetCode Solution
The Permutations template plus a sort and one skip check.
Permutations II Code
1var permuteUnique = function(nums) {2 nums.sort((a, b) => a - b);3 const res = [], path = [], used = new Array(nums.length).fill(false);4 const backtrack = () => {5 if (path.length === nums.length) {6 res.push([...path]);7 return;8 }9 for (let i = 0; i < nums.length; i++) {10 if (used[i]) continue;11 if (i > 0 && nums[i] === nums[i - 1] && !used[i - 1]) continue;12 used[i] = true;13 path.push(nums[i]);14 backtrack();15 path.pop();16 used[i] = false;17 }18 };19 backtrack();20 return res;21};
Permutations II in Python, Java, C++, TypeScript and C
Permutations II in Python
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res, path, used = [], [], [False] * len(nums)
def backtrack():
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continue
used[i] = True
path.append(nums[i])
backtrack()
path.pop()
used[i] = False
backtrack()
return resPermutations II in Java
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
backtrack(nums, new ArrayList<>(), new boolean[nums.length], res);
return res;
}
private void backtrack(int[] nums, List<Integer> path, boolean[] used, List<List<Integer>> res) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
used[i] = true;
path.add(nums[i]);
backtrack(nums, path, used, res);
path.remove(path.size() - 1);
used[i] = false;
}
}
}Permutations II in C++
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
vector<int> path;
vector<bool> used(nums.size(), false);
backtrack(nums, path, used, res);
return res;
}
private:
void backtrack(vector<int>& nums, vector<int>& path, vector<bool>& used, vector<vector<int>>& res) {
if (path.size() == nums.size()) {
res.push_back(path);
return;
}
for (int i = 0; i < (int)nums.size(); i++) {
if (used[i]) continue;
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
used[i] = true;
path.push_back(nums[i]);
backtrack(nums, path, used, res);
path.pop_back();
used[i] = false;
}
}
};Permutations II in TypeScript
function permuteUnique(nums: number[]): number[][] {
nums.sort((a, b) => a - b);
const res: number[][] = [], path: number[] = [], used: boolean[] = new Array(nums.length).fill(false);
const backtrack = (): void => {
if (path.length === nums.length) {
res.push([...path]);
return;
}
for (let i = 0; i < nums.length; i++) {
if (used[i]) continue;
if (i > 0 && nums[i] === nums[i - 1] && !used[i - 1]) continue;
used[i] = true;
path.push(nums[i]);
backtrack();
path.pop();
used[i] = false;
}
};
backtrack();
return res;
}Permutations II in C
int cmp(const void* a, const void* b) { return *(int*)a - *(int*)b; }
void backtrack(int* nums, int n, int* path, int depth, bool* used, int** res, int* count) {
if (depth == n) {
res[*count] = malloc(n * sizeof(int));
memcpy(res[(*count)++], path, n * sizeof(int));
return;
}
for (int i = 0; i < n; i++) {
if (used[i]) continue;
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
used[i] = true;
path[depth] = nums[i];
backtrack(nums, n, path, depth + 1, used, res, count);
used[i] = false;
}
}
int** permuteUnique(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
qsort(nums, numsSize, sizeof(int), cmp);
int total = 1;
for (int i = 2; i <= numsSize; i++) total *= i;
int** res = malloc(total * sizeof(int*));
int path[8];
bool used[8] = {false};
*returnSize = 0;
backtrack(nums, numsSize, path, 0, used, res, returnSize);
*returnColumnSizes = malloc(*returnSize * sizeof(int));
for (int i = 0; i < *returnSize; i++) (*returnColumnSizes)[i] = numsSize;
return res;
}Edge Cases & Common Mistakes
- Forgetting to sort: the skip rule only works when equal values are adjacent.
used[i − 1]instead of!used[i − 1]: also produces unique results but explores far more dead branches; the!usedform prunes at the top.- All values equal: exactly one permutation.
- No duplicates: the rule never fires, and the result is the same as Permutations.
- Deduplicating with a set afterwards: correct but wasteful; skip during the search instead.
Summary
Sort the numbers, then run the choose / recurse / un-choose template with one extra rule: skip nums[i] when it equals nums[i − 1] and nums[i − 1] is unused. Equal values are then always placed in order, so every unique permutation is built exactly once.
More practice: DSA interview questions with answers · patterns cheat sheet
