Skip to main content

Knight Dialer - Solution & Explanation

MediumDynamic Programming40 min readAsked at: Amazon, Meta, Google +3
Practice this problem

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. 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.

 

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.

 

Constraints:

  • 1 <= n <= 5000

Approach Overview

Problem Overview: A knight moves on a classic phone keypad (0–9). Starting from any digit, the knight makes n-1 moves. Each move must follow chess knight rules. The task is to count how many distinct number sequences of length n can be dialed. Results are returned modulo 1e9+7.

Approach 1: Dynamic Programming (O(n) time, O(n) space)

The keypad can be modeled as a small directed graph where each digit connects to the digits reachable by a knight move. For example, 1 β†’ {6,8}, 4 β†’ {0,3,9}, and 5 has no valid moves. Use Dynamic Programming where dp[i][d] represents the number of sequences of length i ending at digit d. Initialize all digits with value 1 for length 1. For every step, iterate through digits and distribute counts to their reachable neighbors. The key insight is that the number of ways to reach a digit depends only on the previous step’s reachable digits. This transforms a potentially exponential search into a linear DP transition. Time complexity is O(n) because the digit set is constant (10), and space complexity is O(n) if you keep the full DP table. This approach clearly demonstrates state transitions and is easy to reason about during interviews. The technique is a classic example of Dynamic Programming applied to a small graph transition system.

Approach 2: Optimized Dynamic Programming with Space Reduction (O(n) time, O(1) space)

The DP state for step i depends only on step i-1. Storing the entire n Γ— 10 table is unnecessary. Instead, keep two arrays: one for the current counts and one for the next counts. After computing transitions for all digits, swap them and continue. This reduces memory usage from O(n) to constant O(10), effectively O(1). Each iteration still processes a fixed set of knight transitions, so time remains O(n). This version is typically what production code or competitive programming solutions use. The logic is identical to the full DP table but relies on rolling state updates, a common pattern in dynamic programming problems where only the previous row matters.

Recommended for interviews: Start by describing the keypad as a graph of knight transitions. Explain the DP state dp[i][digit] and the recurrence that accumulates counts from reachable digits. Once the interviewer agrees with the state transition, mention the rolling-array optimization that reduces memory to O(1). Demonstrating both the straightforward DP and the space-optimized version shows strong understanding of DP state reduction patterns.

Approach 1: Dynamic Programming Approach

This approach uses dynamic programming to store and reuse the number of dialable numbers of length n starting from each digit. We maintain a 2D DP table where dp[i][j] indicates how many numbers of length i can start from digit j.

The primary idea is to iterate from i=1 to n, updating the DP table based on the moves possible from each digit in the previous state.

This function uses dynamic programming to calculate the number of valid phone numbers. The moves are stored in a dictionary with each digit pointing to its possible knight moves. We initialize a 2D list dp where dp[i][j] represents the number of numbers of length i+1 starting from digit j. The result is obtained by summing up the values in the last row of the dp table.

Code

Python

Java

C++

Complexity

Time Complexity: O(n) for each of the 10 digits, resulting in O(10n) operations.
Space Complexity: O(10n) due to the DP table.

Try this approach in the editor β†’

Approach 2: Optimized Dynamic Programming with Space Reduction

This approach optimizes the dynamic programming technique by reducing space complexity. Instead of using a full 2D array, we use two 1D arrays to track only the current and the previous state, thus reducing the space required from O(n*10) to O(20).

This function uses a space-efficient dynamic programming approach. Instead of maintaining a 2D table, it uses two lists: prev and curr, which track the current and previous counts of numbers of length n. The prev list is updated at each step to effectively simulate the transition from i to i+1 without maintaining an entire history.

Code

Python

Java

C++

Complexity

Time Complexity: O(n) - iterating over digits with constant time calculations;
Space Complexity: O(10) as we only hold current and previous state arrays.

Try this approach in the editor β†’

Approach 3: Recurrence

According to the problem description, we need to calculate the number of different phone numbers of length n. Each digit can only follow certain fixed digits, which we can list as follows:

Current Digit Previous Digits
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

We can use a recurrence approach to calculate the number of different phone numbers of length n. Let f[i] represent the number of different phone numbers of length i. Initially, f[1] = 1. For phone numbers of length i, we can calculate them based on phone numbers of length i - 1. Therefore, we can derive the recurrence relations:

$ \begin{aligned} 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] \end{aligned}

Then, we update f to g and continue calculating the phone numbers of the next length until we calculate the number of phone numbers of length n.

Finally, we sum all the elements in f and take the result modulo 10^9 + 7 to get the answer.

The time complexity is O(n), where n is the length of the phone number. The space complexity is O(|\Sigma|), where \Sigma is the set of digits, and in this problem |\Sigma| = 10$.

Code

