Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Generate unique permutations from a list

Return all unique permutations of a list that may contain duplicates.

Python practice17 minRecursion & BacktrackingIntermediateLast updated March 27, 2026

Problem statement

Given a list of integers nums that may contain duplicates, return all unique permutations of nums. Each permutation should be represented as a list. The returned list of permutations must be sorted lexicographically (list comparison). Use backtracking and skip duplicate choices to ensure each permutation is generated once.

Task

Practice backtracking with duplicate handling to generate all unique permutations in a deterministic (sorted) order.

Examples

Example with duplicates

Input

nums = [1,1,2]

Output

[[1, 1, 2], [1, 2, 1], [2, 1, 1]]

Although there are 3! = 6 permutations with duplicates considered, only 3 unique permutations exist.

Input format

A list of integers nums (may be empty) possibly containing duplicates.

Output format

A list of unique permutations (each a list). The overall list is sorted lexicographically.

Constraints

- 0 <= len(nums) <= 8 - -10^6 <= nums[i] <= 10^6 - Use backtracking with a visited array and skip duplicate values - Return permutations sorted for deterministic outputs

Samples

Sample 1

Input

nums = [0,1,0]

Output

[[0, 0, 1], [0, 1, 0], [1, 0, 0]]

Unique permutations of [0,1,0], sorted lexicographically.