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?- A. (6, [1, 2, 1, 2])
- B. (24, [1, 1, 2, 2])
- C. (6, [1, 1, 2, 2])
- 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
- Problem: Generate all valid strings of n pairs of brackets in lexicographic order of the recursion ('(' tried first). python def gen(n)…
- Problem: Count the ways to place n queens on an n × n board so none attack each other. python def queens(n): cols, d1, d2 = set(), set()…
- Problem: Find whether a word exists in a letter grid by moving to adjacent (up/down/left/right) cells without reusing a cell. python def…
- Problem: List all combinations of k numbers from 1..n that sum to s (each number used at most once). python def combo(k, s, n=9): out = []…
- Problem: The recursive function below counts calls. How many times is f called for f(5)? python calls = 0 def f(n): global calls calls +=…
- Problem: Compute xⁿ by fast exponentiation (recursive squaring) and count multiplications. python mults = 0 def power(x, n): global mults…