Permutations II - Problem

Given a collection of numbers nums that might contain duplicates, return all possible unique permutations in any order.

A permutation is a rearrangement of elements where order matters. Since the input may contain duplicate numbers, we need to ensure that our result contains only unique permutations (no duplicate permutations in the output).

Key Challenge: Handle duplicate elements properly to avoid generating duplicate permutations.

Input & Output

Example 1 — With Duplicates
$ Input: nums = [1,1,2]
Output: [[1,1,2],[1,2,1],[2,1,1]]
💡 Note: The input has duplicate 1s. All unique permutations are: [1,1,2], [1,2,1], and [2,1,1]. Note that [1,1,2] appears only once in output despite having two 1s.
Example 2 — All Duplicates
$ Input: nums = [1,2,1,1]
Output: [[1,1,1,2],[1,1,2,1],[1,2,1,1],[2,1,1,1]]
💡 Note: Three 1s and one 2. The unique permutations arrange the three 1s in different positions with the single 2.
Example 3 — No Duplicates
$ Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
💡 Note: No duplicate elements, so we get all 3! = 6 possible permutations of the three distinct numbers.

Constraints

  • 1 ≤ nums.length ≤ 8
  • -10 ≤ nums[i] ≤ 10

Visualization

Tap to expand
Permutations II: Generate Unique Permutations112Input: [1,1,2] (has duplicates)↓ Generate All Unique Arrangements ↓[1,1,2][1,2,1][2,1,1]Output: 3 unique permutationsNo duplicates like [1,1,2], [1,1,2] in result
Understanding the Visualization
1
Input
Array [1,1,2] with duplicate elements
2
Process
Generate all unique arrangements
3
Output
3 unique permutations: [[1,1,2],[1,2,1],[2,1,1]]
Key Takeaway
🎯 Key Insight: Sort first, then skip duplicates at the same recursion level to avoid generating duplicate permutations
Asked in
Microsoft 35 Amazon 28 Google 25 Apple 22
216.0K Views
Medium Frequency
~25 min Avg. Time
7.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen