15(July) Smallest number
15. Smallest Number
The problem can be found at the following link: Question Link
Problem Description
Given two integers s and d, the task is to find the smallest number such that the sum of its digits is s and the number of digits in the number are d. Return a string that is the smallest possible number. If it is not possible, then return -1.
Example:
Input:
s = 9, d = 2Output:
18Explanation: 18 is the smallest number possible with the sum of digits = 9 and total digits = 2.
My Approach
Check Feasibility:
If the sum
sis greater than9 * d, it is not possible to create such a number. Return-1in this case.
Initialization:
Create a string
resultwithdzeros.Decrement
sby 1 to handle the smallest non-zero digit scenario.
Digit Assignment:
Iterate from the rightmost digit to the leftmost.
Assign the maximum possible digit (9 or less) to each position until the sum
sis exhausted.
Adjust the First Digit:
Add 1 to the first digit to compensate for the initial decrement of
s.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(d), as we iterate through the digits up to
d.Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated