Given a positive number n and a mobile keypad having digits from 0 to 9 associated with each key, count the total possible combinations of digits having length n. We can start with any digit and press only four adjacent keys of any digit. The keypad also contains * and # keys, which we are not allowed to press.

For example,

Input:  n = 2
 
Output: 36
 
Explanation: Total possible combinations are 36 [00, 08, 11, 12, 14, 21, 22, 23, 25, 32, 33, 36, 41, 44, 45, 47, … ,96, 98, 99]

Mobile Keypad

Practice this problem

We can use recursion to solve this problem since the problem has optimal substructure. The problem can be broken down into smaller, simple “subproblems”, which can further be divided into yet simpler, smaller subproblems until the solution becomes trivial.

The idea is to consider each digit one by one and count all n–digit numbers starting from the current digit. For each digit i, recur for digit i, and all digits reachable from i. To easily find all digits reachable from any digit, use a multimap that stores the mapping of digits reachable from every digit. When the digit becomes n–digit, update the count.

 
The above solution exhibits overlapping subproblems. As shown below, the same subproblems (highlighted in the same color) are getting computed repeatedly.

n–digit number starting from 1 =
 
1 + (n-1) digit number starting from 1
2 + (n-1) digit number starting from 2
4 + (n-1) digit number starting from 4
 
n–digit number starting from 2 =
 
1 + (n-1) digit number starting from 1
2 + (n-1) digit number starting from 2
3 + (n-1) digit number starting from 3
5 + (n-1) digit number starting from 5
 
n–digit number starting from 5 =
 
2 + (n-1) digit number starting from 2
4 + (n-1) digit number starting from 4
5 + (n-1) digit number starting from 5
6 + (n-1) digit number starting from 6
8 + (n-1) digit number starting from 8

We know that problems with optimal substructure and overlapping subproblems can be solved using dynamic programming, where subproblem solutions are memoized rather than computed repeatedly. The top-down memoized approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

Total possible combinations are 36

Java


Download  Run Code

Output:

Total possible combinations are 36

Python


Download  Run Code

Output:

Total possible combinations are 36

The time complexity of the above solution is O(n2) and requires O(n) extra space, where n is the given length of digits.