A string is called good if it is made with only digits 0 to 9 and adjacent elements are different. The task is to find the sum of the digits of all possible good strings of length X that end with the given digit Y. The answer could be large so print the answer modulo 109 + 7.
Input: X = 2, Y = 2
All possible strings of length 2 that end with 2 are:
02, 12, 32, 42, 52, 62, 72, 82, 92.
Now, ((0 + 2) + (1 + 2) + (3 + 2) + (4 + 2) + (5 + 2)
+ (6 + 2) + (7 + 2) + (8 + 2) + (9 + 2)) = 61
Input: X = 6, Y = 4
Approach: This problem can be solved by using dynamic programming. Lets define the following states:
- dp[i][j]: Sum of the digits of all possible good strings of length i that end with j.
- cnt[i][j]: Count of the good strings of length i that end with j.
The value of the previous state will have to be used to compute the value for the current state as the adjacent digits have to be compared whether they are equal or not. Now, the recurrence relation will be:
dp[i][j] = dp[i][j] + dp[i – 1][k] + cnt[i – 1][k] * j
Here, dp[i – 1][k] is the sum of the digits of good strings of length (i – 1) that end with k and k != j.
cnt[i -1][k] is the count of good strings of length (i – 1) that end with k and k != j.
So for position i, (cnt(i – 1)[k] * j) has to be added as j is being put at index i and the count of possible strings that have length (i – 1) is cnt[i – 1][k].
Below is the implementation of the above approach:
Time Complexity: O(N)
- Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
- Find the number of good permutations
- Find all good indices in the given Array
- Print all Good numbers in given range
- Find the good permutation of first N natural numbers
- Find the shortest distance between any pair of two different good nodes
- Minimum number of elements that should be removed to make the array good
- Check whether product of digits at even places is divisible by sum of digits at odd place of a number
- Maximize the given number by replacing a segment of digits with the alternate digits given
- Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
- Find the minimum number of elements that should be removed to make an array good
- Numbers with sum of digits equal to the sum of digits of its all prime factor
- Count numbers in given range such that sum of even digits is greater than sum of odd digits
- Find the average of k digits from the beginning and l digits from the end of the given number
- Check if the sum of digits of number is divisible by all of its digits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.