Generate all N digit numbers having absolute difference as K between adjacent digits

Given two integers N and K, the task is to generate all positive integers with length N having an absolute difference of adjacent digits equal to K.

Examples:

Input: N = 4, K = 8
Output: 1919, 8080, 9191
Explanation:
The absolute difference between every consecutive digit of each number is 8.
For Example: 8080 (abs(8-0) = 8, abs(0-8) = 8)

Input: N = 2, K = 2
Output: 13, 24, 20, 35, 31, 46, 42, 57, 53, 68, 64, 79, 75, 86, 97
Explanation:
The absolute difference between every consecutive digit of each number is 1.
 

Approach: The idea is to use Backtracking. Iterate over digits [1, 9] and for each digit form the N-digit number having a difference of absolute digit as K using recursion. Below are the steps:



  1. Create an vector ans[] to store all the resulting numbers and recursively iterate from 1 to 9 to generate numbers starting from each digit. Below are the cases: 
    • Base Case: For all integers of a single length, that is, N = 1, add them to ans[].
    • Recursive Call: If adding digit K to the numbers to one’s digit doesn’t exceed 9, then recursively call by decreasing the N and update num to (10*num + num%10 + K) as shown below:

      if(num % 10 + K <= 9) { 
         recursive_function(10 * num + (num % 10 + K), K, N – 1, and); 
      }

    • If the value of K is non-zero after all the recursive call and if num % 10 >= K, then again recursively call by decreasing the N and update num to (10*num + num%10 – K) as:

      recursive_function(10 * num + num % 10 – K, K, N – 1, ans);

  2. After all the above steps, print the numbers stored in ans[].

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function that recursively finds the
// possible numbers and append into ans
void checkUntil(int num, int K,
                int N, vector<int>& ans)
{
    
    // Base Case
    if (N == 1) 
    {
        ans.push_back(num);
        return;
    }
  
    // Check the sum of last digit and k
    // less than or equal to 9 or not
    if ((num % 10 + K) <= 9)
        checkUntil(10 * num
                       + (num % 10 + K),
                   K, N - 1, ans);
  
    // If k==0, then subtraction and
    // addition does not make any
    // difference
    // Hence, subtraction is skipped
    if (K) {
        if ((num % 10 - K) >= 0)
            checkUntil(10 * num
                           + num % 10 - K,
                       K, N - 1,
                       ans);
    }
}
  
// Function to call checkUntil function
// for every integer from 1 to 9
void check(int K, int N, vector<int>& ans)
{
    // check_util function recursively
    // store all numbers starting from i
    for (int i = 1; i <= 9; i++) {
        checkUntil(i, K, N, ans);
    }
}
  
// Function to print the all numbers
// which  satisfy the conditions
void print(vector<int>& ans)
{
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << ", ";
    }
}
  
// Driver Code
int main()
{
    // Given N and K
    int N = 4, K = 8;
  
    // To store the result
    vector<int> ans;
  
    // Function Call
    check(K, N, ans);
  
    // Print Resultant Numbers
    print(ans);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for 
// the above approach
import java.util.*;
class GFG{
  
    // Function that recursively finds the
    // possible numbers and append into ans
    static void checkUntil(int num, int K, int N,
                           Vector<Integer> ans)
    {
        
        // Base Case
        if (N == 1
        {
            ans.add(num);
            return;
        }
  
        // Check the sum of last digit and k
        // less than or equal to 9 or not
        if ((num % 10 + K) <= 9)
            checkUntil(10 * num + (num % 10 + K), 
                       K, N - 1, ans);
  
        // If k==0, then subtraction and
        // addition does not make any
        // difference
        // Hence, subtraction is skipped
        if (K > 0
        {
            if ((num % 10 - K) >= 0)
                checkUntil(10 * num + num % 10 - K, 
                           K, N - 1, ans);
        }
    }
  
    // Function to call checkUntil function
    // for every integer from 1 to 9
    static void check(int K, int N, Vector<Integer> ans)
    {
        
        // check_util function recursively
        // store all numbers starting from i
        for (int i = 1; i <= 9; i++) 
        {
            checkUntil(i, K, N, ans);
        }
    }
  
    // Function to print the all numbers
    // which  satisfy the conditions
    static void print(Vector<Integer> ans)
    {
        for (int i = 0; i < ans.size(); i++) 
        {
            System.out.print(ans.get(i) + ", ");
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Given N and K
        int N = 4, K = 8;
  
        // To store the result
        Vector<Integer> ans = new Vector<Integer>();;
  
        // Function Call
        check(K, N, ans);
  
        // Print Resultant Numbers
        print(ans);
    }
}
  
// This code is contributed by Amit Katiyar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
  
# Function that recursively finds the
# possible numbers and append into ans
def checkUntil(num, K, N, ans):
      
    # Base Case
    if (N == 1):
        ans.append(num)
        return
  
    # Check the sum of last digit and k
    # less than or equal to 9 or not
    if ((num % 10 + K) <= 9):
        checkUntil(10 * num +
                 (num % 10 + K), 
                 K, N - 1, ans)
  
    # If k==0, then subtraction and
    # addition does not make any
    # difference
    # Hence, subtraction is skipped
    if (K):
        if ((num % 10 - K) >= 0):
            checkUntil(10 * num + 
                      num % 10 - K, 
                     K, N - 1, ans)
      
# Function to call checkUntil function
# for every integer from 1 to 9
def check(K, N, ans):
      
    # check_util function recursively
    # store all numbers starting from i
    for i in range(1, 10):
        checkUntil(i, K, N, ans)
  
# Function to print the all numbers
# which satisfy the conditions
def print_list(ans):
      
    for i in range(len(ans)):
        print(ans[i], end = ", ")
  
# Driver Code
if __name__ == "__main__":
  
    # Given N and K
    N = 4
    K = 8;
  
    # To store the result
    ans = []
  
    # Function call
    check(K, N, ans)
  
    # Print resultant numbers
    print_list(ans)
  
# This code is contributed by chitranayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function that recursively finds the
// possible numbers and append into ans
static void checkUntil(int num, int K, int N,
                       List<int> ans)
{
  
    // Base Case
    if (N == 1) 
    {
        ans.Add(num);
        return;
    }
  
    // Check the sum of last digit and k
    // less than or equal to 9 or not
    if ((num % 10 + K) <= 9)
        checkUntil(10 * num + (num % 10 + K), 
                 K, N - 1, ans);
  
    // If k==0, then subtraction and
    // addition does not make any
    // difference
    // Hence, subtraction is skipped
    if (K > 0) 
    {
        if ((num % 10 - K) >= 0)
            checkUntil(10 * num + num % 10 - K, 
                     K, N - 1, ans);
    }
}
  
// Function to call checkUntil function
// for every integer from 1 to 9
static void check(int K, int N, List<int> ans)
{
  
    // check_util function recursively
    // store all numbers starting from i
    for(int i = 1; i <= 9; i++) 
    {
        checkUntil(i, K, N, ans);
    }
}
  
// Function to print the all numbers
// which satisfy the conditions
static void print(List<int> ans)
{
    for(int i = 0; i < ans.Count; i++) 
    {
        Console.Write(ans[i] + ", ");
    }
}
  
// Driver Code
public static void Main(String[] args)
{
      
    // Given N and K
    int N = 4, K = 8;
  
    // To store the result
    List<int> ans = new List<int>();;
  
    // Function call
    check(K, N, ans);
  
    // Print Resultant Numbers
    print(ans);
}
}
  
// This code is contributed by Amit Katiyar

chevron_right


Output: 

1919, 8080, 9191,

Time Complexity: O(2N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:



If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.