- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- 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 find numbers with same consecutive differences in Python

Suppose we have to find an array of size N such that the absolute difference between every two consecutive digits is K. Every number in the answer must not have leading zeros except for the number 0 itself.

So, if the input is like N = 4 K = 7, then the output will be [1818, 2929, 7070, 8181, 9292], here 0707 is not valid as it has leading 0.

To solve this, we will follow these steps −

if N is same as 1, then

return a new list from range 0 to 9

queue := make a queue with all elements from 1 to 9

for n in range 0 to N - 2, do

len_queue := size of queue

for j in range 0 to len_queue - 1, do

num := left item of queue, and delete it from queue

lsd := num mod 10

if lsd - K >= 0, then

insert num * 10 + lsd - K at the end of queue

if K and lsd + K <= 9, then

insert num * 10 + lsd + K at the end of queue

return elements of queue

## Example

Let us see the following implementation to get better understanding −

from collections import deque def solve(N, K): if N == 1: return list(range(10)) queue = deque(list(range(1, 10))) for n in range(N - 1): len_queue = len(queue) for j in range(len_queue): num = queue.popleft() lsd = num % 10 if lsd - K >= 0: queue.append( num * 10 + lsd - K ) if K and lsd + K <= 9: queue.append( num * 10 + lsd + K ) return list(queue) N = 4 K = 7 print(solve(N, K))

## Input

4, 7

## Output

[1818, 2929, 7070, 8181, 9292]

- Related Questions & Answers
- Numbers With Same Consecutive Differences in C++
- Program to find concatenation of consecutive binary numbers in Python
- Program to pack same consecutive elements into sublist in Python
- Program to find tuple with same product in Python
- Python program for sum of consecutive numbers with overlapping in lists
- Program to find length of substring with consecutive common characters in Python
- Program to find length of longest consecutive sublist with unique elements in Python
- C++ program to find two numbers with sum and product both same as N
- Program to find length of longest consecutive sequence in Python
- Find two numbers with sum and product both same as N in C++ Program
- Compute the differences between consecutive elements and prepend numbers in Numpy
- Find missing element in a sorted array of consecutive numbers in Python
- Program to find string after removing consecutive duplicate characters in Python
- Program to find array by swapping consecutive index pairs in Python
- Program to find length of shortest sublist with maximum frequent element with same frequency in Python