Problem Description
Given a standard phone keypad where only the numeric keys are allowed as starting positions, a chess knight makes valid L-shaped moves (two squares in one direction and one square perpendicular), and you must count the number of distinct phone numbers of length n that can be dialed. Each move must be a valid knight move and the answer should be returned modulo 10^9 + 7.
Key Insights
- The knight's move is restricted by the keypad design, so precompute which digits can reach which others.
- Dynamic Programming is applied where dp[i][j] represents the ways to reach digit j after i moves.
- Only the numeric keys are valid positions, with digit 5 being isolated (no valid moves from it).
- Use a rolling DP array (or update in-place) because the state at step i only depends on step i-1.
- For each iteration, compute the cumulative number of dial sequences for each digit and take the modulo at each step.
Space and Time Complexity
Time Complexity: O(n) – For each move, a constant number of transitions (at most 3 per digit) are computed. Space Complexity: O(1) – Only a fixed size (10 elements) DP array is needed for computation.
Solution
We approach this problem using Dynamic Programming (DP). Start by defining a mapping for each digit that lists the reachable digits using valid knight moves on the keypad. Initialize a DP array with 10 entries, each set to 1, since starting from any digit constitutes a valid single-digit number. For each move (from 2 to n digits), compute a new DP array by summing counts from previous positions based on the knight move mapping. At each step, update using modulo 10^9 + 7 to handle large numbers. Finally, the sum of the entries in the DP array after n moves gives the total number of distinct phone numbers.