Given n, find count of n digit Stepping numbers. A number is called stepping number if all adjacent digits have an absolute difference of 1. 321 is a Stepping Number while 421 is not.
Input : 2 Output : 17 Explanation: The numbers are 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, 87, 89, 98. Input : 1 Output : 10 Explanation: the numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
A naive approach is to run a loop for all n digit numbers and check for every number if it is Stepping.
An efficient approach is to use dynamic programming.
In dp[i][j], i denotes number of digits and j denotes last digit. // If there is only one digit if (i == 1) dp(i, j) = 1; // If last digit is 0. if (j == 0) dp(i, j) = dp(i-1, j+1) // If last digit is 9 else if (j == 9) dp(i, j) = dp(i-1, j-1) // If last digit is neither 0 // nor 9. else dp(i, j) = dp(i-1, j-1) + dp(i-1, j+1) Result is ∑dp(n, j) where j varies from 1 to 9.
Time Complexity: O(n)
Auxiliary Space: O(n)Number of n digit stepping numbers | Space optimized solution
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Number of n digit stepping numbers | Space optimized solution
- Count of Numbers in Range where first digit is equal to last digit of the number
- Program to print first N Stepping numbers
- Print Nth Stepping or Autobiographical number
- Number of n digit numbers that do not contain 9
- Number of occurrences of 2 as a digit in numbers from 0 to n
- Sum of n digit numbers divisible by a given number
- Count n digit numbers divisible by given number
- Smallest n digit number divisible by given three numbers
- Largest N digit number divisible by given three numbers
- Largest Even and Odd N-digit numbers in Octal Number System
- Largest Even and Odd N-digit numbers in Hexadecimal Number System
- Print all K digit repeating numbers in a very large number
- Count total number of N digit numbers such that the difference between sum of even and odd digits is 1
- Check whether a number can be expressed as a product of single digit numbers
- Count numbers with difference between number and its digit sum greater than specific value
- Count numbers in a range with digit sum divisible by K having first and last digit different
- Count n digit numbers not having a particular digit
- Min steps to convert N-digit prime number into another by replacing a digit in each step
- Find the remainder when First digit of a number is divided by its Last digit