• Difficulty Level : Hard
• Last Updated : 01 Sep, 2022

Given the mobile numeric keypad. You can only press buttons that are up, left, right or down to the current button. You are not allowed to press bottom row corner buttons (i.e. * and # ).

Given a number N, find out the number of possible numbers of given length.

Examples:

For N=1, number of possible numbers would be 10 (0, 1, 2, 3, â€¦., 9)
For N=2, number of possible numbers would be 36
Possible numbers: 00,08 11,12,14 22,21,23,25 and so on.
If we start with 0, valid numbers will be 00, 08 (count: 2)
If we start with 1, valid numbers will be 11, 12, 14 (count: 3)
If we start with 2, valid numbers will be 22, 21, 23,25 (count: 4)
If we start with 3, valid numbers will be 33, 32, 36 (count: 3)
If we start with 4, valid numbers will be 44,41,45,47 (count: 4)
If we start with 5, valid numbers will be 55,54,52,56,58 (count: 5)
....................................
....................................
We need to print the count of possible numbers.
Recommended Practice

N = 1 is trivial case, number of possible numbers would be 10 (0, 1, 2, 3, â€¦., 9)
For N > 1, we need to start from some button, then move to any of the four direction (up, left, right or down) which takes to a valid button (should not go to *, #). Keep doing this until N length number is obtained (depth first traversal).

Recursive Solution:

Mobile Keypad is a rectangular grid of 4X3 (4 rows and 3 columns)
Lets say Count(i, j, N) represents the count of N length numbers starting from position (i, j)

If N = 1
Count(i, j, N) = 10
Else
Count(i, j, N) = Sum of all Count(r, c, N-1) where (r, c) is new
position after valid move of length 1 from current
position (i, j)

Following is the implementation of above recursive formula.

## Javascript



Output

Count for numbers of length 1: 10n
Count for numbers of length 2: 36n
Count for numbers of length 3: 138n
Count for numbers of length 4: 532n
Count for numbers of length 5: 2062n

Dynamic Programming

There are many repeated traversal on smaller paths (traversal for smaller N) to find all possible longer paths (traversal for bigger N). See following two diagrams for example. In this traversal, for N = 4 from two starting positions (buttons ‘4’ and ‘8’), we can see there are few repeated traversals for N = 2 (e.g. 4 -> 1, 6 -> 3, 8 -> 9, 8 -> 7 etc).

Since the problem has both properties: Optimal Substructure and Overlapping Subproblems, it can be efficiently solved using dynamic programming.

Following is the program for dynamic programming implementation.

## Javascript



Output

Count for numbers of length 1: 10n
Count for numbers of length 2: 36n
Count for numbers of length 3: 138n
Count for numbers of length 4: 532n
Count for numbers of length 5: 2062n

A Space Optimized Solution:

The above dynamic programming approach also runs in O(n) time and requires O(n) auxiliary space, as only one for loop runs n times, other for loops runs for constant time. We can see that nth iteration needs data from (n-1)th iteration only, so we need not keep the data from older iterations. We can have a space efficient dynamic programming approach with just two arrays of size 10. Thanks to Nik for suggesting this solution.

## C++

 // A Space Optimized C++ program to count number of possible numbers // of given length #include using namespace std;   // Return count of all possible numbers of length n // in a given numeric keyboard int getCount(char keypad[][3], int n) {     if (keypad == NULL || n <= 0)         return 0;     if (n == 1)         return 10;       // odd[i], even[i] arrays represent count of numbers starting     // with digit i for any length j     int odd[10], even[10];     int i = 0, j = 0, useOdd = 0, totalCount = 0;       for (i = 0; i <= 9; i++)         odd[i] = 1; // for j = 1       for (j = 2; j <= n; j++) // Bottom Up calculation from j = 2 to n     {         useOdd = 1 - useOdd;           // Here we are explicitly writing lines for each number 0         // to 9. But it can always be written as DFS on 4X3 grid         // using row, column array valid moves         if (useOdd == 1)         {             even[0] = odd[0] + odd[8];             even[1] = odd[1] + odd[2] + odd[4];             even[2] = odd[2] + odd[1] + odd[3] + odd[5];             even[3] = odd[3] + odd[2] + odd[6];             even[4] = odd[4] + odd[1] + odd[5] + odd[7];             even[5] = odd[5] + odd[2] + odd[4] + odd[8] + odd[6];             even[6] = odd[6] + odd[3] + odd[5] + odd[9];             even[7] = odd[7] + odd[4] + odd[8];             even[8] = odd[8] + odd[0] + odd[5] + odd[7] + odd[9];             even[9] = odd[9] + odd[6] + odd[8];         }         else         {             odd[0] = even[0] + even[8];             odd[1] = even[1] + even[2] + even[4];             odd[2] = even[2] + even[1] + even[3] + even[5];             odd[3] = even[3] + even[2] + even[6];             odd[4] = even[4] + even[1] + even[5] + even[7];             odd[5] = even[5] + even[2] + even[4] + even[8] + even[6];             odd[6] = even[6] + even[3] + even[5] + even[9];             odd[7] = even[7] + even[4] + even[8];             odd[8] = even[8] + even[0] + even[5] + even[7] + even[9];             odd[9] = even[9] + even[6] + even[8];         }     }       // Get count of all possible numbers of length "n" starting     // with digit 0, 1, 2, ..., 9     totalCount = 0;     if (useOdd == 1)     {         for (i = 0; i <= 9; i++)             totalCount += even[i];     }     else     {         for (i = 0; i <= 9; i++)             totalCount += odd[i];     }     return totalCount; }   // Driver program to test above function int main() {     char keypad[4][3] = {{'1', '2', '3'},                          {'4', '5', '6'},                          {'7', '8', '9'},                          {'*', '0', '#'}};     cout << "Count for numbers of length 1: " << getCount(keypad, 1) << endl;     cout << "Count for numbers of length 2: " << getCount(keypad, 2) << endl;     cout << "Count for numbers of length 3: " << getCount(keypad, 3) << endl;     cout << "Count for numbers of length 4: " << getCount(keypad, 4) << endl;     cout << "Count for numbers of length 5: " << getCount(keypad, 5) << endl;       return 0; }   //This code is contributed by Mayank Tyagi

## C

 // A Space Optimized C program to count number of possible numbers // of given length #include   // Return count of all possible numbers of length n // in a given numeric keyboard int getCount(char keypad[][3], int n) {     if(keypad == NULL || n <= 0)         return 0;     if(n == 1)         return 10;       // odd[i], even[i] arrays represent count of numbers starting     // with digit i for any length j     int odd[10], even[10];     int i = 0, j = 0, useOdd = 0, totalCount = 0;       for (i=0; i<=9; i++)         odd[i] = 1;  // for j = 1       for (j=2; j<=n; j++) // Bottom Up calculation from j = 2 to n     {         useOdd = 1 - useOdd;           // Here we are explicitly writing lines for each number 0         // to 9. But it can always be written as DFS on 4X3 grid         // using row, column array valid moves         if(useOdd == 1)         {             even[0] = odd[0] + odd[8];             even[1] = odd[1] + odd[2] + odd[4];             even[2] = odd[2] + odd[1] + odd[3] + odd[5];             even[3] = odd[3] + odd[2] + odd[6];             even[4] = odd[4] + odd[1] + odd[5] + odd[7];             even[5] = odd[5] + odd[2] + odd[4] + odd[8] + odd[6];             even[6] = odd[6] + odd[3] + odd[5] + odd[9];             even[7] = odd[7] + odd[4] + odd[8];             even[8] = odd[8] + odd[0] + odd[5] + odd[7] + odd[9];             even[9] = odd[9] + odd[6] + odd[8];         }         else         {             odd[0] = even[0] + even[8];             odd[1] = even[1] + even[2] + even[4];             odd[2] = even[2] + even[1] + even[3] + even[5];             odd[3] = even[3] + even[2] + even[6];             odd[4] = even[4] + even[1] + even[5] + even[7];             odd[5] = even[5] + even[2] + even[4] + even[8] + even[6];             odd[6] = even[6] + even[3] + even[5] + even[9];             odd[7] = even[7] + even[4] + even[8];             odd[8] = even[8] + even[0] + even[5] + even[7] + even[9];             odd[9] = even[9] + even[6] + even[8];         }     }       // Get count of all possible numbers of length "n" starting     // with digit 0, 1, 2, ..., 9     totalCount = 0;     if(useOdd == 1)     {         for (i=0; i<=9; i++)             totalCount += even[i];     }     else     {         for (i=0; i<=9; i++)             totalCount += odd[i];     }     return totalCount; }   // Driver program to test above function int main() {     char keypad[4][3] = {{'1','2','3'},         {'4','5','6'},         {'7','8','9'},         {'*','0','#'}     };     printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));     printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2));     printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3));     printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4));     printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5));       return 0; }

## Java

 // A Space Optimized Java program to // count number of possible numbers // of given length class GFG {   // Return count of all possible numbers of // length n in a given numeric keyboard static int getCount(char keypad[][], int n) {     if(keypad == null || n <= 0)         return 0;     if(n == 1)         return 10;       // odd[i], even[i] arrays represent count of     // numbers starting with digit i for any length j     int []odd = new int[10];     int []even = new int[10];     int i = 0, j = 0, useOdd = 0, totalCount = 0;       for (i = 0; i <= 9; i++)         odd[i] = 1; // for j = 1           // Bottom Up calculation from j = 2 to n     for (j = 2; j <= n; j++)     {         useOdd = 1 - useOdd;           // Here we are explicitly writing lines         // for each number 0 to 9. But it can always be         // written as DFS on 4X3 grid using row,         // column array valid moves         if(useOdd == 1)         {             even[0] = odd[0] + odd[8];             even[1] = odd[1] + odd[2] + odd[4];             even[2] = odd[2] + odd[1] +                       odd[3] + odd[5];             even[3] = odd[3] + odd[2] + odd[6];             even[4] = odd[4] + odd[1] +                       odd[5] + odd[7];             even[5] = odd[5] + odd[2] + odd[4] +                                odd[8] + odd[6];             even[6] = odd[6] + odd[3] +                       odd[5] + odd[9];             even[7] = odd[7] + odd[4] + odd[8];             even[8] = odd[8] + odd[0] + odd[5] +                                odd[7] + odd[9];             even[9] = odd[9] + odd[6] + odd[8];         }         else         {             odd[0] = even[0] + even[8];             odd[1] = even[1] + even[2] + even[4];             odd[2] = even[2] + even[1] +                      even[3] + even[5];             odd[3] = even[3] + even[2] + even[6];             odd[4] = even[4] + even[1] +                      even[5] + even[7];             odd[5] = even[5] + even[2] + even[4] +                                even[8] + even[6];             odd[6] = even[6] + even[3] +                      even[5] + even[9];             odd[7] = even[7] + even[4] + even[8];             odd[8] = even[8] + even[0] + even[5] +                                even[7] + even[9];             odd[9] = even[9] + even[6] + even[8];         }     }       // Get count of all possible numbers of     // length "n" starting with digit 0, 1, 2, ..., 9     totalCount = 0;     if(useOdd == 1)     {         for (i = 0; i <= 9; i++)             totalCount += even[i];     }     else     {         for (i = 0; i <= 9; i++)             totalCount += odd[i];     }     return totalCount; }   // Driver Code public static void main(String[] args) {     char keypad[][] = {{'1','2','3'},                        {'4','5','6'},                        {'7','8','9'},                        {'*','0','#'}};     System.out.printf("Count for numbers of length %d: %d\n", 1,                                            getCount(keypad, 1));     System.out.printf("Count for numbers of length %d: %d\n", 2,                                            getCount(keypad, 2));     System.out.printf("Count for numbers of length %d: %d\n", 3,                                            getCount(keypad, 3));     System.out.printf("Count for numbers of length %d: %d\n", 4,                                            getCount(keypad, 4));     System.out.printf("Count for numbers of length %d: %d\n", 5,                                            getCount(keypad, 5)); } }   // This code is contributed by PrinciRaj1992

## Python3

 # A Space Optimized Python program to count # number of possible numbers # of given length   # Return count of all possible numbers # of length n # in a given numeric keyboard def getCount(keypad, n):       if(not keypad or n <= 0):         return 0     if(n == 1):         return 10       # odd[i], even[i] arrays represent     # count of numbers starting     # with digit i for any length j     odd = [0]*10     even = [0]*10     i = 0     j = 0     useOdd = 0     totalCount = 0       for i in range(10):         odd[i] = 1 # for j = 1       for j in range(2,n+1): # Bottom Up calculation from j = 2 to n               useOdd = 1 - useOdd           # Here we are explicitly writing lines for each number 0         # to 9. But it can always be written as DFS on 4X3 grid         # using row, column array valid moves         if(useOdd == 1):                       even[0] = odd[0] + odd[8]             even[1] = odd[1] + odd[2] + odd[4]             even[2] = odd[2] + odd[1] + odd[3] + odd[5]             even[3] = odd[3] + odd[2] + odd[6]             even[4] = odd[4] + odd[1] + odd[5] + odd[7]             even[5] = odd[5] + odd[2] + odd[4] + odd[8] + odd[6]             even[6] = odd[6] + odd[3] + odd[5] + odd[9]             even[7] = odd[7] + odd[4] + odd[8]             even[8] = odd[8] + odd[0] + odd[5] + odd[7] + odd[9]             even[9] = odd[9] + odd[6] + odd[8]                   else:                       odd[0] = even[0] + even[8]             odd[1] = even[1] + even[2] + even[4]             odd[2] = even[2] + even[1] + even[3] + even[5]             odd[3] = even[3] + even[2] + even[6]             odd[4] = even[4] + even[1] + even[5] + even[7]             odd[5] = even[5] + even[2] + even[4] + even[8] + even[6]             odd[6] = even[6] + even[3] + even[5] + even[9]             odd[7] = even[7] + even[4] + even[8]             odd[8] = even[8] + even[0] + even[5] + even[7] + even[9]             odd[9] = even[9] + even[6] + even[8]       # Get count of all possible numbers of length "n" starting     # with digit 0, 1, 2, ..., 9     totalCount = 0     if(useOdd == 1):         for i in range(10):             totalCount += even[i]           else:         for i in range(10):             totalCount += odd[i]       return totalCount   # Driver program to test above function if __name__ == "__main__":     keypad = [['1','2','3'],             ['4','5','6'],             ['7','8','9'],             ['*','0','#']]           print("Count for numbers of length ",1,": ", getCount(keypad, 1))     print("Count for numbers of length ",2,": ", getCount(keypad, 2))     print("Count for numbers of length ",3,": ", getCount(keypad, 3))     print("Count for numbers of length ",4,": ", getCount(keypad, 4))     print("Count for numbers of length ",5,": ", getCount(keypad, 5))       # This code is contributed by # ChitraNayal

## C#

 // A Space Optimized C# program to // count number of possible numbers // of given length using System;       class GFG {   // Return count of all possible numbers of // length n in a given numeric keyboard static int getCount(char [,]keypad, int n) {     if(keypad == null || n <= 0)         return 0;     if(n == 1)         return 10;       // odd[i], even[i] arrays represent count of     // numbers starting with digit i for any length j     int []odd = new int[10];     int []even = new int[10];     int i = 0, j = 0, useOdd = 0, totalCount = 0;       for (i = 0; i <= 9; i++)         odd[i] = 1; // for j = 1           // Bottom Up calculation from j = 2 to n     for (j = 2; j <= n; j++)     {         useOdd = 1 - useOdd;           // Here we are explicitly writing lines         // for each number 0 to 9. But it can always be         // written as DFS on 4X3 grid using row,         // column array valid moves         if(useOdd == 1)         {             even[0] = odd[0] + odd[8];             even[1] = odd[1] + odd[2] + odd[4];             even[2] = odd[2] + odd[1] +                       odd[3] + odd[5];             even[3] = odd[3] + odd[2] + odd[6];             even[4] = odd[4] + odd[1] +                       odd[5] + odd[7];             even[5] = odd[5] + odd[2] + odd[4] +                                odd[8] + odd[6];             even[6] = odd[6] + odd[3] +                       odd[5] + odd[9];             even[7] = odd[7] + odd[4] + odd[8];             even[8] = odd[8] + odd[0] + odd[5] +                                odd[7] + odd[9];             even[9] = odd[9] + odd[6] + odd[8];         }         else         {             odd[0] = even[0] + even[8];             odd[1] = even[1] + even[2] + even[4];             odd[2] = even[2] + even[1] +                      even[3] + even[5];             odd[3] = even[3] + even[2] + even[6];             odd[4] = even[4] + even[1] +                      even[5] + even[7];             odd[5] = even[5] + even[2] + even[4] +                                even[8] + even[6];             odd[6] = even[6] + even[3] +                      even[5] + even[9];             odd[7] = even[7] + even[4] + even[8];             odd[8] = even[8] + even[0] + even[5] +                                even[7] + even[9];             odd[9] = even[9] + even[6] + even[8];         }     }       // Get count of all possible numbers of     // length "n" starting with digit 0, 1, 2, ..., 9     totalCount = 0;     if(useOdd == 1)     {         for (i = 0; i <= 9; i++)             totalCount += even[i];     }     else     {         for (i = 0; i <= 9; i++)             totalCount += odd[i];     }     return totalCount; }   // Driver Code public static void Main(String[] args) {     char [,]keypad = {{'1','2','3'},                       {'4','5','6'},                       {'7','8','9'},                       {'*','0','#'}};     Console.Write("Count for numbers of length {0}: {1}\n", 1,                                         getCount(keypad, 1));     Console.Write("Count for numbers of length {0}: {1}\n", 2,                                         getCount(keypad, 2));     Console.Write("Count for numbers of length {0}: {1}\n", 3,                                         getCount(keypad, 3));     Console.Write("Count for numbers of length {0}: {1}\n", 4,                                         getCount(keypad, 4));     Console.Write("Count for numbers of length {0}: {1}\n", 5,                                         getCount(keypad, 5)); } }   // This code is contributed by 29AjayKumar

## Javascript



Output

Count for numbers of length 1: 10
Count for numbers of length 2: 36
Count for numbers of length 3: 138
Count for numbers of length 4: 532
Count for numbers of length 5: 2062

Auxiliary Space: O(1)

My Personal Notes arrow_drop_up
Related Articles