Knight Dialer solution explained

Knight Dialer counts how many digit strings of length n a chess knight can type on a phone keypad, starting on any digit and jumping between digits. Keep ten counters, one per digit, for the strings of the current length ending there; each step, every digit passes its count to the two or three digits a knight can reach from it. That is O(n) time with O(1) memory. For very large n, raising the 10 by 10 jump matrix to the power n - 1 brings it to O(log n) matrix products.

By Published 7 min read

The problem in plain words

A phone keypad has three columns and four rows: 1 2 3 on top, then 4 5 6, then 7 8 9, and finally *, 0, # on the bottom row. A chess knight moves two squares in one direction and one square at a right angle. Place the knight on any digit key and make n - 1 knight moves, landing only on digit keys (never on * or #). The keys you visit, in order, spell an n-digit string. Count the distinct strings you can make. The total becomes huge quickly, so return it modulo 1,000,000,007.

Knight moves on the keypad, checked against coordinates in testing
FromCan jump toFromCan jump to
16, 860, 1, 7
27, 972, 6
34, 881, 3
40, 3, 992, 4
5nowhere04, 6
Knight moves on the keypad, checked against coordinates in testing. Scroll sideways on a small screen.
Counts computed by the code on this page
nStringsnStrings
1105240
2201014,912
3462058,689,536
4104100540,641,702 after the remainder
Counts computed by the code on this page. Scroll sideways on a small screen.

What the interviewer is checking

Knight Dialer is a friendly way to test whether you see a graph and a step count hiding in a puzzle. The interviewer watches for three things: writing the jump table correctly (most bugs live there), framing the count as 'strings of length k ending at digit d', and noticing that each step only needs the previous step. Candidates who also mention the matrix-power speed-up, or the symmetry that shrinks ten counters to four, usually leave a strong impression. Handling key 5 cleanly is a small but telling detail.

Brute force: walk every path

From each starting digit, recursively try every jump until n digits have been typed, and count the completed strings. It is easy to write and very slow: digits 4 and 6 branch three ways, the rest two, so the work grows exponentially. For n = 12 it already visits 78,080 complete strings, and the count keeps multiplying with every extra digit. It is the reference used in testing.

@@knight-dialer/slow.py@@
Python: exhaustive walk over the jump table.

The pattern: counts per ending digit

The brute force repeats itself: the number of ways to finish from digit 4 with three moves left is the same no matter how you got to 4. So count by ending digit. Let ends[d] be the number of strings of the current length that end on d. For length 1, every ends[d] is 1. To grow by one digit, each d hands its count to every key it can jump to. After n - 1 rounds, add up the ten counters. Each round does at most 20 additions, so the whole thing is linear in n with ten numbers of memory.

@@knight-dialer/fast.py@@
Python: the ten-counter DP, plus matrix exponentiation for huge n.

The second function treats the jump table as a 10 by 10 matrix M, where M[i][j] is 1 when the knight can go from i to j. Entry (i, j) of M^k counts walks of k jumps from i to j, so the answer is the sum of every entry of M^(n - 1). Repeated squaring reaches that power with about log2(n) squarings plus one extra product for each 1 bit of n - 1, each product costing 1,000 multiply-adds. In one timing run on the test machine, the linear loop took about 2.4 seconds for n = 1,000,000 in Python and the matrix version took about 2 milliseconds. Exact timings will differ on other machines, but the gap grows with n.

The linear version ports straight to JavaScript, because it only adds numbers below the modulus. A matrix version in JavaScript needs more care: two values just under 1,000,000,007 multiply to about 10^18, which is beyond the 2^53 range of exact numbers. Use BigInt for the products or split each factor into high and low halves.

@@knight-dialer/fast.js@@
JavaScript: the linear DP, safe with ordinary numbers.

A symmetry follow-up

