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 The numbers are 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, 87, 89, 98. Input : 1 Output : 10 The numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
In the previous post a solution that requires O(n) auxiliary space is discussed. The auxiliary space required to solve the problem can be optimized. The 2-D dp array dp[i][j] represents count of stepping number of length i and last digit j. For a digit j the count is obtained from digit j – 1 and j + 1. The recurrence relation is dp[i][j] = dp[i-1][j-1] + dp[i-1][j+1] . Observe that the answer for current length i depends only on i – 1. So a 1-D dp array can be used in which for a given i, dp[j] stores count of stepping numbers of length i ending with digit j. Before updating dp array for a given length i, store the result for length i – 1 in another array prev, then update dp array using prev array.
Below is the implementation of above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
- Number of n digit stepping numbers
- A Space Optimized Solution of LCS
- A Space Optimized DP solution for 0-1 Knapsack Problem
- Longest Common Substring (Space optimized DP solution)
- Word Wrap problem ( Space optimized solution )
- Printing Matrix Chain Multiplication (A Space Optimized Solution)
- Count of Numbers in Range where first digit is equal to last digit of the number
- Number of n digit numbers that do not contain 9
- Sum of n digit numbers divisible by a given number
- Number of occurrences of 2 as a digit in numbers from 0 to n
- Largest N digit number divisible by given three numbers
- Count n digit numbers divisible by given number
- Smallest n digit number divisible by given three numbers
- Largest Even and Odd N-digit numbers in Octal Number System
- Check whether a number can be expressed as a product of single digit numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.