All distinct orders of [1, 1, 2]: how do you avoid repeats?
Question
Write distinct_orders(items). It returns every distinct order of the list as a tuple, each exactly once, in sorted order. Equal values can't be told apart: swapping the two 1s in (1, 1, 2) gives the same order, not a new one.
Don't build all n! orders and remove the repeats afterwards. Don't change the input list.
distinct_orders([1, 1, 2]) # [(1, 1, 2), (1, 2, 1), (2, 1, 1)] distinct_orders([]) # [()]
def distinct_orders(items): ...
Show hints (3)
- "COUNT, DON'T INDEX"
Picking the first 1 or the second 1 leads to the same results. Instead of picking positions, keep a
Counterof how many copies of each value are still free. - "ONE BRANCH PER VALUE"
At each step, loop over the distinct values in sorted order. Take a value only if its count is above 0. Equal values then never get two branches.
- "UNDO AND COPY"
After the recursive call, put the value back: pop it from the path and add 1 to its count. When the path is full, save
tuple(path), notpathitself.
Show checked explanation
Backtrack over value counts, not positions. Keep a Counter of the values still free. At each step, try each distinct value once if its count is above 0: take it, recurse, then put it back. Equal values never get separate branches, so no repeat is ever built and nothing needs removing afterwards.
from collections import Counter def distinct_orders(items): counts, path = Counter(items), [] def build(): if len(path) == len(items): yield tuple(path) # a copy: path keeps changing return for value in sorted(counts): if counts[value] > 0: counts[value] -= 1 path.append(value) yield from build() path.pop() # put the value back for the next branch counts[value] += 1 return list(build()) print(distinct_orders([1, 1, 2]), distinct_orders([]))
[(1, 1, 2), (1, 2, 1), (2, 1, 1)] [()]
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Here is the search for [1, 1, 2]. It starts with the counts {1: 2, 2: 1}:
| path so far | still free | next step |
|---|---|---|
| () | 1, 1, 2 | try 1, then 2 |
| (1,) | 1, 2 | try 1, then 2 |
| (1, 1) | 2 | save (1, 1, 2) |
| (1, 2) | 1 | save (1, 2, 1) |
| (2,) | 1, 1 | try 1 |
| (2, 1) | 1 | save (2, 1, 1) |
The first step has only two branches, 1 and 2, although the list holds three numbers. Code that picks positions would branch on the first 1 and again on the second 1. It would then build every order twice. itertools.permutations([1, 1, 2]) does exactly that: it returns 6 tuples, and only 3 are distinct.
The undo step matters. When the branch that starts with 1 is finished, both 1s are free again, so the branch that starts with 2 can still use them.
Why not sorted(set(itertools.permutations(items)))? It gives the right answer, but it builds all n! orders first. For nine 0s and one 1, that is 3,628,800 tuples for just 10 distinct orders.
How many results are there? Divide n! by the factorial of each count: 3!/2! = 3 for [1, 1, 2], and 4!/(2!·2!) = 6 for [1, 1, 2, 2]. Each result costs O(n) to copy, so the output alone takes O(n) times that number.
Because the values are tried in sorted order, the results come out sorted too.
Common mistakes
- Saving
pathinstead oftuple(path). Every result is then the same list, and the laterpopcalls empty it, so you get[[], [], []]. - Tracking used values in a set instead of counts. After the first 1, the set also blocks the second 1, so
[1, 1, 2]gives no results at all. - Forgetting
counts[value] += 1after the branch. The first result uses up every value, and you get only[(1, 1, 2)]. - Expecting it to work at any length. The recursion goes one level deeper per item, and Python's default limit is 1000, so
[7] * 1500raisesRecursionError, although it has only one order.
Follow-up questions
- "Now two equal values must never stand next to each other." Check before you take a value: skip it if it equals
path[-1]. Two equal neighbours stay next to each other in every longer path, so the branch can stop at once. For[1, 1, 2, 2]only (1, 2, 1, 2) and (2, 1, 2, 1) remain. - "Can you do it without a Counter?" Yes. Sort the list and keep a
usedflag for each index. Skip indexiifitems[i] == items[i - 1]and copyi - 1is not used yet. Equal values are then always taken left to right, so each order is built once.
What a strong answer covers
Explains where the repeats come from, equal values getting separate branches, and fixes that instead of filtering the output. Uses counts, puts values back after each branch and saves a copy of the path. Gives the n! over factorials count and mentions the recursion limit.
Open in interactive practice deck →