Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Generate all permutations of a list that may contain duplicates, without repeats. How many are produced?

Problem: Generate all permutations of a list that may contain duplicates, without repeats. How many are produced?
def perms(a):
    a.sort(); out, used, cur = [], [False] * len(a), []
    def bt():
        if len(cur) == len(a): out.append(cur[:]); return
        for i in range(len(a)):
            if used[i] or (i and a[i] == a[i-1] and not used[i-1]): continue
            used[i] = True; cur.append(a[i]); bt(); cur.pop(); used[i] = False
    bt()
    return len(out), out[1]
print(perms([1, 2, 1, 2]))
What is printed?
  1. A. (6, [1, 2, 1, 2])
  2. B. (24, [1, 1, 2, 2])
  3. C. (6, [1, 1, 2, 2])
  4. D. (12, [1, 2, 1, 2])

Correct answer: A. (6, [1, 2, 1, 2])

Sorting groups equal values; a duplicate may be used only after its earlier twin is already in the current permutation, which removes repeated orderings. 4!/(2!·2!) = 6 distinct permutations; the first is [1,1,2,2] and the second [1,2,1,2]. Without the skip rule all 24 are generated.

More Coding Interview Problems questions

Exams that ask this topic