Valid Keypad Sequences Under Knight Moves
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Consider a 4-row by 3-column phone button layout:
1 2 3
4 5 6
7 8 9
* 0 #
To enter a digit string of length n, choose any numeric key (0 through 9) for the first character, and then perform n - 1 consecutive chess-knight leaps to select the remaining characters:
def knight_dialer(n: int) -> int:
- Each leap shifts
2rows and1column, or1row and2columns, in any direction. - Every character in the string must come from a numeric button (
0–9); leaping outside the 4x3 grid or landing on*or#is forbidden. - When
n = 1, zero leaps occur, so every numeric button0–9(including5) forms a valid single-digit string (10strings in total). - Compute how many distinct length-
ndigit strings can be entered, and return that count modulo10^9 + 7(1_000_000_007).
Examples
Example 1
Input: n = 4
Output: 104
Tracking how many valid strings end on each button 0..9:
- Length 1 (0 leaps): [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] (sum 10).
- Length 2 (1 leap): [2, 2, 2, 2, 3, 0, 3, 2, 2, 2] (sum 20; button 5 has no valid knight destinations).
- Length 3 (2 leaps): [6, 5, 4, 5, 6, 0, 6, 5, 4, 5] (sum 46).
- Length 4 (3 leaps): [12, 10, 10, 10, 16, 0, 16, 10, 10, 10], giving 12 + 10 + 10 + 10 + 16 + 0 + 16 + 10 + 10 + 10 = 104.
Example 2
Input: n = 5
Output: 240
Advancing the length-4 counts by one additional knight leap produces [32, 26, 20, 26, 32, 0, 32, 26, 20, 26], which totals 240.
Example 3
Input: n = 25
Output: 715338219
Across 24 knight leaps there are 3,715,338,240 distinct 25-digit strings; reducing modulo 1,000_000_007 yields 715,338,219.
Constraints
1 <= n <= 5000
Step-by-step walkthrough
Understand the keypad and sequence rules
A dialed sequence of length
nstarts by placing the knight on any numeric key (0through9) and then makingn - 1legal chess knight jumps:- 1 starting press +
n - 1jumps =ndigits. Whenn = 1, you press one digit and make0jumps, so all 10 digits (0through9) are valid 1-digit sequences. - Only digits
0–9are allowed. Every jump moves 2 rows and 1 column, or 1 row and 2 columns, and may never land outside the grid or on*or#. - Return the answer modulo
1_000_000_007(10^9 + 7). For largen(up to5000), the true count has roughly 1,800 decimal digits, so we keep only the remainder when divided by1_000_000_007.
- 1 starting press +
Map every digit's legal knight jumps
Instead of recomputing row and column offsets during the algorithm, inspect the 4x3 keypad once and list where a knight can jump from each digit:
Keypad layout Legal knight jumps from each digit +---+---+---+ | 1 | 2 | 3 | 0 -> 4, 6 5 -> (none) +---+---+---+ 1 -> 6, 8 6 -> 0, 1, 7 | 4 | 5 | 6 | 2 -> 7, 9 7 -> 2, 6 +---+---+---+ 3 -> 4, 8 8 -> 1, 3 | 7 | 8 | 9 | 4 -> 0, 3, 9 9 -> 2, 4 +---+---+---+ | * | 0 | # | +---+---+---+Notice two helpful properties in this table:
- Digit
5is trapped. Every L-shaped jump from the center(row 1, col 1)either leaves the 4x3 board or lands on*or#. So5produces"5"whenn = 1, and contributes nothing at all whenn >= 2. - Knight jumps are reversible. If a knight on
4can jump to0, then a knight on0can jump right back to4. That meansKNIGHT_MOVES[digit]is both the list of digitsdigitcan jump to and the list of digits that can jump intodigit.
from typing import List MOD = 1_000_000_007 # KNIGHT_MOVES[digit] lists every numeric key reachable from `digit` in one # L-shaped chess knight jump. Because knight jumps are reversible (if A can # jump to B, then B can jump to A), this same list also gives every digit # that can jump *into* `digit` on the previous step. # Digit 5 sits in the center: all 8 knight jumps go off-grid or hit * / #. KNIGHT_MOVES: List[List[int]] = [ [4, 6], # 0 <-> 4, 6 [6, 8], # 1 <-> 6, 8 [7, 9], # 2 <-> 7, 9 [4, 8], # 3 <-> 4, 8 [0, 3, 9], # 4 <-> 0, 3, 9 [], # 5 has no legal knight moves [0, 1, 7], # 6 <-> 0, 1, 7 [2, 6], # 7 <-> 2, 6 [1, 3], # 8 <-> 1, 3 [2, 4], # 9 <-> 2, 4 ]- Digit
Why exploring one sequence at a time is too slow
A naive approach starts at each digit and uses recursion to branch out through every possible jump until the sequence reaches length
n. Look at what happens after just two jumps:Start at 1 -> 6 -> 0 -> (still needs n - 3 jumps from 0) Start at 3 -> 4 -> 0 -> (still needs n - 3 jumps from 0) Start at 7 -> 6 -> 0 -> (still needs n - 3 jumps from 0) Start at 9 -> 4 -> 0 -> (still needs n - 3 jumps from 0)All four paths land on
0at length 3. From that moment onward, the knight does not care how it reached0—every future continuation from0is identical. Exploring paths one by one repeats that future work separately for every path, multiplying the work by roughly2.3per step (~2.3^5000operations forn = 5000, which will never finish).Key idea: count how many sequences end on each digit
Instead of listing individual sequences, bundle them by their last digit. Let
counts[d]hold the number of valid sequences of the current length that end on digitd:- At length 1: there is 1 sequence ending on each digit (
"0","1", ...,"9"), socounts = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]. - Extending from length
kto lengthk + 1: to form a sequence ending ondigit, we must take a sequence of lengthkthat ended on someprev_digitcapable of jumping todigit, and appenddigit. Because jumps work in both directions, thoseprev_digitvalues areKNIGHT_MOVES[digit]:
next_counts[digit] = sum of counts[prev_digit] for prev_digit in KNIGHT_MOVES[digit]Why write into a separate
next_countslist instead of updatingcountsin place? Because while computingnext_counts[4]we readcounts[0], and moments later while computingnext_counts[6]we also need the oldcounts[0]from lengthk, not the newly updated lengthk + 1value.- At length 1: there is 1 sequence ending on each digit (
Write the step-by-step transition
We run the extension round
n - 1times, taking% MODon every addition so the numbers stay small. Notice that digit5needs zero special-caseifstatements: whenn = 1, the loop runs0times andcounts[5] = 1is included in the sum (10); whenn >= 2,KNIGHT_MOVES[5]is empty sonext_counts[5]becomes0on the very first round and stays0forever.def knight_dialer(n: int) -> int: # Phase 1: Base case for length 1 (0 jumps). # counts[d] = number of valid sequences of the current length ending at digit d. # For n = 1, starting on any digit 0..9 (including 5) gives 1 valid sequence. counts = [1] * 10 # Phase 2: Extend sequences one knight jump at a time, for n - 1 jumps total. # When n = 1, range(0) is empty so we skip straight to summing `[1] * 10`. for _ in range(n - 1): # Write into a fresh list so every transition in this round reads counts # from the previous sequence length, never mixing two rounds together. next_counts = [0] * 10 for digit in range(10): ways_to_digit = 0 for prev_digit in KNIGHT_MOVES[digit]: # Take modulo on every step so numbers stay below MOD instead of # growing to ~1,800 decimal digits by n = 5000. ways_to_digit = (ways_to_digit + counts[prev_digit]) % MOD next_counts[digit] = ways_to_digit counts = next_counts # Phase 3: Sum sequences of length n across all 10 possible ending digits. total_sequences = 0 for digit_ways in counts: total_sequences = (total_sequences + digit_ways) % MOD return total_sequencesTrace n = 1 through n = 5 by hand
Let's watch the 10-element
countstable evolve across the first four jump rounds:Digit: 0 1 2 3 4 5 6 7 8 9 | Row sum (answer) ----------------------------------------------------+-------------------- Length 1: 1 1 1 1 1 1 1 1 1 1 | 10 Length 2: 2 2 2 2 3 0 3 2 2 2 | 20 Length 3: 6 5 4 5 6 0 6 5 4 5 | 46 Length 4: 12 10 10 10 16 0 16 10 10 10 | 104 (Example 1) Length 5: 32 26 20 26 32 0 32 26 20 26 | 240 (Example 2)Check how Length 4 is computed from the Length 3 row:
- Digit
0(KNIGHT_MOVES[0] = [4, 6]):counts[4] + counts[6] = 6 + 6 = 12. - Digit
1(KNIGHT_MOVES[1] = [6, 8]):counts[6] + counts[8] = 6 + 4 = 10(same for3,7,9). - Digit
2(KNIGHT_MOVES[2] = [7, 9]):counts[7] + counts[9] = 5 + 5 = 10(same for8). - Digit
4(KNIGHT_MOVES[4] = [0, 3, 9]):counts[0] + counts[3] + counts[9] = 6 + 5 + 5 = 16(same for6). - Digit
5(KNIGHT_MOVES[5] = []): sum over empty list =0.
Adding the Length 4 row gives
12 + 10 + 10 + 10 + 16 + 0 + 16 + 10 + 10 + 10 = 104(Example 1), and one more round gives240(Example 2).- Digit
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple MOD = 1_000_000_007 # KNIGHT_MOVES[digit] lists every numeric key reachable from `digit` in one # L-shaped chess knight jump. Because knight jumps are reversible (if A can # jump to B, then B can jump to A), this same list also gives every digit # that can jump *into* `digit` on the previous step. # Digit 5 sits in the center: all 8 knight jumps go off-grid or hit * / #. KNIGHT_MOVES: List[List[int]] = [ [4, 6], # 0 <-> 4, 6 [6, 8], # 1 <-> 6, 8 [7, 9], # 2 <-> 7, 9 [4, 8], # 3 <-> 4, 8 [0, 3, 9], # 4 <-> 0, 3, 9 [], # 5 has no legal knight moves [0, 1, 7], # 6 <-> 0, 1, 7 [2, 6], # 7 <-> 2, 6 [1, 3], # 8 <-> 1, 3 [2, 4], # 9 <-> 2, 4 ] def knight_dialer(n: int) -> int: # Phase 1: Base case for length 1 (0 jumps). # counts[d] = number of valid sequences of the current length ending at digit d. # For n = 1, starting on any digit 0..9 (including 5) gives 1 valid sequence. counts = [1] * 10 # Phase 2: Extend sequences one knight jump at a time, for n - 1 jumps total. # When n = 1, range(0) is empty so we skip straight to summing `[1] * 10`. for _ in range(n - 1): # Write into a fresh list so every transition in this round reads counts # from the previous sequence length, never mixing two rounds together. next_counts = [0] * 10 for digit in range(10): ways_to_digit = 0 for prev_digit in KNIGHT_MOVES[digit]: # Take modulo on every step so numbers stay below MOD instead of # growing to ~1,800 decimal digits by n = 5000. ways_to_digit = (ways_to_digit + counts[prev_digit]) % MOD next_counts[digit] = ways_to_digit counts = next_counts # Phase 3: Sum sequences of length n across all 10 possible ending digits. total_sequences = 0 for digit_ways in counts: total_sequences = (total_sequences + digit_ways) % MOD return total_sequences✅ Submit now — all tests should pass.
Intuition & how it works
Imagine 10 islands numbered 0 through 9 connected by ferry routes, where travelers hop along one ferry route per day. If you want to know how many distinct 5-day trip itineraries end on Island 4, you do not need to read every traveler's full diary—you only need to add up how many travelers were standing on Islands 0, 3, and 9 at the end of Day 4, because those are the only islands with a direct ferry to Island 4. This technique—solving a multi-step counting problem by storing and reusing summary counts from the previous step instead of re-exploring individual histories—is called dynamic programming.
A naive approach tries to build every valid phone number one digit at a time using recursion. Because most digits have 2 or 3 legal knight jumps, the number of sequences multiplies by roughly 2.3 with each extra digit. By n = 5000, there are roughly 2.3^5000 sequences, so enumerating them one by one is completely impossible—and wasteful, because millions of different prefixes ending on the same digit have the exact same legal continuations.
Instead, we store a fixed adjacency list—a per-button table listing which numeric buttons sit one L-shaped jump away—and maintain a 10-slot array counts, where counts[d] tracks how many valid strings of the current length finish on digit d. Let's trace up to Example 1 (n = 4):
- Length 1 (
0jumps): Every single digit"0"through"9"(including"5") is a valid 1-digit string, socounts = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1](sum =10). - Length 2 (
1jump): For each digit, we add upcountsat its neighbors. Digit4connects to0, 3, 9(1 + 1 + 1 = 3), digit0connects to4, 6(1 + 1 = 2), and digit5has no valid jumps (0), yielding[2, 2, 2, 2, 3, 0, 3, 2, 2, 2](sum =20). - Length 3 (
2jumps): Summing neighbors again produces[6, 5, 4, 5, 6, 0, 6, 5, 4, 5](sum =46). - Length 4 (
3jumps, Example 1): Repeating one more time givesnext_counts[0] = 6 + 6 = 12,next_counts[4] = 6 + 5 + 5 = 16, and[12, 10, 10, 10, 16, 0, 16, 10, 10, 10]overall, totaling104.
At every addition we apply modulo arithmetic—keeping only the remainder % 1_000_000_007—which preserves exact remainders under addition while keeping every integer small and fast.
Complexity
- Time: O(n). We run
n - 1transition rounds, and each round loops over the 10 digits and their fixed knight-jump neighbors (20 neighbor lookups in total across the whole table), doing roughly20 * nconstant-time additions. - Space: O(1). Regardless of how large
nis, we only keep the fixed 10-entryKNIGHT_MOVEStable and two 10-element integer lists (countsandnext_counts).
Edge cases
n = 1(single digit, zero jumps): Digit5is valid here because no jump is required, so the outer looprange(0)does not run and the sum of[1] * 10correctly returns10.n >= 2(center key5isolated): BecauseKNIGHT_MOVES[5]is[]and no other digit lists5,counts[5]drops to0on the first jump and never contributes again.- First modulo wraparound at
n = 24: Up ton = 23, the total count fits below1_000_000_007; atn = 24, the true count is1,609,056,256, which wraps around to609,056,249. - Maximum constraint
n = 5000: Performs about100,000small integer additions and finishes in a few milliseconds without recursion stack growth.
Common mistakes
- Missing the jumps through
0(0 <-> 4and0 <-> 6): It is easy to focus on the1–9square and forget that4and6have 3 legal moves (including down to0), while7and9cannot jump to*or#. Always cross-check your move table againstn = 2(20 total moves). - Mutating
countsin place instead of writing tonext_counts: Updatingcounts[0]first and then readingcounts[0]when computingcounts[4]in the same round mixes lengthk + 1counts into lengthkcounts and overcounts. - Hard-coding
5out of the initial array: Startingcounts[5] = 0breaksn = 1(returning9instead of10), whereas adding+ 1at the end for5breaks everyn >= 2. Leavingcounts[5] = 1withKNIGHT_MOVES[5] = []handles both cases naturally. - Using top-down recursion for
n = 5000: Even with memoization—caching(digit, remaining_jumps)results in a dictionary so each state is solved once—recursing 5,000 levels deep exceeds Python's default 1,000-frame call-stack limit and raisesRecursionError. - Applying
% MODonly at the very end: Python supports arbitrary-precision integers so it will not overflow, but numbers reach ~1,800 digits byn = 5000, making arithmetic noticeably slower (and overflowing 64-bit integers in C++, Java, or Go byn = 50).
Alternative approaches
- Top-down recursion with memoization: Define
ways(digit, jumps_left)recursively and cache each(digit, jumps_left)pair. This also runs inO(n)time if you raisesys.setrecursionlimit, but usesO(n)memory for the cache and call stack instead ofO(1). - Symmetry compression (4 states instead of 10): Group equivalent keys by keypad symmetry so each round updates just 4 numbers instead of 10 (still
O(n)time, smaller constant; detailed in the third follow-up). - Matrix exponentiation (
O(log n)time): Represent one transition round as a 10x10 matrix multiplication and raise that matrix to the(n - 1)-th power (detailed in the first follow-up).
Follow-up questions
- How can you compute the count in O(log n) time when n reaches 10^18? Build a 10x10 adjacency matrix
M—a grid whereM[a][b] = 1if a knight can jump fromatoband0otherwise—because multiplying a row of counts byMperforms one jump round, and entryM^(n-1)[a][b]counts all(n - 1)-jump walks fromatob. You can computeM^(n-1)using exponentiation by squaring (repeatedly squaringMto getM^2, M^4, M^8, ...and multiplying together the powers matching the binary bits ofn - 1). Sincelog2(10^18)is about60and multiplying two 10x10 matrices takes10^3 = 1,000operations, evenn = 10^18finishes in roughly120,000operations (O(log n)time andO(1)space).
def mat_mult(a: List[List[int]], b: List[List[int]]) -> List[List[int]]:
size = len(a)
product = [[0] * size for _ in range(size)]
for r in range(size):
for mid in range(size):
if a[r][mid] == 0:
continue
for c in range(size):
product[r][c] = (product[r][c] + a[r][mid] * b[mid][c]) % MOD
return product
def knight_dialer_log(n: int) -> int:
# Start `result` as the 10x10 identity matrix (0 jumps) and `base` as 1 jump.
base = [[0] * 10 for _ in range(10)]
result = [[0] * 10 for _ in range(10)]
for digit in range(10):
result[digit][digit] = 1
for neighbor in KNIGHT_MOVES[digit]:
base[digit][neighbor] = 1
jumps = n - 1
while jumps > 0:
if jumps % 2 == 1:
result = mat_mult(result, base)
base = mat_mult(base, base)
jumps //= 2
return sum(sum(row) for row in result) % MOD
-
What adjustments are needed if a caller also supplies a set of broken digits that cannot be pressed? A broken digit cannot be pressed first and cannot be landed on during any jump. Initialize
counts[d] = 0ifd in brokenelse1, and during each round skip anydigit in brokensonext_counts[digit]stays0. Because every broken digit always holds0, it automatically contributes0when other digits sum overKNIGHT_MOVES, so you do not even need to rebuild the move table (and if every digit0–9is broken, the answer cleanly becomes0even forn = 1). -
How can reflection symmetries of the keypad shrink the state space below ten digits? Flipping the keypad left-to-right (
1 <-> 3,4 <-> 6,7 <-> 9) and flipping the top three rows upside-down (1 <-> 7,2 <-> 8,3 <-> 9) leaves all knight connections unchanged, grouping the active keys into just 4 equivalence classes (sets of keys that always have identical path counts): cornersA = {1, 3, 7, 9}, vertical middlesB = {2, 8}, horizontal middlesC = {4, 6}, andD = {0}(with5only counting atn = 1). Tracking the group sums(a, b, c, d)starting at(4, 2, 2, 1)forn >= 2, each round becomes four tiny assignments:a, b, c, d = (2*b + 2*c) % MOD, a, (a + 2*d) % MOD, c, returning(a + b + c + d) % MOD(or10ifn == 1), which also shrinks theO(log n)matrix from 10x10 down to 4x4.
Follow-up questions
- How can you compute the count in O(log n) time when n reaches 10^18?
- What adjustments are needed if a caller also supplies a set of broken digits that cannot be pressed?
- How can reflection symmetries of the keypad shrink the state space below ten digits?
Similar questions
- Stateful Tic-Tac-Toe Engine and Mobile View
- User Action Sequence Prefix Tree
- Valid Palindrome With One Optional Deletion
- Banned Phrase Chat Filter
- User Activity Prefix Counts
- Efficient Dot Product for Sparse Vectors
More Whatnot interview questions
- User Action Sequence Prefix Tree Hard
- Valid Palindrome With One Optional Deletion Easy
- Stateful Tic-Tac-Toe Engine and Mobile View Medium Pro
- Live-Shopping Trending Stream Discovery Medium Pro
- Efficient Dot Product for Sparse Vectors Medium Pro
- Evaluate and Debug a Live-Shopping Marketplace App Medium Pro
- Month-over-Month Customer Retention Medium Pro
- Calendar-Aware 7-Day Moving Average in SQL Medium Pro
- Banned Phrase Chat Filter Medium Pro
- User Activity Prefix Counts Easy Pro