Count N-digit numbers whose digits does not exceed absolute difference of the two previous digits
Given an integer N, the task is to count the number of N-digit numbers such that each digit, except the first and second digits, is less than or equal to the absolute difference of the previous two digits.
Input: N = 1
Explanation: All the numbers from [0 – 9] are valid because the number of digits is 1.
Input : N = 3
Output : 375
Naive Approach: The simplest approach is to iterate over all possible N-digit numbers and for each such numbers, check if all its digits satisfy the above condition or not.
Time Complexity: O(10N*N)
Auxiliary Space: O(1)
Efficient Approach: In the efficient approach, all possible numbers are constructed instead of verifying the conditions on a range of numbers. This can be achieved with the help of Dynamic Programming because it has overlapping subproblems and optimal substructure. The subproblems can be stored in dp table using memoization where dp[digit][prev1][prev2] stores the answer from the digit-th position till the end, when the previous digit selected, is prev1 and the second most previous digit selected is prev2.
Follow the below steps to solve the problem:
- Define a recursive function countOfNumbers(digit, prev1, prev2) by performing the following steps.
- Check the base cases. If the value of digit is equal to N+1 then return 1 as a valid N-digit number is formed.
- If the result of the state dp[digit][prev1][prev2] is already computed, return this state dp[digit][prev1][prev2].
- If the current digit is 1, then any digit from [1-9] can be placed. If N=1, then 0 can be placed as well.
- If the current digit is 2, then any digit from [0-9] can be placed.
- Else any number from [0-(abs(prev1-prev2))] can be placed at the current position.
- After making a valid placement, recursively call the countOfNumbers function for index digit+1.
- Return the sum of all possible valid placements of digits as the answer.
Below is the code for the above approach:
Time Complexity : O(N * 103)
Auxiliary Space: O(N * 102)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.