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?- A. 8 8
- B. 6 10
- C. 8 10
- 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
- Problem: Each candidate can be used at most ONCE and the list has duplicates; count the distinct combinations that sum to the target…
- Problem: Divide two integers without , / or %, truncating toward zero, using doubling (shifts). python def divide(a, b): neg = (a < 0) !=…
- Problem: Traverse a matrix along anti-diagonals, alternating direction (up-right first). python def diag(m): R, C = len(m), len(m[0]); out…
- Edge case: building a 3 × 3 grid with list multiplication. python grid = [[0] 3] 3 grid[0][0] = 1 print(grid) What is printed?
- Edge case: lambdas created in a loop (closures). python fs = [lambda: i 10 for i in range(3)] gs = [lambda i=i: i 10 for i in range(3)]…
- Edge case: JavaScript event-loop ordering of synchronous code, a promise callback and a timer. javascript const out = []; out.push("A")…