- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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[0] := dp[1]
- for i in range 1 to 8, do
- ndp[i] := dp[i - 1] + dp[i + 1]

- ndp[9] := dp[8]
- 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

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

## Input

3

## Output

32

- Related Articles
- Number of n digit stepping numbers in C++
- Write a program in Python to count the number of digits in a given number N
- Program to count total number of set bits of all numbers in range 0 to n in Python
- Count Numbers with N digits which consists of even number of 0's in C++
- Count Numbers with N digits which consists of odd number of 0's in C++
- Count total number of digits from 1 to N in C++
- Program to count number of BST with n nodes in Python
- Golang Program to Count the Number of Digits in a Number
- Program to count number of common divisors of two numbers in Python
- Program to count number of elements in a list that contains odd number of digits in Python
- Swift Program to Count Number of Digits in an Integer
- Java Program to Count Number of Digits in an Integer
- Kotlin Program to Count Number of Digits in an Integer
- Count of n digit numbers whose sum of digits equals to given sum in C++
- Total number of non-decreasing numbers with n digits

Advertisements