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?- A. 2 8 36
- B. 3 8 36
- C. 3 8 24
- 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
- Problem: Can all matchsticks form a square (every stick used exactly once)? Backtrack placing sticks (longest first) into 4 sides…
- Problem: Insert '+', '−' or '' between the digits (or leave digits joined) so the expression equals the target. Operands may not have…
- Problem: A thief robs houses arranged as a binary tree; robbing two directly linked houses triggers an alarm. Each node returns (best if…
- Problem: Place the minimum number of cameras on tree nodes so every node is monitored (a camera covers itself, its parent and its…
- Problem: A tree of n nodes holds n coins in total, unevenly. A move transfers one coin between adjacent nodes. Minimum moves so every node…
- Problem: Return all node values at exactly distance k from a target node (distance counts edges, moving up or down). Record parent…