Find second smallest number from sum of digits and number of digits
Last Updated :
25 Apr, 2023
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);
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.
Similar Reads
Find smallest number with given digits and sum of digits Given two positive integers P and Q, find the minimum integer containing only digits P and Q such that the sum of the digits of the integer is N. Example: Input: N = 11, P = 4, Q = 7 Output: 47Explanation: There are two possible integers that can be formed from 4 and 7 such that their sum is 11 i.e.
9 min read
Find the Largest number with given number of digits and sum of digits Given an integer s and d, The task is to find the largest number with given digit sum s and the number of digits d. Examples: Input: s = 9, d = 2Output: 90 Input: s = 20, d = 3Output: 992 Recommended PracticeLargest number possibleTry It! Naive Approach: Consider all m digit numbers and keep a max v
13 min read
Smallest number with given sum of digits and sum of square of digits Given the sum of digits a and sum of the square of digits b . Find the smallest number with the given sum of digits and the sum of the square of digits. The number should not contain more than 100 digits. Print -1 if no such number exists or if the number of digits is more than 100.Examples: Input :
15+ min read
Find smallest number with given number of digits and sum of digits under given constraints Given two integers S and D, the task is to find the number having D number of digits and the sum of its digits as S such that the difference between the maximum and the minimum digit in the number is as minimum as possible. If multiple such numbers are possible, print the smallest number.Examples: I
7 min read
Number obtained by reducing sum of digits of 2N into a single digit Given a positive integer N, the task is to find the single digit obtained after recursively adding the digits of 2N until a single digit remains. Examples: Input: N = 6Output: 1Explanation: 26 = 64. Sum of digits = 10.Now, Sum of digits = 10. Therefore, sum is 1. Input: N = 10Output: 7Explanation: 2
4 min read
Smallest multiple of a given number made of digits 0 and 9 only We are given an integer N. We need to write a program to find the least positive integer X made up of only digits 9's and 0's, such that, X is a multiple of N. Note: It is assumed that the value of X will not exceed 106. Examples: Input : N = 5 Output : X = 90 Explanation: 90 is the smallest number
8 min read
Find the kth smallest number with sum of digits as m Given two integers M and K, the task is to find the Kth smallest number with digit sum as M.Examples: Input: M = 5, K = 3 Output: 23 Sequence of numbers starting from 1 with digit sum as 5 is as follows: 5 14 23 32 41 So 3rd smallest number is 23Input: M = 4, K = 1 Output: 4 Approach: We need to fin
6 min read
Smallest number by rearranging digits of a given number Find the Smallest number (Not leading Zeros) which can be obtained by rearranging the digits of a given number. Examples: Input: n = 846903Output: 304689Input: n = 55010Output: 10055Input: n = -40505Output: -55400Steps to find the smallest number. Count the frequency of each digit in the number.If i
7 min read
Smallest odd number with even sum of digits from the given number N Given a large number in form of string str. The task is to find the smallest odd number whose sum of digits is even by removing zero or more characters from the given string str, where the digits can be rearranged. Examples Input: str = "15470" Output: 15 Explanation: Two smallest odd digits are 1
6 min read