The jump table stays the same if you swap the left and right columns, or swap the top row with the third row, so digits fall into groups with identical counts: the corners 1, 3, 7, 9; the middle column 2 and 8; the sides 4 and 6; and 0 by itself. A corner jumps to one side digit and one middle-column digit. A middle-column digit jumps to two corners. A side digit jumps to two corners and to 0. And 0 jumps to the two sides. Tracking one counter per group gives four update rules instead of twenty, and the testing confirmed the totals match the full table. It is a nice extra to mention, not something interviewers require.

Complexity

n is the length of the string
ApproachTimeExtra memory
Walk every pathExponential in nO(n) call stack
Memoized recursion on (digit, moves left)O(n)O(n) cache and stack
Ten counters, one round per digit addedO(n)O(1)
Matrix power of the 10 by 10 jump matrixO(log n) products, each 1,000 multiply-addsO(1)
n is the length of the string. Scroll sideways on a small screen.

Edge cases

  • n = 1: all ten digits count, including 5. The loop runs zero times and the sum is 10.
  • n = 2: key 5 contributes nothing from here on, and the answer is 20, the number of (digit, jump) pairs.
  • Very large n: take the remainder after every addition, and consider the matrix power.
  • A variant that forbids starting on certain digits: set those starting counters to 0 instead of 1.

Common mistakes

  • Typing the jump table from memory and getting one entry wrong. Derive it from coordinates or double-check that every jump is listed in both directions.
  • Updating the counters in place, so a digit's new value is read as an old one in the same round.
  • Running n rounds instead of n - 1: a string of n digits has n - 1 jumps.
  • Forgetting key 5 at n = 1, or adding it back at later lengths.
  • Multiplying in JavaScript without BigInt in a matrix version, which silently loses precision.

How to explain it out loud

Fictional example

From a keypad puzzle to a small graph
Candidate
The keys are nodes and knight moves are edges, so I'm counting walks of length n minus 1. Let me write the edges out first, because that's where I'd make a mistake.
Candidate
How I got to a digit doesn't matter for what comes next, so I'll keep a count per ending digit. Each round, every digit adds its count to its neighbours. Linear time, ten numbers.
Interviewer
And if n were a billion?
Candidate
Then I'd raise the ten by ten adjacency matrix to the n minus 1 power by repeated squaring and sum the entries. That's about thirty squarings plus a few extra products.

Count Vowels Permutation is the same idea with five letters and a 'may follow' table in place of knight jumps. Domino and Tromino Tiling also reduces to a short recurrence that a matrix power can speed up. Number of Dice Rolls With Target Sum builds counts one step at a time over totals. Fibonacci Number is the simplest example of trading a loop for fast exponentiation.

Practicing with Natively

Most Knight Dialer bugs come from the jump table, which is worth catching while practicing, not in front of an interviewer. On Mac or Windows, Natively can read the keypad problem from a screenshot, check your table of moves, and push you toward the matrix-power follow-up once the linear version works. The mock's transcript then shows whether you explained the graph view before you started counting.

Questions people ask

How do you solve Knight Dialer?

Keep one counter per digit for the numbers of the current length ending there, all 1 at length 1. Each round, every digit adds its count to the digits a knight can jump to. After n - 1 rounds, sum the ten counters modulo 1,000,000,007.

Which keys can a knight reach on the phone keypad?

1 goes to 6 and 8, 2 to 7 and 9, 3 to 4 and 8, 4 to 0, 3 and 9, 6 to 0, 1 and 7, 7 to 2 and 6, 8 to 1 and 3, 9 to 2 and 4, 0 to 4 and 6. Key 5 has no moves.

What is the time complexity of Knight Dialer?

O(n) time and O(1) memory with ten counters. Raising the 10 by 10 jump matrix to the power n - 1 by repeated squaring takes O(log n) matrix products.

Why does Knight Dialer give 10 for n = 1 but 20 for n = 2?

Every digit, including 5, is a valid one-digit number. For two digits you need a jump, and the keypad has 20 (digit, jump) pairs, with 5 contributing none.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP