Program to find numbers with same consecutive differences in Python

PythonServer Side ProgrammingProgramming

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]
raja
Updated on 07-Oct-2021 12:29:23

Advertisements