Python coding

Every distinct ordering

Given a list nums of integers that may contain repeated values, return every distinct ordering of the whole list. Two orderings are the same if they show the same values in the same positions, so [1, 1, 2] has 3 orderings, not 6. Each one must appear exactly once; you may return them in any sequence.

1 ≤ len(nums) ≤ 7, and nums is not necessarily sorted.

  • distinct_orderings([1,2,3]) → [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
  • distinct_orderings([1,1,2]) → [[1,1,2],[1,2,1],[2,1,1]]
  • distinct_orderings([2,2]) → [[2,2]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Build the ordering one position at a time: choose any number not used yet, recurse, then undo. A used list of booleans tracks which indexes are in the current path.

Hint 2

Repeats create duplicates when two equal values are tried for the same position. Sort first, so equal values sit side by side and are easy to spot.

Hint 3

Skip nums[i] when it equals nums[i - 1] and nums[i - 1] is not in use. Equal values then enter the path only in index order, so each ordering is built once.

Solution and why it works
pythonO(n·n!) in the worst case (all values distinct) · O(n) recursion depth, beyond the output
def distinct_orderings(nums: list[int]) -> list[list[int]]:
    nums = sorted(nums)                  # equal values end up side by side
    used = [False] * len(nums)
    res, path = [], []

    def bt() -> None:
        if len(path) == len(nums):
            res.append(path[:])          # copy: path keeps changing
            return
        for i, x in enumerate(nums):
            if used[i] or (i > 0 and x == nums[i - 1] and not used[i - 1]):
                continue                 # taken, or a twin that must wait for the one before it
            used[i] = True
            path.append(x)
            bt()
            path.pop()
            used[i] = False

    bt()
    return res

Each level fills one position with a number whose index is still unused, so a full path is an ordering. With repeats, two equal values tried at the same position start identical subtrees. After sorting, skipping nums[i] when it equals nums[i-1] and that twin is unused lets equal values enter only in index order, so every ordering is built exactly once. Traps: skipping without sorting misses twins that are apart ([1, 2, 1]), and res.append(path) stores one aliased list.