Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Count permutations of 1..n where, for every position i (1-based), the value is divisible by i or i is divisible by the value.

Problem: Count permutations of 1..n where, for every position i (1-based), the value is divisible by i or i is divisible by the value.
def count(n):
    used = [False] * (n + 1)
    def go(i):
        if i > n: return 1
        t = 0
        for v in range(1, n + 1):
            if not used[v] and (v % i == 0 or i % v == 0):
                used[v] = True; t += go(i + 1); used[v] = False
        return t
    return go(1)
print(count(4), count(5))
What is printed?
  1. A. 8 8
  2. B. 6 10
  3. C. 8 10
  4. D. 4 10

Correct answer: C. 8 10

Backtracking places a value at each position only if the divisibility test passes. For n = 4 there are 8 such permutations; n = 5 adds value 5, which can only sit at position 1 or 5, giving 8 10 in total.

More Coding Interview Problems questions

Exams that ask this topic