Data Structures & AlgorithmsHardProduct company OA

Problem: A chess knight hops on a phone keypad (1-9 in a 3 × 3 grid, 0 below 8). Count the distinct numbers of length n it can dial (start on any digit, every hop is a knight move).

Problem: A chess knight hops on a phone keypad (1-9 in a 3 × 3 grid, 0 below 8). Count the distinct numbers of length n it can dial (start on any digit, every hop is a knight move).
def dialer(n):
    moves = {0: (4, 6), 1: (6, 8), 2: (7, 9), 3: (4, 8), 4: (0, 3, 9), 5: (),
             6: (0, 1, 7), 7: (2, 6), 8: (1, 3), 9: (2, 4)}
    dp = [1] * 10
    for _ in range(n - 1):
        dp = [sum(dp[p] for p in moves[d]) for d in range(10)]
    return sum(dp)
print(dialer(1), dialer(2), dialer(3))
What is printed?
  1. A. 10 20 46
  2. B. 10 18 46
  3. C. 9 20 46
  4. D. 10 20 40

Correct answer: A. 10 20 46

dp[d] = numbers of the current length ending on digit d; each step sums over digits that reach d. Length 1: all 10 digits. Length 2: the move lists have 2+2+2+2+3+0+3+2+2+2 = 20 entries. Length 3 → 46. 5 has no moves, so it only counts for n = 1. O(n) with a fixed 10-state table (matrix power for huge n).

More Coding Interview Problems questions

Exams that ask this topic