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?- A. 10 20 46
- B. 10 18 46
- C. 9 20 46
- 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
- Problem: Trade a stock any number of times (hold at most one share); each completed sale pays a fixed fee. Maximise profit with two…
- Problem: Is c formed by interleaving a and b (keeping each string's internal order)? dp[i][j] = first i chars of a and j chars of b can…
- Problem: Wildcard matching over the whole string: '?' matches any one character, '' matches any sequence (including empty). python def…
- Problem: Return (length of the longest strictly increasing subsequence, number of such longest subsequences). python def numlis(a): n =…
- Problem: With k identical eggs and an n-floor building, find the minimum number of drops that guarantees finding the critical floor. DP on…
- Problem: Two players alternately take a pile from either END of a row; both play optimally. Compute (first player's total − second…