Open In App

Find second smallest number from sum of digits and number of digits

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given the sum of digits as S and the number of digits as D, the task is to find the second smallest number

Examples:

Input: S = 9, D = 2
Output: 27
Explanation: 18 is the smallest number possible with sum = 9 and total digits = 2, Whereas the second smallest is 27.

Input: S = 16, D = 3
Output: 178
Explanation: 169 is the smallest number possible with sum is 16 and total digits = 3, Whereas the second smallest is 178.

Approach: To solve the problem follow the below idea:

The idea is to use greedy approach and find the minimum element by filling all digits from least significant digit to most significant one by one, once we found the minimum element then we can easily find the second minimum element by using the next greater element in such a way that the sum of digits should be the same.

Illustration:

Let’s take an example to understand how we can find the second minimum element by using the next permutation concept:

Let minimum number = 10799. 

  • Start scanning the given number from the least significant(rightmost) digit to the most significant(leftmost) digit and whenever we found a digit less than 9 then increase it by one and decrease the next digit by one now this number is the second minimum number. 
  • Hence 2nd minimum element which is the next permutation of the minimum element = 10889.

Below are the steps for the above approach:

  • First, check the base case,
    • If the sum is greater than 9*number of digits that is the maximum possible sum we can get by using D number of digits, then return -1.
    • Check if sum == 1. then it is not possible to get the 2nd minimum element whose sum is greater than 1, hence return -1.
    • Check if D == 1, then only one possible way to get any number with any given sum hence return -1.
  • Initialize an empty string ans to store the resulting number and decrease the sum by one because we need to leave 1 for the last digit.
  • Now put the maximum possible number of 9 at end of the answer on the least significant side so that we can get the minimum number.
    • Run a loop from D – 1 to 0,
      • Check if the sum is greater than 9, add 9 to the ans, and subtract 9 from the sum.
      • Else add the sum to ans and set sum = 0.
  • Add 1 to the sum and append it to the string.
  • Reverse the ans string to get the correct ordering of digits.
  • Now we have a minimum number we get by using sum and D.
  • Now run a loop from the end of the answer to find the rightmost index equal to 9, and store the index in ind variable.
  • Decrement the digit at index ind by one, and increment the digit at index ind – 1 by one to get 2nd minimum element.
  • Return answer.

Below is the code for the above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
string secondSmallest(int S, int D)
{
 
    if (S >= D * 9 || S == 1 || D == 1)
        return "-1";
 
    int dup = D;
 
    S -= 1;
    string ans = "";
    for (int i = D - 1; i > 0; i--) {
        if (S > 9) {
            ans += '0' + 9;
            S -= 9;
        }
        else {
            ans += '0' + S;
            S = 0;
        }
    }
    ans += '0' + (S + 1);
    reverse(ans.begin(), ans.end());
 
    int ind = dup - 1;
    for (int i = dup - 1; i >= 0; i--) {
        if (ans[i] == '9')
            ind = i;
        else
            break;
    }
 
    ans[ind] -= 1;
    ans[ind - 1] += 1;
 
    return ans;
}
 
// Drivers code
int main()
{
 
    int S = 9, D = 2;
    string ans = secondSmallest(S, D);
 
    // Function Call
    cout << ans;
    return 0;
}
 
//This code is contributed by Akash Jha


Java




/*package whatever //do not write package name here */
 
import java.util.*;
 
public class Main {
 
    public static String secondSmallest(int S, int D)
    {
 
        if (S >= D * 9 || S == 1 || D == 1)
            return "-1";
 
        int dup = D;
 
        S -= 1;
        StringBuilder ans = new StringBuilder();
        for (int i = D - 1; i > 0; i--) {
            if (S > 9) {
                ans.append((char)('0' + 9));
                S -= 9;
            }
            else {
                ans.append((char)('0' + S));
                S = 0;
            }
        }
        ans.append((char)('0' + (S + 1)));
        ans.reverse();
 
        int ind = dup - 1;
        for (int i = dup - 1; i >= 0; i--) {
            if (ans.charAt(i) == '9')
                ind = i;
            else
                break;
        }
 
        ans.setCharAt(ind, (char)(ans.charAt(ind) - 1));
        ans.setCharAt(ind - 1,
                      (char)(ans.charAt(ind - 1) + 1));
 
        return ans.toString();
    }
 
    public static void main(String[] args)
    {
        int S = 9, D = 2;
        String ans = secondSmallest(S, D);
 
        // Function Call
        System.out.println(ans);
    }
}


Python3




# code
def second_smallest(S: int, D: int) -> str:
    if S >= D * 9 or S == 1 or D == 1:
        return "-1"
 
    dup = D
 
    S -= 1
    ans = ""
    for i in range(D - 1, 0, -1):
        if S > 9:
            ans += chr(ord('0') + 9)
            S -= 9
        else:
            ans += chr(ord('0') + S)
            S = 0
    ans += chr(ord('0') + (S + 1))
    ans = ans[::-1]
 
    ind = dup - 1
    for i in range(dup - 1, -1, -1):
        if ans[i] == '9':
            ind = i
        else:
            break
 
    ans = ans[:ind] + chr(ord(ans[ind]) - 1) + ans[ind + 1:]
    ans = ans[:ind - 1] + chr(ord(ans[ind - 1]) + 1) + ans[ind:]
 
    return ans
 
# Drivers code
S = 9
D = 2
ans = second_smallest(S, D)
 
# Function Call
print(ans)


C#




using System;
 
class Program
{
  static string SecondSmallest(int S, int D)
  {
    if (S >= D * 9 || S == 1 || D == 1)
      return "-1";
 
    int dup = D;
 
    S -= 1;
    string ans = "";
    for (int i = D - 1; i > 0; i--)
    {
      if (S > 9)
      {
        ans += (char)('0' + 9);
        S -= 9;
      }
      else
      {
        ans += (char)('0' + S);
        S = 0;
      }
    }
    ans += (char)('0' + (S + 1));
    char[] arr = ans.ToCharArray();
    Array.Reverse(arr);
    ans = new string(arr);
 
    int ind = dup - 1;
    for (int i = dup - 1; i >= 0; i--)
    {
      if (ans[i] == '9')
        ind = i;
      else
        break;
    }
 
    ans = ans.Substring(0, ind) + (char)(ans[ind] - 1) + ans.Substring(ind + 1);
    ans = ans.Substring(0, ind - 1) + (char)(ans[ind - 1] + 1) + ans.Substring(ind);
 
    return ans;
  }
 
  static void Main(string[] args)
  {
    int S = 9, D = 2;
    string ans = SecondSmallest(S, D);
 
    // Function Call
    Console.WriteLine(ans);
  }
}


Javascript




function second_smallest(S, D) {
    // If S is greater than or equal to 9 times D or S or D is 1, return -1
    if (S >= D * 9 || S == 1 || D == 1) {
        return "-1";
    }
 
    let dup = D;
 
    // Decrement S by 1
    S -= 1;
    let ans = "";
    for (let i = D - 1; i > 0; i--) {
        if (S > 9) {
            // Append '9' to ans and decrement S by 9
            ans += String.fromCharCode('0'.charCodeAt(0) + 9);
            S -= 9;
        } else {
            // Append the character corresponding to S + '0' to ans and set S to 0
            ans += String.fromCharCode('0'.charCodeAt(0) + S);
            S = 0;
        }
    }
    // Append the character corresponding to (S + 1) + '0' to ans
    ans += String.fromCharCode('0'.charCodeAt(0) + (S + 1));
    // Reverse ans
    ans = ans.split("").reverse().join("");
 
    let ind = dup - 1;
    for (let i = dup - 1; i >= 0; i--) {
        if (ans[i] == '9') {
            ind = i;
        } else {
            break;
        }
    }
 
    // Replace the character at index ind in ans with the character that comes before it in the ASCII table
    ans = ans.substring(0, ind) + String.fromCharCode(ans.charCodeAt(ind) - 1) + ans.substring(ind + 1);
    // Replace the character at index ind - 1 in ans with the character that comes after it in the ASCII table
    ans = ans.substring(0, ind - 1) + String.fromCharCode(ans.charCodeAt(ind - 1) + 1) + ans.substring(ind);
 
    return ans;
}
 
// Drivers code
let S = 9;
let D = 2;
let ans = second_smallest(S, D);
 
// Function Call
console.log(ans);


Output

27

Time Complexity: O(D), As we a loop D times.
Auxiliary Space: O(D), As we take a string of size D to store the answer.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads