Skip to problem
←

Mobile Numeric Keypad

Medium 0 attempts

Count the distinct digit sequences of length n that can be typed on this keypad:

text
1 2 3
4 5 6
7 8 9
  0

The first press may be any digit, including 0. For each subsequent press, stay on the same key or move one key up, down, left, or right. Diagonal moves, wrapping, and the two blank positions beside 0 are not allowed.

Leading zeros count, so "00" and "08" are valid two-press sequences. From 0, the next key can only be 0 or 8. From 5, it can be 2, 4, 5, 6, or 8. Return the exact count, not the sequences themselves.

Function contract

Implement getCount(n). Receive the exact number of key presses in each digit sequence.

Output: Return the exact number of valid length-n digit sequences as a JavaScript number. Leading zeros count; no modulus is applied.

Example 1

Input
n = 1
Output
10

Example 2

Input
n = 2
Output
36

Example 3

Input
n = 3
Output
138
Constraints
  • 1 <= n <= 25

DP with Adjacency Map

Let dp[d] count sequences of the current length ending at digit d. Initially every digit has one length-1 sequence. To add a press ending at d, sum counts from d itself and its valid neighboring keys. Build a fresh array for each length so transitions all use the previous length. The adjacency map includes staying on the same key.

At n = 25 the total is 1217034591721250, below Number.MAX_SAFE_INTEGER, so all additions remain exact under the published bounds.

javascript
function getCount(n) {
  const adj = {0:[0,8],1:[1,2,4],2:[2,1,3,5],3:[3,2,6],4:[4,1,5,7],5:[5,2,4,6,8],6:[6,3,5,9],7:[7,4,8],8:[8,5,7,9,0],9:[9,6,8]};
  let dp = Array(10).fill(1);
  for (let i = 2; i <= n; i++) {
    const next = Array(10).fill(0);
    for (let d = 0; d <= 9; d++) for (const prev of adj[d]) next[d] += dp[prev];
    dp = next;
  }
  return dp.reduce((a,b) => a+b, 0);
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript