Given a positive number, map its digits to the corresponding alphabet in the mapping table [(1, 'A'), (2, 'B'), … (26, 'Z')], and return the count of the total number of decodings possible. Assume that the input number can be split into valid single-digit or two-digit numbers that are present in the mapping table.

For example,

Input:  123
 
Output: 3
 
The possible decodings are [ABC, AW, LC]
 
 
Input:  1221
 
Output: 5
 
The possible decodings are [ABBA, ABU, AVA, LBA, LU]

Practice this problem

From the above examples, it is evident that,

  • A single-digit between 1–9 can be mapped to a corresponding alphabet between A–I.
  • Two digits between 10–26 can be mapped to a corresponding alphabet between J–Z.

So, the problem of computing T(n) for an n–digit number can be broken down into the subproblems of computing T(n-1) if the last digit lies between 1–9 and computing T(n-2) if the last two digits lie between 10–26, and finally adding the two.

 
The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The total number of decodings are 5

Java


Download  Run Code

Output:

The total number of decodings are 5

Python


Download  Run Code

Output:

The total number of decodings are 5

The time complexity of the above solution is exponential as several subproblems are recalculated repeatedly. It also requires extra space for the recursion (call stack).

 
If we take a closer look at the solution, the value of T(n) can be calculated in constant time if the values of T(n-1) and T(n-2) are known in advance. The idea is to solve the smaller subproblems first and then solve the larger subproblems using the already computed results of the smaller subproblems. This approach is also known as the bottom-up approach and used to solve dynamic programming problems.

Following is the dynamic programming solution in C++, Java, and Python, where solutions to the subproblems are derived in a bottom-up manner:

C++


Download  Run Code

Output:

The total number of decodings are 5

Java


Download  Run Code

Output:

The total number of decodings are 5

Python


Download  Run Code

Output:

The total number of decodings are 5

The time complexity of the above dynamic programming solution is O(n), where n is the length of the input sequence. The extra space used by the program is O(n) for the auxiliary array.

 
However, the code only reads the last two elements from the auxiliary array at any point. Therefore, the space complexity can be further reduced to O(1) by keeping track of the solutions to only the last two subproblems. This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

The total number of decodings are 5

Java


Download  Run Code

Output:

The total number of decodings are 5

Python


Download  Run Code

Output:

The total number of decodings are 5