Leetcode #935: Knight Dialer
In this guide, we solve Leetcode #935 Knight Dialer in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
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.
Python Solution
class Solution:
def knightDialer(self, n: int) -> int:
f = [1] * 10
for _ in range(n - 1):
g = [0] * 10
g[0] = f[4] + f[6]
g[1] = f[6] + f[8]
g[2] = f[7] + f[9]
g[3] = f[4] + f[8]
g[4] = f[0] + f[3] + f[9]
g[6] = f[0] + f[1] + f[7]
g[7] = f[2] + f[6]
g[8] = f[1] + f[3]
g[9] = f[2] + f[4]
f = g
return sum(f) % (10**9 + 7)
Complexity
The time complexity is , where is the length of the phone number. The space complexity is , where is the set of digits, and in this problem .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.