Mobile Numeric Keypad Problem
Pattern: 2D grid DP
On a phone keypad, count n-digit sequences where each next digit is the same key or a key directly up, down, left or right of it. Count sequences ending at each digit, length by length.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
The keypad is 1 2 3 / 4 5 6 / 7 8 9 / * 0 #, and * and # may not be pressed. Return how many sequences of n digits exist
in which each digit is the same as, or directly above, below, left or right of, the one before. n = 1 gives 10;
n = 2 gives 36. The catalogue has no practice link for this one.
Think first
- Which keys can follow 5? And 0?
- What does each length need from the previous one?
- How many states?
Hints
Brute force, and why it fails
Generate every sequence: up to 5ⁿ.
The key insight
Counts per ending digit are all that matter, so each length is ten sums.
Dry run
| total | 10 |
|---|
n = 1: every digit alone, 10 sequences.
The plan
count = [1] * 10
repeat n - 1 times: count[d] = sum of count[p] for p that may precede d
Complexity
- Time
O(n)- Space
O(1)
Ten digits per step.
Edge cases
- n = 1: 10.
- Large n: 64-bit.
- n = 0: by this guide's count, 10 is not defined; tests start at 1.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public long getCount(int n) {
int[][] next = {{0, 8}, {1, 2, 4}, {2, 1, 3, 5}, {3, 2, 6}, {4, 1, 5, 7}, {5, 2, 4, 6, 8},
{6, 3, 5, 9}, {7, 4, 8}, {8, 5, 7, 9, 0}, {9, 6, 8}}; // a digit, then itself or a key next to it
long[] count = new long[10];
Arrays.fill(count, 1); // sequences of length 1 ending at each digit
for (int len = 2; len <= n; len++) {
long[] nc = new long[10];
for (int d = 0; d <= 9; d++) for (int p : next[d]) nc[d] += count[p]; // came from p, now pressed d
count = nc;
}
long total = 0;
for (long c : count) total += c;
return total;
}
}C++
class Solution {
public:
long long getCount(int n) {
vector<vector<int>> next = {{0, 8}, {1, 2, 4}, {2, 1, 3, 5}, {3, 2, 6}, {4, 1, 5, 7}, {5, 2, 4, 6, 8},
{6, 3, 5, 9}, {7, 4, 8}, {8, 5, 7, 9, 0}, {9, 6, 8}}; // itself or a key next to it
vector<long long> count(10, 1); // sequences of length 1 ending at each digit
for (int len = 2; len <= n; len++) {
vector<long long> nc(10, 0);
for (int d = 0; d <= 9; d++) for (int p : next[d]) nc[d] += count[p]; // came from p, now pressed d
count = nc;
}
long long total = 0;
for (long long c : count) total += c;
return total;
}
};Python
class Solution:
def getCount(self, n: int) -> int:
nxt = [[0, 8], [1, 2, 4], [2, 1, 3, 5], [3, 2, 6], [4, 1, 5, 7], [5, 2, 4, 6, 8],
[6, 3, 5, 9], [7, 4, 8], [8, 5, 7, 9, 0], [9, 6, 8]] # a digit, then itself or a key next to it
count = [1] * 10 # sequences of length 1 ending at each digit
for _ in range(n - 1):
count = [sum(count[p] for p in nxt[d]) for d in range(10)] # came from p, now pressed d
return sum(count)Common mistakes
- Allowing * and #.
- Forgetting a key may repeat.