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 - Unique Permutations INPUT nums = [1, 1, 2] 1 1 2 idx 0 idx 1 idx 2 Contains Duplicates! Two 1's in array After sorting: [1, 1, 2] 1 1 2 Sorting helps skip duplicates Goal: Find unique perms Expected: 3 permutations ALGORITHM STEPS 1 Sort Array Group duplicates together 2 Track Used Elements Boolean array for visited 3 Skip Duplicates If prev same and unused 4 Backtrack Build permutations recursively Decision Tree (Pruned) [ ] [1] [2] skip dup [1,1] [1,2] [2,1] [1,1,2] [1,2,1] [2,1,1] FINAL RESULT 3 Unique Permutations Perm 1: 1 1 2 OK Perm 2: 1 2 1 OK Perm 3: 2 1 1 OK Output: [[1,1,2],[1,2,1],[2,1,1]] Complexity Time: O(n! * n) Space: O(n) recursion Key Insight: Sort the array first to group duplicates. Skip a number if it equals the previous number AND the previous number hasn't been used yet (used[i-1] == false). This ensures each duplicate is only used in sequence, preventing duplicate permutations while still allowing repeated elements in valid arrangements. TutorialsPoint - Permutations II | Backtracking with Duplicate Pruning
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