Data Structures & AlgorithmsVery hardProduct company OA

Problem: Count permutations p of 1..n where for every position i (1-based) p[i] is divisible by i or i is divisible by p[i] (backtracking with pruning).

Problem: Count permutations p of 1..n where for every position i (1-based) p[i] is divisible by i or i is divisible by p[i] (backtracking with pruning).
def arrangements(n):
    used = [False] * (n + 1)
    def bt(pos):
        if pos > n: return 1
        c = 0
        for v in range(1, n + 1):
            if not used[v] and (v % pos == 0 or pos % v == 0):
                used[v] = True; c += bt(pos + 1); used[v] = False
        return c
    return bt(1)
print(arrangements(3), arrangements(4), arrangements(6))
What is printed?
  1. A. 2 8 36
  2. B. 3 8 36
  3. C. 3 8 24
  4. D. 6 24 720

Correct answer: B. 3 8 36

Pruning at each position keeps the search far below n!. n = 3: 123, 213, 321 → 3 (132 fails because 3 at position 2). n = 4 → 8, n = 6 → 36. A bitmask DP over (position, used set) gives O(n · 2ⁿ) for larger n (up to ~20).

More Coding Interview Problems questions

Exams that ask this topic