Practice › Recursion & Backtracking
Unique Permutations with Duplicates
Medium · Recursion & Backtracking · Asked at Amazon, Microsoft, LinkedIn, Meta
The array may contain repeated values. Print every distinct permutation, in lexicographic order (compare numbers by value, element by element), one per line.
Input
First line: n. Second line: n space-separated integers.
Output
The distinct permutations, one per line, elements separated by spaces.
Constraints
- 1 ≤ n ≤ 7
- −10 ≤ a[i] ≤ 10
Sort the array. Backtrack position by position; at each position skip a value equal to the previous one when that previous copy is still unused — this way equal values are always used left to right, and no permutation is produced twice.
Example 1
Input
3 1 1 2
Output
1 1 2 1 2 1 2 1 1
Example 2
Input
3 3 1 2
Output
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
Hints
- Plain backtracking produces the same permutation once for each order of equal values.
- Sort first so equal values are next to each other.
- Use a copy of a value only if the previous equal copy is already used.
Approach
Sort the array and backtrack: at each position try every unused index i in increasing order, but skip i when a[i] == a[i − 1] and a[i − 1] is not used. This forces equal values to be placed in their original order, so each distinct permutation appears exactly once — and because candidates are tried in sorted order, the permutations come out lexicographically sorted.
Complexity: O(n · n!) time in the worst case · O(n) recursion depth
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int n;
vector<int> a, cur;
vector<bool> used;
string out;
void go() {
if ((int) cur.size() == n) {
for (int i = 0; i < n; i++) out += to_string(cur[i]) + (i + 1 < n ? " " : "\n");
return;
}
for (int i = 0; i < n; i++) {
if (used[i] || (i > 0 && a[i] == a[i - 1] && !used[i - 1])) continue;
used[i] = true;
cur.push_back(a[i]);
go();
cur.pop_back();
used[i] = false;
}
}
int main() {
cin >> n;
a.resize(n);
used.assign(n, false);
for (auto &x : a) cin >> x;
sort(a.begin(), a.end());
go();
cout << out;
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = sorted(data[1 : 1 + n])
used = [False] * n
cur = []
out = []
def go():
if len(cur) == n:
out.append(" ".join(map(str, cur)))
return
for i in range(n):
if used[i] or (i > 0 and a[i] == a[i - 1] and not used[i - 1]):
continue
used[i] = True
cur.append(a[i])
go()
cur.pop()
used[i] = False
go()
print("\n".join(out))Java solution
import java.util.*;
public class Main {
static int n;
static int[] a;
static boolean[] used;
static int[] cur;
static StringBuilder out = new StringBuilder();
static void go(int depth) {
if (depth == n) {
for (int i = 0; i < n; i++) out.append(cur[i]).append(i + 1 < n ? " " : "\n");
return;
}
for (int i = 0; i < n; i++) {
if (used[i] || (i > 0 && a[i] == a[i - 1] && !used[i - 1])) continue;
used[i] = true;
cur[depth] = a[i];
go(depth + 1);
used[i] = false;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
Arrays.sort(a);
used = new boolean[n];
cur = new int[n];
go(0);
System.out.print(out);
}
}Solve Unique Permutations with Duplicates online · All practice problems