Generate 10-digit number using a phone keypad
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
The "generate 10-digit numbers using a phone keypad" problem is a classic algorithm challenge: given a standard phone keypad and a starting digit, count or enumerate all 10-digit numbers where each successive digit is a valid knight's move (like chess) from the previous digit on the keypad. This is a dynamic programming problem that tests understanding of state transitions, memoization, and graph traversal.
Phone Keypad Layout
Knight's Move Adjacency
From each digit, a knight (chess piece) can move to specific other digits:
Note: digit 5 has no valid knight moves (all destinations would fall off the keypad).
Solution 1: Recursive with Memoization
Solution 2: Dynamic Programming (Bottom-Up)
Time complexity: O(N * 10) where N is the number of digits. Space complexity: O(10) = O(1).
Solution 3: Matrix Exponentiation
For very large N, use matrix exponentiation for O(log N) time:
Solution 4: Enumerate All Numbers
To generate the actual numbers (feasible for small N):
Variations
Starting from a Specific Digit
Excluding Digit 0 and 5 (No Corner Pieces)
Adjacent Moves (Not Knight)
A different variant uses adjacent digit moves instead of knight moves:
Common Pitfalls
- Forgetting digit 5 has no moves: In the knight variant, 5 cannot reach any other digit. Sequences that reach 5 terminate early, contributing 0 to the count.
- Off-by-one in digit count: A 10-digit number has 9 transitions (moves), not 10. The DP loop runs
n_digits - 1times. - Integer overflow: For large N, counts grow exponentially. Use Python's arbitrary precision integers or modular arithmetic (
% 10**9 + 7) in other languages. - Confusing knight vs adjacent moves: The classic problem uses knight moves (L-shaped, like chess), not simple adjacency. Verify which variant the problem asks for.
- Starting digit 0: Some problem variants exclude 0 as a starting digit (phone numbers don't start with 0). Clarify the constraints.
Summary
- The phone keypad knight problem counts N-digit numbers where each digit is a knight's move from the previous
- Dynamic programming solves it in O(N) time with O(1) space using a 10-element array
- Matrix exponentiation solves it in O(log N) for very large N
- Digit 5 is a dead end (no valid knight moves)
- Total 10-digit numbers: 1,424 (starting from any digit)
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseInterview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.