Knight Dialer (LeetCode 935): Solution and Explanation

Medium
Dynamic Programming

A chess knight hops around a phone keypad, landing only on digit keys. Count how many distinct phone numbers of length n it can dial by starting on any key and making n - 1 jumps, modulo 10^9 + 7.

Intuition

Brute force would try every starting key and every jump sequence, which grows roughly like 2^n. But the future of a partly dialed number depends only on the key the knight is standing on now, not on how it got there.

That suggests counting by last key: dp[d] is the number of valid numbers of the current length that end on d. For length 1 every key has exactly one number, itself.

To add a digit, every number ending on d can be extended by each knight jump out of d. So the count for a key nb in the next row is the sum of dp[d] over all keys d that can jump to nb.

The keypad is fixed and tiny: ten keys and twenty jumps in total, and key 5 has none. Each hop is a constant amount of work, so n - 1 hops cost O(n).

Approach: Hop-by-hop DP over the ten keys

  1. Write the jump table: 0 -> 4, 6; 1 -> 6, 8; 2 -> 7, 9; 3 -> 4, 8; 4 -> 0, 3, 9; 5 -> none; 6 -> 0, 1, 7; 7 -> 2, 6; 8 -> 1, 3; 9 -> 2, 4.
  2. Set dp = [1] * 10, the counts for 1-digit numbers.
  3. Repeat n - 1 times: create nxt with ten zeros, and for every key d and every jump d -> nb, add dp[d] to nxt[nb] modulo 10^9 + 7.
  4. Replace dp with nxt after each hop.
  5. Return the sum of the ten counts modulo 10^9 + 7.

Step-by-step example

n = 1
  1. dp = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]: every key is a 1-digit number by itself.
  2. n - 1 = 0, so no hops are made.
  3. The sum of the ten counts is 10, so the answer is 10.
  4. For n = 2 the same table gives one more hop: each key's count becomes its number of incoming jumps, for example key 4 receives from 3, 9 and 0, and the total is 20.

Code: Python, Java, C++

1class Solution:
2    def knightDialer(self, n: int) -> int:
3        MOD = 10**9 + 7
4        moves = [[4, 6], [6, 8], [7, 9], [4, 8], [0, 3, 9], [], [0, 1, 7], [2, 6], [1, 3], [2, 4]]
5        dp = [1] * 10
6        for _ in range(n - 1):
7            nxt = [0] * 10
8            for d in range(10):
9                for nb in moves[d]:
10                    nxt[nb] = (nxt[nb] + dp[d]) % MOD
11            dp = nxt
12        return sum(dp) % MOD
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Matrix exponentiation O(log n)
Hop-by-hop DP over the ten keys O(n)
Memoized recursion O(n)
Symmetry groups O(n)
Time

O(n)

Each of the n - 1 hops walks the 20 knight jumps once, which is constant work per hop.

Space

O(1)

Only two arrays of ten counts are kept, no matter how large n is.

Other approaches

Memoized recursion (time O(n), space O(n))

Define count(key, remaining) as the numbers that can still be dialed from key with remaining digits left, and memoize it. It gives the same answer but stores a 10 x n table and can hit recursion limits for n = 5000.

Matrix exponentiation (time O(log n), space O(1))

The hop is a fixed 10 x 10 adjacency matrix, so raising it to the power n - 1 by repeated squaring gives the counts in logarithmic time. It is overkill for n up to 5000 but useful for huge n.

Symmetry groups (time O(n), space O(1))

By the keypad's symmetry, keys fall into a few classes ({1,3,7,9}, {2,8}, {4,6}, {0}, {5}) that always share counts, so the DP can run on four or five numbers instead of ten.

Common mistakes

  • Returning 0 instead of 10 for n = 1. A single key, including 5, is a valid number.
  • Writing the update into dp in place. A key's new count must use only the previous row, so build a fresh nxt array.
  • Forgetting the modulo inside the loop. The counts grow exponentially and overflow 32-bit integers within a few dozen hops.
  • Getting the jump table wrong, especially giving key 5 neighbors or forgetting that 4 and 6 can reach 0.

Frequently asked questions

Why does key 5 never gain any count after the first digit?

No knight jump from any key lands on 5, and none leaves it either. So 5 contributes 1 for n = 1 and 0 for every longer length.

Why is it enough to remember only the last key?

Which digits can come next depends only on where the knight stands. Two numbers ending on the same key have exactly the same set of continuations, so their counts can be merged.

Can this be faster than O(n)?

Yes. The transition is a fixed 10 x 10 matrix, so matrix exponentiation computes the answer in O(log n) multiplications. For n up to 5000 the simple loop is already fast.

Is the jump relation symmetric?

Yes. If the knight can jump from a to b, it can jump back from b to a, so the jump table is an undirected graph with 10 nodes and 10 edges.