Knight Dialer: Count Dialable Digit Sequences
WhatnotSoftware Engineer · Technical ScreenLast updated
Calculate the number of distinct n-digit phone numbers reachable by standard chess knight moves on a numeric keypad, modulo 10^9 + 7.
Knight Dialer: Count Dialable Digit Sequences
A chess knight is placed on a standard telephone keypad:
1 2 3
4 5 6
7 8 9
* 0 #
The knight can only step on numeric digits (0 through 9). It cannot land on * or #. A legal move consists of moving two squares vertically and one horizontally, or two squares horizontally and one vertically (the standard L-shape move in chess).
Given an integer n, return the total number of distinct numeric sequences of length n you can dial. You may start the knight on any numeric digit. Because the answer may be very large, return it modulo 10^9 + 7 (1000000007).
Function Signature
def knight_dialer(n: int) -> int:
pass
Constraints
1 <= n <= 5000
Examples
Example 1:
Input: n = 1
Output: 10
Explanation: With length 1, starting on any of the 10 digits produces a valid 1-digit sequence: [0], [1], ..., [9].
Example 2:
Input: n = 2
Output: 20
Explanation:
Starting on 0 gives: 04, 06 (2)
Starting on 1 gives: 16, 18 (2)
Starting on 2 gives: 27, 29 (2)
Starting on 3 gives: 34, 38 (2)
Starting on 4 gives: 40, 43, 49 (3)
Starting on 5 gives: none (0)
Starting on 6 gives: 60, 61, 67 (3)
Starting on 7 gives: 72, 76 (2)
Starting on 8 gives: 81, 83 (2)
Starting on 9 gives: 92, 94 (2)
Total = 2 + 2 + 2 + 2 + 3 + 0 + 3 + 2 + 2 + 2 = 20.
Example 3:
Input: n = 3
Output: 46
Edge Cases to Consider
n = 1: Digit5can be dialed once since no moves are required, but forn > 1, sequences starting or landing on5are impossible because5has no legal knight moves.- Large
n: Ensure transitions and running sums apply the modulo at each step to prevent overflow or unnecessary memory overhead.
Hints
Hint 1
Precompute an adjacency list mapping each digit from 0 to 9 to all digits reachable in a single knight move.
Hint 2
Notice that the number of paths of length k ending at digit d depends only on the number of paths of length k - 1 ending at d's neighbors.
Hint 3
You only need the digit counts from the previous step to compute the next step, allowing you to use O(1) auxiliary space.
Follow-up questions
- How would you optimize this solution to run in O(log n) time if n could be as large as 10^18?
- How does the solution change if certain keys are disabled dynamically (passed as a set of blocked digits)?
- Can you exploit the vertical symmetry of the keypad (e.g., digits 1 and 3 behave identically) to reduce the number of unique states?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.