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 2 rows and 1 column, or 1 row and 2 columns, 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 button 0–9 (including 5) forms a valid single-digit string (10 strings in total).
  • Compute how many distinct length-n digit strings can be entered, and return that count modulo 10^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

  1. Understand the keypad and sequence rules

    A dialed sequence of length n starts by placing the knight on any numeric key (0 through 9) and then making n - 1 legal chess knight jumps:

    • 1 starting press + n - 1 jumps = n digits. When n = 1, you press one digit and make 0 jumps, so all 10 digits (0 through 9) are valid 1-digit sequences.
    • Only digits 0–9 are 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 large n (up to 5000), the true count has roughly 1,800 decimal digits, so we keep only the remainder when divided by 1_000_000_007.
  2. 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:

    1. Digit 5 is trapped. Every L-shaped jump from the center (row 1, col 1) either leaves the 4x3 board or lands on * or #. So 5 produces "5" when n = 1, and contributes nothing at all when n >= 2.
    2. Knight jumps are reversible. If a knight on 4 can jump to 0, then a knight on 0 can jump right back to 4. That means KNIGHT_MOVES[digit] is both the list of digits digit can jump to and the list of digits that can jump into digit.
    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
    ]
    
  3. 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 0 at length 3. From that moment onward, the knight does not care how it reached 0—every future continuation from 0 is identical. Exploring paths one by one repeats that future work separately for every path, multiplying the work by roughly 2.3 per step (~2.3^5000 operations for n = 5000, which will never finish).

  4. 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 digit d:

    • At length 1: there is 1 sequence ending on each digit ("0", "1", ..., "9"), so counts = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1].
    • Extending from length k to length k + 1: to form a sequence ending on digit, we must take a sequence of length k that ended on some prev_digit capable of jumping to digit, and append digit. Because jumps work in both directions, those prev_digit values are KNIGHT_MOVES[digit]:
    next_counts[digit] = sum of counts[prev_digit] for prev_digit in KNIGHT_MOVES[digit]
    

    Why write into a separate next_counts list instead of updating counts in place? Because while computing next_counts[4] we read counts[0], and moments later while computing next_counts[6] we also need the old counts[0] from length k, not the newly updated length k + 1 value.

  5. Write the step-by-step transition

    We run the extension round n - 1 times, taking % MOD on every addition so the numbers stay small. Notice that digit 5 needs zero special-case if statements: when n = 1, the loop runs 0 times and counts[5] = 1 is included in the sum (10); when n >= 2, KNIGHT_MOVES[5] is empty so next_counts[5] becomes 0 on the very first round and stays 0 forever.

    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
    
  6. Trace n = 1 through n = 5 by hand

    Let's watch the 10-element counts table 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 for 3, 7, 9).
    • Digit 2 (KNIGHT_MOVES[2] = [7, 9]): counts[7] + counts[9] = 5 + 5 = 10 (same for 8).
    • Digit 4 (KNIGHT_MOVES[4] = [0, 3, 9]): counts[0] + counts[3] + counts[9] = 6 + 5 + 5 = 16 (same for 6).
    • 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 gives 240 (Example 2).

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

  1. Length 1 (0 jumps): Every single digit "0" through "9" (including "5") is a valid 1-digit string, so counts = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] (sum = 10).
  2. Length 2 (1 jump): For each digit, we add up counts at its neighbors. Digit 4 connects to 0, 3, 9 (1 + 1 + 1 = 3), digit 0 connects to 4, 6 (1 + 1 = 2), and digit 5 has no valid jumps (0), yielding [2, 2, 2, 2, 3, 0, 3, 2, 2, 2] (sum = 20).
  3. Length 3 (2 jumps): Summing neighbors again produces [6, 5, 4, 5, 6, 0, 6, 5, 4, 5] (sum = 46).
  4. Length 4 (3 jumps, Example 1): Repeating one more time gives next_counts[0] = 6 + 6 = 12, next_counts[4] = 6 + 5 + 5 = 16, and [12, 10, 10, 10, 16, 0, 16, 10, 10, 10] overall, totaling 104.

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 - 1 transition 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 roughly 20 * n constant-time additions.
  • Space: O(1). Regardless of how large n is, we only keep the fixed 10-entry KNIGHT_MOVES table and two 10-element integer lists (counts and next_counts).

Edge cases

  • n = 1 (single digit, zero jumps): Digit 5 is valid here because no jump is required, so the outer loop range(0) does not run and the sum of [1] * 10 correctly returns 10.
  • n >= 2 (center key 5 isolated): Because KNIGHT_MOVES[5] is [] and no other digit lists 5, counts[5] drops to 0 on the first jump and never contributes again.
  • First modulo wraparound at n = 24: Up to n = 23, the total count fits below 1_000_000_007; at n = 24, the true count is 1,609,056,256, which wraps around to 609,056,249.
  • Maximum constraint n = 5000: Performs about 100,000 small integer additions and finishes in a few milliseconds without recursion stack growth.

Common mistakes

  • Missing the jumps through 0 (0 <-> 4 and 0 <-> 6): It is easy to focus on the 1–9 square and forget that 4 and 6 have 3 legal moves (including down to 0), while 7 and 9 cannot jump to * or #. Always cross-check your move table against n = 2 (20 total moves).
  • Mutating counts in place instead of writing to next_counts: Updating counts[0] first and then reading counts[0] when computing counts[4] in the same round mixes length k + 1 counts into length k counts and overcounts.
  • Hard-coding 5 out of the initial array: Starting counts[5] = 0 breaks n = 1 (returning 9 instead of 10), whereas adding + 1 at the end for 5 breaks every n >= 2. Leaving counts[5] = 1 with KNIGHT_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 raises RecursionError.
  • Applying % MOD only at the very end: Python supports arbitrary-precision integers so it will not overflow, but numbers reach ~1,800 digits by n = 5000, making arithmetic noticeably slower (and overflowing 64-bit integers in C++, Java, or Go by n = 50).

Alternative approaches

  • Top-down recursion with memoization: Define ways(digit, jumps_left) recursively and cache each (digit, jumps_left) pair. This also runs in O(n) time if you raise sys.setrecursionlimit, but uses O(n) memory for the cache and call stack instead of O(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 where M[a][b] = 1 if a knight can jump from a to b and 0 otherwise—because multiplying a row of counts by M performs one jump round, and entry M^(n-1)[a][b] counts all (n - 1)-jump walks from a to b. You can compute M^(n-1) using exponentiation by squaring (repeatedly squaring M to get M^2, M^4, M^8, ... and multiplying together the powers matching the binary bits of n - 1). Since log2(10^18) is about 60 and multiplying two 10x10 matrices takes 10^3 = 1,000 operations, even n = 10^18 finishes in roughly 120,000 operations (O(log n) time and O(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] = 0 if d in broken else 1, and during each round skip any digit in broken so next_counts[digit] stays 0. Because every broken digit always holds 0, it automatically contributes 0 when other digits sum over KNIGHT_MOVES, so you do not even need to rebuild the move table (and if every digit 0–9 is broken, the answer cleanly becomes 0 even for n = 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): corners A = {1, 3, 7, 9}, vertical middles B = {2, 8}, horizontal middles C = {4, 6}, and D = {0} (with 5 only counting at n = 1). Tracking the group sums (a, b, c, d) starting at (4, 2, 2, 1) for n >= 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 (or 10 if n == 1), which also shrinks the O(log n) matrix from 10x10 down to 4x4.

Follow-up questions

Similar questions

More Whatnot interview questions

All 21 Whatnot questions →