The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Problem summary: The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagram: A chess knight can move as indicated in the chess diagram below: We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell). Given an integer n, return how many distinct phone numbers of length n we can dial. You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps. As the answer may be very large, return the answer modulo 109 + 7.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
1
Example 2
2
Example 3
3131
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #935: Knight Dialer
class Solution {
public int knightDialer(int n) {
final int mod = (int) 1e9 + 7;
long[] f = new long[10];
Arrays.fill(f, 1);
while (--n > 0) {
long[] g = new long[10];
g[0] = (f[4] + f[6]) % mod;
g[1] = (f[6] + f[8]) % mod;
g[2] = (f[7] + f[9]) % mod;
g[3] = (f[4] + f[8]) % mod;
g[4] = (f[0] + f[3] + f[9]) % mod;
g[6] = (f[0] + f[1] + f[7]) % mod;
g[7] = (f[2] + f[6]) % mod;
g[8] = (f[1] + f[3]) % mod;
g[9] = (f[2] + f[4]) % mod;
f = g;
}
return (int) (Arrays.stream(f).sum() % mod);
}
}
// Accepted solution for LeetCode #935: Knight Dialer
func knightDialer(n int) (ans int) {
f := make([]int, 10)
for i := range f {
f[i] = 1
}
const mod int = 1e9 + 7
for i := 1; i < n; i++ {
g := make([]int, 10)
g[0] = (f[4] + f[6]) % mod
g[1] = (f[6] + f[8]) % mod
g[2] = (f[7] + f[9]) % mod
g[3] = (f[4] + f[8]) % mod
g[4] = (f[0] + f[3] + f[9]) % mod
g[6] = (f[0] + f[1] + f[7]) % mod
g[7] = (f[2] + f[6]) % mod
g[8] = (f[1] + f[3]) % mod
g[9] = (f[2] + f[4]) % mod
f = g
}
for _, x := range f {
ans = (ans + x) % mod
}
return
}
// Accepted solution for LeetCode #935: Knight Dialer
struct Solution;
impl Solution {
fn knight_dialer(n: i32) -> i32 {
let max = 1_000_000_007;
let n = n as usize;
let mut dp: [[usize; 10]; 2] = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];
let map = vec![
vec![4, 6],
vec![6, 8],
vec![7, 9],
vec![4, 8],
vec![0, 3, 9],
vec![],
vec![0, 1, 7],
vec![2, 6],
vec![1, 3],
vec![2, 4],
];
let mut res = 10;
for i in 1..n {
res = 0;
for j in 0..10 {
let mut sum = 0;
for &k in &map[j] {
sum += dp[(i - 1) % 2][k];
sum %= max;
}
dp[i % 2][j] = sum;
res += dp[i % 2][j];
res %= max;
}
}
res as i32
}
}
#[test]
fn test() {
let n = 1;
let res = 10;
assert_eq!(Solution::knight_dialer(n), res);
let n = 2;
let res = 20;
assert_eq!(Solution::knight_dialer(n), res);
let n = 3;
let res = 46;
assert_eq!(Solution::knight_dialer(n), res);
let n = 161;
let res = 533_302_150;
assert_eq!(Solution::knight_dialer(n), res);
}
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(log n)
Space
O(|\Sigma|^2)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.