Skip to content
Related Articles

Related Articles

Improve Article
Smallest number whose sum of digits is N and every digit occurring at most K times
  • Last Updated : 10 Jun, 2021

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++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the smallest number
// whose sum of digits is N and each
// digit occurring at most K times
void findSmallestNumberPossible(int N, int K)
{
    // Maximum sum possible using
    // each digit at most K times
    if (N > 45 * K) {
        cout << "-1";
        return;
    }
 
    // Append smallest number into
    // the resultant string
    string res = "";
    int count = 0;
 
    // Iterate over the range [9, 1]
    for (int i = 9; i >= 1;) {
 
        // If the count of the digit
        // is K, then update count and
        // check for the next digit
        if (count == K) {
            i--;
            count = 0;
        }
 
        // If N is greater than
        // current digit
        if (N > i) {
 
            // Subtract i from N
            N -= i;
 
            // Insert i as a digit
            res += (char)48 + i;
        }
        else {
 
            // Insert remaining N
            // as a digit
            res += (char)N + 48;
            N = 0;
            break;
        }
 
        // Increment count
        count++;
    }
 
    // Reverse the string
    reverse(res.begin(),
            res.end());
 
    // Print the answer
    cout << res;
}
 
// Driver Code
int main()
{
    int N = 25, K = 3;
 
    // Function Call
    findSmallestNumberPossible(N, K);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to find the smallest number
// whose sum of digits is N and each
// digit occurring at most K times
static void findSmallestNumberPossible(int N, int K)
{
     
    // Maximum sum possible using
    // each digit at most K times
    if (N > 45 * K)
    {
        System.out.print("-1");
        return;
    }
 
    // Append smallest number into
    // the resultant string
    StringBuilder res = new StringBuilder();
    int count = 0;
 
    // Iterate over the range [9, 1]
    for(int i = 9; i >= 1😉
    {
         
        // If the count of the digit
        // is K, then update count and
        // check for the next digit
        if (count == K)
        {
            i--;
            count = 0;
        }
 
        // If N is greater than
        // current digit
        if (N > i)
        {
             
            // Subtract i from N
            N -= i;
 
            // Insert i as a digit
            res.append((char)('0' + i));
        }
        else
        {
             
            // Insert remaining N
            // as a digit
            res.append((char)('0' + N));
            N = 0;
            break;
        }
 
        // Increment count
        count++;
    }
 
    // Reverse the string
    res.reverse();
 
    // Print the answer
    System.out.print(res.toString());
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 25, K = 3;
 
    // Function Call
    findSmallestNumberPossible(N, K);
}
}
 
// This code is contributed by jithin

Python3




# Python3 program for the above approach
 
# Function to find the smallest number
# whose sum of digits is N and each
# digit occurring at most K times
def findSmallestNumberPossible(N, K) :
 
    # Maximum sum possible using
    # each digit at most K times
    if (N > 45 * K) :
        print("-1", endl = "");
        return;
 
    # Append smallest number into
    # the resultant string
    res = "";
    count = 0;
 
    # Iterate over the range [9, 1]
    i = 9;   
    while i >= 1 :
 
        # If the count of the digit
        # is K, then update count and
        # check for the next digit
        if (count == K) :
            i -= 1;
            count = 0;
 
        # If N is greater than
        # current digit
        if (N > i) :
 
            # Subtract i from N
            N -= i;
 
            # Insert i as a digit
            res += chr(48 + i);
         
        else :
 
            # Insert remaining N
            # as a digit
            res += chr(N + 48);
            N = 0;
            break;
 
        # Increment count
        count += 1;
 
    # Reverse the string
    res = res[::-1]
 
    # Print the answer
    print(res, end = "");
 
# Driver Code
if __name__ == "__main__" :
 
    N = 25; K = 3;
 
    # Function Call
    findSmallestNumberPossible(N, K);
     
    # This code is contributed by AnkThon

C#




// C# program to implement
// the above approach 
using System;
class GFG
{
  
// Function to find the smallest number
// whose sum of digits is N and each
// digit occurring at most K times
static void findSmallestNumberPossible(int N, int K)
{
      
    // Maximum sum possible using
    // each digit at most K times
    if (N > 45 * K)
    {
        Console.Write("-1");
        return;
    }
  
    // Append smallest number into
    // the resultant string
    string res = "" ;
    int count = 0;
  
    // Iterate over the range [9, 1]
    for (int i = 9; i >= 1;)
    {
  
        // If the count of the digit
        // is K, then update count and
        // check for the next digit
        if (count == K)
        {
            i--;
            count = 0;
        }
  
        // If N is greater than
        // current digit
        if (N > i)
        {
  
            // Subtract i from N
            N -= i;
  
            // Insert i as a digit
            res += (char)('0' + i);
        }
        else
        {
  
            // Insert remaining N
            // as a digit
            res += (char)('0' + N);
            N = 0;
            break;
        }
  
        // Increment count
        count++;
    }
     
     // Reverse the string
     string ans = "";
     for (int i = res.Length - 1; i >= 0; i--)
     {
         ans += res[i] + "";
          
     }
   
     // Print the answer
     Console.WriteLine(ans);
}
  
// Driver Code
public static void Main()
{
    int N = 25, K = 3;
  
    // Function Call
    findSmallestNumberPossible(N, K);
}
}
 
// This code is contributed by susmitakundugoaldanga

Javascript




<script>
 
      // JavaScript program to implement
      // the above approach
       
      // Function to find the smallest number
      // whose sum of digits is N and each
      // digit occurring at most K times
      function findSmallestNumberPossible(N, K) {
        // Maximum sum possible using
        // each digit at most K times
        if (N > 45 * K) {
          document.write("-1");
          return;
        }
 
        // Append smallest number into
        // the resultant string
        var res = "";
        var count = 0;
 
        // Iterate over the range [9, 1]
        for (var i = 9; i >= 1; ) {
          // If the count of the digit
          // is K, then update count and
          // check for the next digit
          if (count === K) {
            i--;
            count = 0;
          }
 
          // If N is greater than
          // current digit
          if (N > i) {
            // Subtract i from N
            N -= i;
 
            // Insert i as a digit
            res += String.fromCharCode("0".charCodeAt(0) + i);
          } else {
            // Insert remaining N
            // as a digit
            res += String.fromCharCode("0".charCodeAt(0) + N);
            N = 0;
            break;
          }
 
          // Increment count
          count++;
        }
 
        // Reverse the string
        var ans = "";
        for (var i = res.length - 1; i >= 0; i--) {
          ans += res[i] + "";
        }
 
        // Print the answer
        document.write(ans);
      }
 
      // Driver Code
      var N = 25,
        K = 3;
 
      // Function Call
      findSmallestNumberPossible(N, K);
       
</script>
Output: 
799

 

Time Complexity: O(log10N)
Auxiliary Space: O(1)

 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :