Count of strictly increasing N-digit numbers
Given a positive integer N, the task is to find the number of N-digit numbers such that every digit is smaller than its adjacent digits.
Input: N = 1
Explanation: All numbers from [0 – 9] satisfy the 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 for each such number, check if all its digits satisfy the given criteria or not. If found to be true, then count these numbers. After checking for all the numbers print the total count obtained.
Time Complexity: O(10N*N)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by using Dynamic Programming because it has overlapping subproblems and optimal substructure. The subproblems can be stored in dp table using memoization where dp[i][prev][sign] stores the result from the ith position till the end, when the previous digit selected, is prev and the variable sign is used to indicate if the current digit must be lesser or greater than the previous digit. Follow the steps below to solve the problem:
- Define a recursive function, say, countOfNumbers(digit, prev, sign) with three parameters: digit, sign and prev.
- Check for the base cases, i.e., if the value of i is equal to N then return 1 as a valid N-digit number is formed.
- Initialize a variable, say, val = 0, to store all possible counts of N-digit numbers.
- If i is 0, then any digit from [1 – 9] can be placed, and also if N = 1, then 0 can be placed as well.
- If i is 1, then any digit from [0 – 9] can be placed such that the current digit is not equal to the previous one.
- If the value of the sign is 1, then place the current digit such that it is less than the previous digit and change the sign to 0 for the next recursive call.
- If the value of the sign is 0, then place the current digit such that it is more than the previous digit and change the sign to 1 for the next recursive call.
- 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 result of each current recursive call.
- After the above steps, print the value returned by the function countOfNumbers(0, N, 0, 0) as the resultant count.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.