Smallest positive number made up of non-repeating digits whose sum of digits is N
Given a positive integer N, the task is to find the smallest positive number made up of distinct digits having sum of its digits equal to N. If no such number exists, print “-1”.
Input: N = 11
Explanation: The sum of the digits = 2 + 9 = 11 ( = N).
Input: N = 46
Approach: The idea is based on the following observations:
- If N < 10: Required answer is N itself.
- If N > 45: Required answer is -1 as the smallest number that can be made using non-repeating digits is 123456789, whose sum of digits is 45.
- Otherwise: The answer can be obtained based on the following pattern.
Consider the following examples, to understand the pattern,
For N = 10: The output is 19.
For N = 11: The output is 29.
For N = 12: The output is 39.
For N = 13: The output is 49.
For N = 21: The output is 489.
For N = 22: The output is 589.
For N = 23: The output is 689.
On observing the above results, it is clear that the answer contains digits in decreasing order having a difference of 1 starting from one’s digit until the digit sum is less than N.
Follow the steps below to solve the problem:
- If the given number is less than 10, then print the number itself.
- If the given number is greater than 45, then print “-1”.
- Otherwise, perform the following steps:
- Initialize a string res to store the required answer and initialize a variable, say digit, as 9.
- Iterate a loop until N ≤ digit and perform the following steps:
- Push digit at the starting of res.
- Decrement N by digit.
- Decrement digit by 1.
- If the value of N is found to be greater than 0, then push the character at the starting of res.
- After completing the above steps, print the value of res as the answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.