Editor

Distinct Rearrangements

#119 · Recursion and backtracking · Advanced · 115 XP · about 20 min

Write unique_permutations(items) that returns every different ordering of the list items, each as a list. When items contains repeated values, an ordering must still appear only once. Return the orderings sorted, in Python's ordering of lists.

Examples

unique_permutations([1, 2, 3])
# returns [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
unique_permutations([1, 1, 2])        # returns [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
unique_permutations(["b", "a", "b"])  # returns [['a', 'b', 'b'], ['b', 'a', 'b'], ['b', 'b', 'a']]

[1, 1, 2] has 6 orderings if the two 1s are told apart, but only 3 different ones when they are not.

Constraints

  • 0 <= len(items) <= 8
  • The items are all numbers or all strings, so they can be compared.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.