progress

~/problems / Backtracking

Permutations II

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~30 min

A shelf display uses a set of coloured blocks, and some blocks are the same colour. Write distinct_orderings(nums: list[int]) -> list[list[int]] that returns every different left-to-right arrangement of all the numbers in nums.

  • Equal numbers are interchangeable: swapping two equal numbers doesn't make a new arrangement. Return each arrangement exactly once.
  • The arrangements can come back in any order.
distinct_orderings([1, 1, 2])   # [[1, 1, 2], [1, 2, 1], [2, 1, 1]]  in some order
distinct_orderings([3, 3])      # [[3, 3]]
distinct_orderings([5])         # [[5]]

Constraints: 1 <= len(nums) <= 12, -10 <= nums[i] <= 10, and the answer has at most 40,000 arrangements.

Don't use itertools.

⭐ Bonus: a speed test with twelve numbers earns a star in time proportional to the size of the answer. Treated as all different they have 12! (about 479 million) orderings, so producing those and removing repeats is hopeless.

Show hint

build the arrangement one position at a time, but choose among the distinct values still available (keep a count of each), not among the individual positions of nums.

Topic: Recursion and backtracking. Choose, recurse, un-choose: subsets, permutations, N-queens, pruning.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc