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 = 2

Output:

18

Explanation: 18 is the smallest number possible with the sum of digits = 9 and total digits = 2.

My Approach

  1. Check Feasibility:

  • If the sum s is greater than 9 * d, it is not possible to create such a number. Return -1 in this case.

  1. Initialization:

  • Create a string result with d zeros.

  • Decrement s by 1 to handle the smallest non-zero digit scenario.

  1. Digit Assignment:

  • Iterate from the rightmost digit to the leftmost.

  • Assign the maximum possible digit (9 or less) to each position until the sum s is exhausted.

  1. 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