Skip to content
BytePatterns

Distinct Arrangements

MediumBacktracking#backtracking#pruning#sorting~30m

Problem

Given a list of values that may contain repeats, return every distinct ordering of all of them. Two orderings are the same when they read the same value by value, so repeats must not produce duplicate answers. Return the orderings in ascending lexicographic order so the output is predictable.

Examples

Input:  vals = [1, 2, 1]
Output: [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
Why:    3 slots with two equal values give 3!/2! = 3 orderings
Input:  vals = [2, 2, 2]
Output: [[2, 2, 2]]
Why:    every ordering reads the same
Input:  vals = []
Output: [[]]
Why:    edge case, there is exactly one way to arrange nothing

Hints

0 / 3

Stuck on the idea rather than the code? Permutations covers it.