Problem 935

Abstract / Summary

A knight moves on a phone keypad and we count the number of unique sequences after a set number of moves.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0935.py

class Solution:
    def knightDialer(self, n: int) -> int:
        # based on https://oeis.org/A327692
        # jump[i] => numbers reachable from i
        jump = [ (4, 6), (6, 8), (7, 9), (4, 8), (3, 9, 0), (), (1, 7, 0), (2, 6), (1, 3), (2, 4) ]
        todo = [1] * 10 # start from each field
        for _ in range(1, n):
            next = [ 0 ] * 10
            for source in range(10):
                for target in jump[source]:
                    next[target] += todo[source]
            todo = next
        return sum(todo) % 1_000_000_007
13 lines | 565 bytes | submitted November 27, 2023 | GitHub   27% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 62% (300k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The Solution class implements a dynamic-programming routine that counts the number of distinct sequences of length n that a chess knight can trace on a standard telephone keypad. Each sequence is formed by moving the knight according to its L-shaped jumps, starting from any of the ten keys (including the central “0”). The final count is returned modulo 1 000 000 007, which keeps the result within a 32-bit integer range.

Core Logic

The algorithm relies on a pre-computed adjacency list named jump. This tuple-of-tuples maps each digit to the set of digits reachable in a single knight move. For example, the entry for digit 0 is empty because a knight cannot land on 0 from any other key in a single move, while the entry for digit 1 contains (6, 8), reflecting the two legal jumps from 1.

jump = [
    (4, 6),        # 0
    (6, 8),        # 1
    (7, 9),        # 2
    (4, 8),        # 3
    (3, 9, 0),     # 4
    (),            # 5 (isolated)
    (1, 7, 0),     # 6
    (2, 6),        # 7
    (1, 3),        # 8
    (2, 4)         # 9
]

A one-dimensional array todo holds the number of ways to reach each digit after a given number of moves. It is initialized with 1 for every digit, representing the trivial sequences of length 1 that start and end on the same key.

todo = [1] * 10

The main loop iterates n-1 times, because the initial state already accounts for the first digit. In each iteration a fresh array next is built by distributing the current counts to all reachable targets. The inner double loop walks through every source digit and, for each, adds its current count to each of its legal destinations.

for _ in range(1, n):
    next = [0] * 10
    for source in range(10):
        for target in jump[source]:
            next[target] += todo[source]
    todo = next

After the loop finishes, todo contains the counts for sequences of exact length n. Summing the ten entries yields the total number of possible knight dialer sequences, and the modulo operation ensures the result conforms to the required range.

return sum(todo) % 1_000_000_007

Edge Cases Handled

When n equals 1, the outer loop body is never executed because the range range(1, n) is empty. In this situation the method directly returns the sum of the initial todo array, which is 10, correctly reflecting the ten one-digit sequences.

The adjacency list includes an empty tuple for digit 5, indicating that no knight move can originate from or land on 5. Consequently, any sequence that would require stepping on 5 contributes zero to the final total, and the algorithm naturally discards such paths without additional checks.

The entry for digit 0 contains only (4, 6), matching the knight’s legal moves from 0. Because the list for 0 is not empty, sequences that start on 0 can continue, and the algorithm correctly propagates counts from 0 to its reachable neighbors.

If n is a large integer, the modulo operation applied only at the final return prevents intermediate overflow while still delivering the correct modular result, thanks to Python’s arbitrary-precision integers.

Performance Optimizations

The implementation uses a fixed-size list of length 10 for both the state vector (todo) and the temporary accumulator (next). This constant-size structure eliminates the overhead of dynamic data structures and enables fast index-based updates.

By pre-computing the jump adjacency list, the algorithm avoids recomputing legal moves during each iteration. The inner loop iterates only over the actual reachable targets for a given source, which reduces the number of additions compared to a naïve full-matrix multiplication.

The modulo reduction is deferred until the final result, which avoids repeated modulus operations inside the nested loops. Since Python integers can grow arbitrarily large, this choice trades a modest increase in intermediate integer size for fewer costly modulus calculations, yielding a net speed gain for typical input sizes.

The use of plain integer addition without any auxiliary data structures keeps the memory footprint minimal and the CPU cache utilization high, as the entire working set fits comfortably within a single cache line.

Overall, the algorithm achieves a tight loop that processes a constant amount of work per iteration, making it well-suited for large values of n while staying within the constraints of the problem.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a magical telephone with numbers zero through nine arranged in a circle. A special knight piece from a chess game starts on one of these numbers. The knight jumps around the phone keypad just like it moves on a chessboard, which means it makes an L-shape hop to land on new numbers.

The list labeled jump acts like a map showing exactly where the knight can move from each number. For example, if the knight is standing on the number zero, the map says it can jump over to four or six. The list called todo keeps track of how many ways the knight could have reached each number. At the very beginning, there is just one way to be on each number because no jumps have happened yet.

Every time the code repeats the steps inside the loop, it calculates all the new possible landing spots for the knight. It looks at every number the knight could be standing on, finds the allowed jumps from the map, and adds up the paths to those new spots. This happens over and over again until the knight has finished all of its jumps. By the end, the code adds together all the different ways the knight could have finished its journey on the keypad.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.65 | σ = 0.92

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python C# Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
fengvyi C++
fsq C++
gouthampradhan Java
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
MacJim C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
fengvyi C++
fsq C++
gouthampradhan Java
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
MacJim C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak C++
33 links | 19 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   November 27, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality