#47

Permutations II

Medium Backtracking with duplicate skip

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return all distinct orderings of an array that may contain duplicates.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: distinct orderings when numbers repeat.

Why this works: sort, and only use a duplicate if its earlier twin is already used. That fixes the order of equal values, so each arrangement is built once.

Example: [1, 1, 2]

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

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Collecting into a Set to remove duplicates — it works, but generates n! permutations anyway.

Solve on LeetCode ↗
Complexity
  • Time: O(n · n!).
  • Space: O(n).
Topic: Recursion & Backtracking
🎬 Episodes 29–36: video coming soon