Smallest number whose sum of digits is N and every digit occurring at most K times
Given two positive integers N and K, the task is to find the smallest number whose sum of digits is N and every distinct digit in that number occurs at most K times. If no such number exists, print “-1”.
Examples:
Input: N = 25, K = 3
Output: 799
Explanation: Sum of digits of the number = (7 + 9 + 9) = 25 and is the smallest possible.
Input: N =100, K = 2
Output: -1
Approach: The given problem can be solved using Greedy Approach. Follow the steps to solve the problem:
- The maximum possible sum of digits of any number having each digit occurring at most K times is K * 45.
- Initialize a string, say res, to store the resultant string formed.
- If N is greater than K * 45, no such number can be obtained. Therefore, print “-1”.
- Otherwise, keep subtracting every number starting from 9 to 1, from N, at most K times. Add the current digit to res. Continue until N is smaller than the current digit.
- If N is smaller than the current digit, insert N as a digit to res.
- After completing the above steps, print the string res in the reversed order as the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findSmallestNumberPossible( int N, int K)
{
if (N > 45 * K) {
cout << "-1" ;
return ;
}
string res = "" ;
int count = 0;
for ( int i = 9; i >= 1;) {
if (count == K) {
i--;
count = 0;
}
if (N > i) {
N -= i;
res += ( char )48 + i;
}
else {
res += ( char )N + 48;
N = 0;
break ;
}
count++;
}
reverse(res.begin(),
res.end());
cout << res;
}
int main()
{
int N = 25, K = 3;
findSmallestNumberPossible(N, K);
return 0;
}
|
Java
import java.io.*;
class GFG{
static void findSmallestNumberPossible( int N, int K)
{
if (N > 45 * K)
{
System.out.print( "-1" );
return ;
}
StringBuilder res = new StringBuilder();
int count = 0 ;
for ( int i = 9 ; i >= 1 😉
{
if (count == K)
{
i--;
count = 0 ;
}
if (N > i)
{
N -= i;
res.append(( char )( '0' + i));
}
else
{
res.append(( char )( '0' + N));
N = 0 ;
break ;
}
count++;
}
res.reverse();
System.out.print(res.toString());
}
public static void main(String[] args)
{
int N = 25 , K = 3 ;
findSmallestNumberPossible(N, K);
}
}
|
Python3
def findSmallestNumberPossible(N, K) :
if (N > 45 * K) :
print ( "-1" , endl = "");
return ;
res = "";
count = 0 ;
i = 9 ;
while i > = 1 :
if (count = = K) :
i - = 1 ;
count = 0 ;
if (N > i) :
N - = i;
res + = chr ( 48 + i);
else :
res + = chr (N + 48 );
N = 0 ;
break ;
count + = 1 ;
res = res[:: - 1 ]
print (res, end = "");
if __name__ = = "__main__" :
N = 25 ; K = 3 ;
findSmallestNumberPossible(N, K);
|
C#
using System;
class GFG
{
static void findSmallestNumberPossible( int N, int K)
{
if (N > 45 * K)
{
Console.Write( "-1" );
return ;
}
string res = "" ;
int count = 0;
for ( int i = 9; i >= 1;)
{
if (count == K)
{
i--;
count = 0;
}
if (N > i)
{
N -= i;
res += ( char )( '0' + i);
}
else
{
res += ( char )( '0' + N);
N = 0;
break ;
}
count++;
}
string ans = "" ;
for ( int i = res.Length - 1; i >= 0; i--)
{
ans += res[i] + "" ;
}
Console.WriteLine(ans);
}
public static void Main()
{
int N = 25, K = 3;
findSmallestNumberPossible(N, K);
}
}
|
Javascript
<script>
function findSmallestNumberPossible(N, K) {
if (N > 45 * K) {
document.write( "-1" );
return ;
}
var res = "" ;
var count = 0;
for ( var i = 9; i >= 1; ) {
if (count === K) {
i--;
count = 0;
}
if (N > i) {
N -= i;
res += String.fromCharCode( "0" .charCodeAt(0) + i);
} else {
res += String.fromCharCode( "0" .charCodeAt(0) + N);
N = 0;
break ;
}
count++;
}
var ans = "" ;
for ( var i = res.length - 1; i >= 0; i--) {
ans += res[i] + "" ;
}
document.write(ans);
}
var N = 25,
K = 3;
findSmallestNumberPossible(N, K);
</script>
|
Time Complexity: O(log10N)
Auxiliary Space: O(1)
Another Approach:
- Create a function named findSmallestNumberPossible that takes two integer parameters N and K.
- If N is greater than the maximum possible sum of digits (K * 45), output -1 as it is impossible to form such a number. Otherwise, continue.
- Create an integer array freq with size 10 to store the frequency of each digit.
- Create an empty string res to store the result.
- Initialize the sum of digits sum to 0.
- Iterate over the digits from 9 to 0 using a for loop.
- While the frequency of digit i is less than K and the sum of digits is less than or equal to N, do the following:
a. Increment the frequency of digit i.
b. Add digit i to the front of the result string res.
c. Update the sum of digits sum by adding i.
- Remove leading zeros from the result string by iterating over it and counting the number of zeros at the beginning.
- If the result string contains only zeros, output 0. Otherwise, output the result string without leading zeros.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <string>
using namespace std;
void findSmallestNumberPossible( int N, int K)
{
if (N > K * 45) {
cout << "-1" << endl;
return ;
}
int freq[10] = {0};
string res = "" ;
int sum = 0;
for ( int i = 9; i >= 0; i--) {
while (freq[i] < K && sum + i <= N) {
freq[i]++;
res = ( char )( '0' + i) + res;
sum += i;
}
}
int zeros = 0;
while (zeros < res.length() && res[zeros] == '0' ) {
zeros++;
}
if (zeros == res.length()) {
cout << "0" << endl;
} else {
cout << res.substr(zeros) << endl;
}
}
int main()
{
int N = 25, K = 3;
findSmallestNumberPossible(N, K);
return 0;
}
|
Java
import java.util.Arrays;
public class SmallestNumberPossible {
public static void findSmallestNumberPossible( int N, int K) {
if (N > K * 45 ) {
System.out.println( "-1" );
return ;
}
int [] freq = new int [ 10 ];
Arrays.fill(freq, 0 );
StringBuilder res = new StringBuilder( "" );
int sum = 0 ;
for ( int i = 9 ; i >= 0 ; i--) {
while (freq[i] < K && sum + i <= N) {
freq[i]++;
res.insert( 0 , i);
sum += i;
}
}
int zeros = 0 ;
while (zeros < res.length() && res.charAt(zeros) == '0' ) {
zeros++;
}
if (zeros == res.length()) {
System.out.println( "0" );
} else {
System.out.println(res.substring(zeros));
}
}
public static void main(String[] args) {
int N = 25 , K = 3 ;
findSmallestNumberPossible(N, K);
}
}
|
Python3
def find_smallest_number_possible(N, K):
if N > K * 45 :
print ( "-1" )
return
freq = [ 0 ] * 10
res = ""
sum_digits = 0
for i in range ( 9 , - 1 , - 1 ):
while freq[i] < K and sum_digits + i < = N:
freq[i] + = 1
res = str (i) + res
sum_digits + = i
zeros = 0
while zeros < len (res) and res[zeros] = = '0' :
zeros + = 1
if zeros = = len (res):
print ( "0" )
else :
print (res[zeros:])
if __name__ = = "__main__" :
N = 25
K = 3
find_smallest_number_possible(N, K)
|
C#
using System;
public class GFG {
static void FindSmallestNumberPossible( int N, int K)
{
if (N > K * 45) {
Console.WriteLine( "-1" );
return ;
}
int [] freq = new int [10];
string res = "" ;
int sum = 0;
for ( int i = 9; i >= 0; i--) {
while (freq[i] < K && sum + i <= N) {
freq[i]++;
res = i.ToString() + res;
sum += i;
}
}
int zeros = 0;
while (zeros < res.Length && res[zeros] == '0' ) {
zeros++;
}
if (zeros == res.Length) {
Console.WriteLine( "0" );
}
else {
Console.WriteLine(res.Substring(zeros));
}
}
public static void Main( string [] args)
{
int N = 25, K = 3;
FindSmallestNumberPossible(N, K);
}
}
|
Javascript
function findSmallestNumberPossible(N, K) {
if (N > K * 45) {
console.log( "-1" );
return ;
}
let freq = new Array(10).fill(0);
let res = "" ;
let sum = 0;
for (let i = 9; i >= 0; i--) {
while (freq[i] < K && sum + i <= N) {
freq[i]++;
res = i + res;
sum += i;
}
}
let zeros = 0;
while (zeros < res.length && res.charAt(zeros) === '0' ) {
zeros++;
}
if (zeros === res.length) {
console.log( "0" );
} else {
console.log(res.substring(zeros));
}
}
let N = 25, K = 3;
findSmallestNumberPossible(N, K);
|
Time Complexity: The time complexity of this code is O(10K), where K is the maximum frequency of each digit. This is because the loop iterates over the digits from 9 to 0 at most 10 times, and for each digit, the while loop runs at most K times.
Auxiliary Space: The space complexity of this code is O(K), which is the size of the freq array used to store the frequency of each digit. The size of the res string is also O(K) because it can have at most K digits. Therefore, the overall space complexity of the code is O(K).
Last Updated :
22 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...