Python

Java

C++

Go

TypeScript

C#

Try this approach in the editor β†’

Approach 4: Matrix Exponentiation to Accelerate Recurrence

Let's denote T(n) as a 1 times 10 matrix \begin{bmatrix} F_0 & F_1 & F_2 cdots F_9 \end{bmatrix}, where F_i represents the number of phone numbers ending with digit i. We want to derive T(n) from T(n - 1). In other words, we need a matrix base such that T(n - 1) times base = T(n), i.e.:

$ \begin{bmatrix} F_0 & F_1 & F_2 cdots F_9 \end{bmatrix} times base = \begin{bmatrix} F_0' & F_1' & F_2' cdots F_9' \end{bmatrix}

Since F_i' = sum_{j} F_j, where j is the previous digit of i, the first column of the matrix base is:

\begin{bmatrix} 0 \ 0 \ 0 \ 0 \ 1 \ 0 \ 1 \ 0 \ 0 \ 0 \end{bmatrix}

Similarly, we can derive the entire matrix base as follows:

\begin{bmatrix} 0 & 0 & 0 & 0 & 1 & 0 & 1 & 0 & 0 & 0 \ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 1 & 0 \ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 1 \ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 \ 1 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 1 \ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \ 1 & 1 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \ 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \ 0 & 1 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \ 0 & 0 & 1 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \end{bmatrix}

We define the initial matrix res = \begin{bmatrix} 1 & 1 & 1 cdots 1 \end{bmatrix}, and multiply it by the matrix base raised to the power of n - 1 to obtain T(n). Finally, we sum all elements in T(n) and take the result modulo 10^9 + 7 to get the answer. The matrix base^{n - 1} can be computed using matrix exponentiation, which has a time complexity of O(log n).

The time complexity is O(log n), and the space complexity is O(|\Sigma|^2), where \Sigma is the set of digits, and in this problem |\Sigma| = 10$.

Code

Python

Java

C++

Go

TypeScript

C#

Try this approach in the editor β†’

Complexity Comparison

ApproachComplexity
Dynamic Programming Approach

Time Complexity: O(n) for each of the 10 digits, resulting in O(10n) operations.
Space Complexity: O(10n) due to the DP table.

Optimized Dynamic Programming with Space Reduction

Time Complexity: O(n) - iterating over digits with constant time calculations;
Space Complexity: O(10) as we only hold current and previous state arrays.

Recurrenceβ€”
Matrix Exponentiation to Accelerate Recurrenceβ€”

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Dynamic Programming (Full DP Table)O(n)O(n)Best for explaining the DP state transition clearly in interviews
Optimized DP with Rolling ArrayO(n)O(1)Preferred implementation when memory efficiency matters

Video Solution

Knight Dialer - Leetcode 935 - Python β€’ NeetCodeIO β€’ 12,475 views views

Watch 9 more video solutions β†’

Frequently Asked Questions

Is Knight Dialer easy or hard?
Knight Dialer is rated Medium difficulty. The challenge is recognizing the keypad as a graph and defining the correct DP state transition. Once the recurrence is clear, the implementation is straightforward and can be optimized to constant space.
Knight Dialer Python/Java solution
Most implementations define a transition map for knight moves and iterate nβˆ’1 times updating counts for each digit. The same DP logic works in Python, Java, and C++ with modulo arithmetic (1e9+7). Space can be reduced to two arrays or a single rolling array.
How to solve Knight Dialer in O(n)?
Use dynamic programming where dp[d] stores the number of sequences ending at digit d for the current step. For each move, compute the next counts using the knight transition map (for example 1β†’6,8 and 4β†’0,3,9). Repeat this process nβˆ’1 times and sum the final counts modulo 1e9+7.
What is the best approach for Knight Dialer?
Dynamic Programming with rolling state optimization is the best approach. Model the keypad as a graph of knight moves and track how many sequences end at each digit after every step. This runs in O(n) time because each step processes a constant number of digits (10) and uses O(1) space with a rolling array.
Is Knight Dialer asked at Google/Amazon/Meta?
Knight Dialer appears in interview preparation lists and has been reported in interviews at companies that test dynamic programming and graph traversal patterns, including large tech companies. It checks whether candidates can model state transitions efficiently and optimize DP space.
What data structure is used in Knight Dialer?
The solution uses arrays for dynamic programming and an adjacency list or mapping that represents valid knight moves between digits. The keypad effectively becomes a small directed graph where DP propagates counts along edges.
What is the time complexity of Knight Dialer?
The optimal solution runs in O(n) time. For each of the n moves, the algorithm updates counts for the 10 digits based on predefined knight transitions. Since the digit set is fixed, the work per step is constant.

Ready to solve this problem?

Practice Knight Dialer with our built-in code editor and test cases.

Practice on FleetCode