Count of N-digit numbers whose absolute difference between adjacent digits is non-increasing
Given a positive integer N, the task is to count the number of N-digit numbers having absolute difference between consecutive digits in non-increasing order.
Input: N = 1
All numbers from 0 to 9 satisfy the given condition as there is only one digit.
Input: N = 3
Naive Approach: The simplest approach to solve the given problem is to iterate over all possible N-digit numbers and count those numbers whose digits are in non-increasing order. After checking for all the numbers, print the value of count as the result.
Time Complexity: O(N * 10N)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by using Dynamic Programming because the above problem 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 digitth position till the end, when the previous digit selected, is prev1 and the second previous digit selected is prev2. Follow the steps below to solve the problem:
- Define a recursive function, say countOfNumbers(digit, prev1, prev2) by performing the following steps.
- 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.
- Otherwise iterate through all the numbers from i = 0 to i = 9, and check if the condition (abs(prev1 – i) <= abs(prev1 – prev2) ) holds valid or not and accordingly place satisfying ‘i’ values in 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.
- Print the value returned by the function countOfNumbers(1, 0, 0, N) as the result.
Below is the implementation of 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.