N digit numbers having difference between the first and last digits as K
Given two integer N and K, the task is to print all positive numbers made up of N digits whose difference between the first and last digits equal to K.
Input: N = 2, K = 0
Output: 11, 22, 33, 44, 55, 66, 77, 88, 99
Input: N = 2, K = 9
Approach: The idea is to generate all possible 1-digit numbers to N-digit numbers using recursion and check if the difference between the first and the last digit of that number is equal to K or not. Below are the steps:
- Generate all possible numbers with length 1.
- At each step, keep on adding digits to the number until the length of the number becomes N.
- When the length of the number becomes equal to N, calculate the difference between the first and last digit of the number, and check if the difference is equal to N or not. If found to be true, print that number and proceed to generate the next number.
Below is the implementation of the above approach:
Time Complexity: O(2N)
Auxiliary Space: O(N)