Knight Dialer - Problem

Imagine you have a chess knight placed on a phone dialer pad! A knight moves in an L-shape: either 2 squares vertically and 1 horizontally, or 2 squares horizontally and 1 vertically.

The phone pad looks like this:

1 2 3
4 5 6
7 8 9
  0

Given an integer n, determine how many distinct phone numbers of length n you can dial by moving the knight around the pad. You can start on any numeric key (0-9), then make exactly n-1 valid knight moves.

Goal: Count all possible phone numbers of length n that can be formed by valid knight moves.

Note: Since the answer can be very large, return it modulo 10^9 + 7.

Input & Output

example_1.py — Small Case
$ Input: n = 1
Output: 10
💡 Note: With only 1 digit, we can start on any of the 10 digits (0-9) and don't need to make any moves. So there are 10 possible phone numbers of length 1.
example_2.py — Two Digits
$ Input: n = 2
Output: 20
💡 Note: For length 2, we need exactly 1 knight move. From digit 5, no moves are possible. From other digits, we can make various moves: 0→4,6; 1→6,8; 2→7,9; etc. Total valid 2-digit numbers: 20.
example_3.py — Larger Case
$ Input: n = 3131
Output: 136006598
💡 Note: For very large n, the number of possible phone numbers grows exponentially, but due to the modulo operation (10^9 + 7), we return 136006598.

Constraints

  • 1 ≤ n ≤ 5000
  • Answer should be returned modulo 109 + 7
  • Knight can start on any digit (0-9)
  • All moves must be valid knight moves within the phone pad

Visualization

Tap to expand
Knight Dialer Problem INPUT 1 2 3 4 5 6 7 8 9 * 0 # K Input: n = 1 (length of phone number) ALGORITHM STEPS 1 Define Moves Map each digit to reachable digits via L-shape moves 2 Base Case (n=1) Each digit counts as 1 Total: 10 starting points 3 DP Transition dp[i] = sum of dp[j] for all j reachable from i 4 Sum Results Add all dp values mod 10^9 + 7 Knight Move Map: 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] FINAL RESULT For n = 1: 0 1 2 3 4 5 6 7 8 9 Each digit = 1 valid number No moves needed (n=1) Calculation: 1+1+1+1+1+1+1+1+1+1 Output: 10 OK Key Insight: This is a Dynamic Programming problem. The knight's L-shaped movement creates a graph where each digit connects to specific other digits. For n=1, we simply count starting positions (10 digits). For larger n, we iterate and sum paths. Note: digit 5 has no valid moves! Time: O(n), Space: O(1). TutorialsPoint - Knight Dialer | Optimal Solution (Dynamic Programming)
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
67.0K Views
High Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen