Let the encoded sequence be 121,
The first way to decode 121 is:
1 = A
2 = B
1 = A
Thus, the decoded string will be ABA.
The second way to decode 121 is:
12 = L
1 = A
Thus, the decoded string will be LA.
The third way to decode 121 is:
1 = A
21 = U
Thus, the decoded string will be AU.
So, there will be 3 ways to decode the sequence 121 i.e. [(ABA), (LA), (AU)].
The input sequence will always have at least 1 possible way to decode.
As the answer can be large, return your answer modulo 10^9 + 7.
Can you solve this using constant extra space?
The first line of input contains an integer T denoting the number of queries or test cases.
The first and only line of each test case contains a digit sequence.
For each test case, print the number of ways to decode the given digit sequence in a separate line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^5
0 <= SEQ[i] <= 9
Time limit: 1 sec
Let’s understand the problem in the previous approach by an example
Suppose we have a sequence 1111, So, now, let’s plot the recursive tree for the above recursive solution.
As we can see in the above diagram:
Note: Subproblem { seq, n } means a problem with ‘seq’ as digit sequence and ‘n’ as the size of the sequence.
To optimize the overlapping sub-problem calculation, we will use memoization by storing answers for each recursive state.
Approach:
We may realise from the previous approaches that we only need the last 2 values of the DP array to fetch the current answer.
In this approach, we will be working on this idea.