# Program to count number of stepping numbers of n digits in python

PythonServer Side ProgrammingProgramming

Suppose we have a number n we have to find the number of stepping numbers of n digit. As we know a number is called stepping number when all adjacent digits have an absolute difference of 1. So if a number is 123, this is stepping number but 124 is not. If the answer is very large then return result mod 10^9 + 7.

So, if the input is like n = 2, then the output will be 17, as the stepping numbers are [12, 23, 34, 45, 56, 67, 78, 89, 98, 87, 76, 65, 54, 43, 32, 21, 10]

To solve this, we will follow these steps −

• m := 10^9 + 7
• if n is same as 0, then
• return 0
• if n is same as 1, then
• return 10
• dp := a list of size 10 filled with value 1
• iterate n - 1 times, do
• ndp := a list of size 10 filled with value 0
• ndp := dp
• for i in range 1 to 8, do
• ndp[i] := dp[i - 1] + dp[i + 1]
• ndp := dp
• dp := ndp
• return (sum of all numbers of dp[from index 1 to end]) mod m

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, n):
m = (10 ** 9 + 7)
if n == 0:
return 0
if n == 1:
return 10
dp =  * 10
for _ in range(n - 1):
ndp =  * 10
ndp = dp
for i in range(1, 9):
ndp[i] = dp[i - 1] + dp[i + 1]
ndp = dp
dp = ndp
return sum(dp[1:]) % m

ob = Solution()
n = 3
print(ob.solve(n))

## Input

3

## Output

32