Count number of integers in given range with adjacent digits different and sum of digits equal to M
Given integers T, A, and B, the task for this problem is to find numbers in the range [A, B] such that the adjacent digits of the number are different and the sum of digits is equal to T. ( A ≤ B ≤ 1018)
Input: T = 5, A = 1, B = 100
Explanation: 5, 14, 23, 32, 41, and 50 are valid integers that are in between the range 1 to 100 and have the sum of digits 5 along with adjacent digits different.
Input: T = 5, A = 1, B = 100000000
Naive approach: The basic way to solve the problem is as follows:
The basic way to solve this problem is to generate all possible combinations by using a recursive approach.
Time Complexity: O(18N), Where N is the number of digits from 0 to 9.
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following idea:
Dynamic programming can be used to solve this problem
- dp[i][j][k][sum] represents numbers with i digits, j is the tight condition pointer, k is the last digit taken and the sum is digit sum till i.
- It can be observed that the recursive function is called exponential times. That means that some states are called repeatedly.
- So the idea is to store the value of each state. This can be done using by the store the value of a state and whenever the function is called, returning the stored value without computing again.
Follow the steps below to solve the problem:
- Create a recursive function that takes four parameters i represents a position to be filled, j represents the tight condition pointer, k represents the last digit taken and sum represents the total sum of digits.
- Call the recursive function for choosing all digits from 0 to 9.
- Base case if N size digit formed and the sum of digits equal to T return 1 else return 0.
- Create a 4d array dp initially filled with -1.
- If the answer for a particular state is computed then save it in dp[i][j][k][sum].
- If the answer for a particular state is already computed then just return dp[i][j][k][sum].
Below is the implementation of the above approach:
Time Complexity: O(N2 * M * K2)
Auxiliary Space: O(N2 * M * K)
Please Login to comment...