Smallest multiple of N formed using the given set of digits
Last Updated :
19 Dec, 2023
Given a set of digits S and an integer N, the task is to find the smallest positive integer if exists which contains only the digits from S and is a multiple of N. Note that the digits from the set can be used multiple times. Examples:
Input: S[] = {5, 2, 3}, N = 12 Output: 252 We can observe that 252 is formed using {2, 5} and is a multiple of 12 Input: S[] = {1, 3, 5, 7, 9}, N = 2 Output: -1 Multiple of 2 would always be an even number but from the given set of digits even number can't be formed.
A simple approach is to sort the set of digits and then move from smallest to the largest number formed using the given digits. We check each number whether it satisfies the given condition. Implementing it this way would result in exponential time complexity. A better approach is to use Modular Arithmetic. So, we maintain a queue in which we will store the modulus of numbers formed using set of digits with the given number N. Initially in the queue, there would be (single digit number) % N but we can calculate (double digit number) % N by using,
New_mod = (Old_mod * 10 + digit) % N
By using the above expression we can calculate modulus values of multiple digit numbers. This is an application of dynamic programming as we are building our solution from smaller state to larger state. We maintain an another vector to ensure that element to be inserted in queue is already present in the queue or not. It uses hashing to ensure O(1) time complexity. We used another vector of pair which also uses hashing to store the values and its structure is
result[new_mod] = { current_element_of_queue, digit}
This vector would be used to construct the solution:
- Sort the set of digits.
- Initialize two vectors dp and result, with INT_MAX and {-1, 0} respectively.
- Initialize a queue and insert digit % N.
- Do while queue is not empty.
- Remove front value from queue and for each digit in the set, find (formed number) % N using above written expression.
- If we didn't get 0 as a modulus value before queue is empty then smallest positive number does not exist else trace the result vector from the 0th index until we get -1 at any index.
- Put all these values in another vector and reverse it.
- This is our required solution.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the required number
int findSmallestNumber(vector<int>& arr, int n)
{
// Initialize both vectors with their initial values
vector<int> dp(n, numeric_limits<int>::max() - 5);
vector<pair<int, int> > result(n, make_pair(-1, 0));
// Sort the vector of digits
sort(arr.begin(), arr.end());
// Initialize the queue
queue<int> q;
for (auto i : arr) {
if (i != 0) {
// If modulus value is not present
// in the queue
if (dp[i % n] > 1e9) {
// Compute digits modulus given number and
// update the queue and vectors
q.push(i % n);
dp[i % n] = 1;
result[i % n] = { -1, i };
}
}
}
// While queue is not empty
while (!q.empty()) {
// Remove the first element of the queue
int u = q.front();
q.pop();
for (auto i : arr) {
// Compute new modulus values by using old queue
// values and each digit of the set
int v = (u * 10 + i) % n;
// If value is not present in the queue
if (dp[u] + 1 < dp[v]) {
dp[v] = dp[u] + 1;
q.push(v);
result[v] = { u, i };
}
}
}
// If required condition can't be satisfied
if (dp[0] > 1e9)
return -1;
else {
// Initialize new vector
vector<int> ans;
int u = 0;
while (u != -1) {
// Constructing the solution by backtracking
ans.push_back(result[u].second);
u = result[u].first;
}
// Reverse the vector
reverse(ans.begin(), ans.end());
for (auto i : ans) {
// Return the required number
return i;
}
}
}
// Driver code
int main()
{
vector<int> arr = { 5, 2, 3 };
int n = 12;
cout << findSmallestNumber(arr, n);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function to return the required number
static int findSmallestNumber(ArrayList<Integer> arr, int n)
{
// Initialize both vectors with their initial values
ArrayList<Integer> dp = new ArrayList<Integer>();
for (int i = 0; i < n; i++)
dp.add(Integer.MAX_VALUE - 5);
ArrayList <ArrayList<Integer>> result = new ArrayList <ArrayList<Integer>>();
for (int i = 0; i < n; i++)
result.add(new ArrayList<Integer>(Arrays.asList(-1, 0)));
// Sort the vector of digits
Collections.sort(arr);
// Initialize the queue
ArrayList<Integer> q = new ArrayList<Integer>();
for (int i : arr) {
if (i != 0) {
// If modulus value is not present
// in the queue
if (dp.get(i % n) > 1000000000) {
// Compute digits modulus given number and
// update the queue and vectors
q.add(i % n);
dp.set(i % n, 1);
result.set(i % n, new ArrayList<Integer>(Arrays.asList(-1, i)));
}
}
}
// While queue is not empty
while (q.size() != 0) {
// Remove the first element of the queue
int u = q.get(0);
q.remove(0);
for (int i : arr) {
// Compute new modulus values by using old queue
// values and each digit of the set
int v = (u * 10 + i) % n;
// If value is not present in the queue
if (dp.get(u) + 1 < dp.get(v)) {
dp.set(v, dp.get(u) + 1);
q.add(v);
result.set(v, new ArrayList<Integer>(Arrays.asList(u, i)));
}
}
}
// If required condition can't be satisfied
if (dp.get(0) > 1000000000)
return -1;
else {
// Initialize new vector
ArrayList<Integer> ans = new ArrayList<Integer>();
int u = 0;
while (u != -1) {
// Constructing the solution by backtracking
ans.add(result.get(u).get(1));
u = result.get(u).get(0);
}
// Reverse the vector
Collections.reverse(ans);
for (int i : ans) {
// Return the required number
return i;
}
}
// This line should never be reached
return -1;
}
// Driver code
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<Integer>(Arrays.asList(5, 2, 3));
int n = 12;
System.out.println(findSmallestNumber(arr, n));
}
}
// This code is contributed by phasing17
Python3
# Python3 implementation of the approach
# Function to return the required number
def findSmallestNumber(arr, n):
# Initialize both vectors with their initial values
dp = [float('inf')] * n
result = [(-1, 0)] * n
# Sort the vector of digits
arr.sort()
# Initialize the queue
q = []
for i in arr:
if i != 0:
# If modulus value is not
# present in the queue
if dp[i % n] > 10 ** 9:
# Compute digits modulus given number
# and update the queue and vectors
q.append(i % n)
dp[i % n] = 1
result[i % n] = -1, i
# While queue is not empty
while len(q) > 0:
# Remove the first element of the queue
u = q.pop(0)
for i in arr:
# Compute new modulus values by using old
# queue values and each digit of the set
v = (u * 10 + i) % n
# If value is not present in the queue
if dp[u] + 1 < dp[v]:
dp[v] = dp[u] + 1
q.append(v)
result[v] = u, i
# If required condition can't be satisfied
if dp[0] > 10 ** 9:
return -1
else:
# Initialize new vector
ans = []
u = 0
while u != -1:
# Constructing the solution by backtracking
ans.append(result[u][1])
u = result[u][0]
# Reverse the vector
ans = ans[::-1]
for i in ans:
# Return the required number
return i
# Driver code
if __name__ == "__main__":
arr = [5, 2, 3]
n = 12
print(findSmallestNumber(arr, n))
# This code is contributed by Rituraj Jain
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to return the required number
static int findSmallestNumber(List<int> arr, int n)
{
// Initialize both vectors with their initial values
List<int> dp = new List<int>();
for (int i = 0; i < n; i++)
dp.Add(Int32.MaxValue - 5);
List <int[]> result = new List<int[]>();
for (int i = 0; i < n; i++)
result.Add(new [] {-1, 0});
// Sort the vector of digits
arr.Sort();
// Initialize the queue
List<int> q = new List<int>();
foreach (int i in arr) {
if (i != 0) {
// If modulus value is not present
// in the queue
if (dp[i % n] > 1000000000) {
// Compute digits modulus given number and
// update the queue and vectors
q.Add(i % n);
dp[i % n] = 1;
result[i % n] = new [] {-1, i};
}
}
}
// While queue is not empty
while (q.Count != 0) {
// Remove the first element of the queue
int u = q[0];
q.RemoveAt(0);
foreach (int i in arr) {
// Compute new modulus values by using old queue
// values and each digit of the set
int v = (u * 10 + i) % n;
// If value is not present in the queue
if (dp[u] + 1 < dp[v]) {
dp[v] = dp[u] + 1;
q.Add(v);
result[v] = new[] { u, i };
}
}
}
// If required condition can't be satisfied
if (dp[0] > 1000000000)
return -1;
else {
// Initialize new vector
List<int> ans = new List<int>();
int u = 0;
while (u != -1) {
// Constructing the solution by backtracking
ans.Add(result[u][1]);
u = result[u][0];
}
// Reverse the vector
ans.Reverse();
foreach (var i in ans) {
// Return the required number
return i;
}
}
// This line should never be reached
return -1;
}
// Driver code
public static void Main(string[] args)
{
List<int> arr = new List<int>(new[] { 5, 2, 3 });
int n = 12;
Console.WriteLine(findSmallestNumber(arr, n));
}
}
// This code is contributed by phasing17
JavaScript
// JavaScript implementation of the approach
let inf = 100000000000
// Function to return the required number
function findSmallestNumber(arr, n){
// Initialize both vectors with their initial values
let dp = new Array(n).fill(inf)
let result = new Array(n)
for (var i = 0; i < n; i++)
result[i] = [-1, 0]
// Sort the vector of digits
arr.sort()
// Initialize the queue
let q = []
for (var i of arr)
{
if (i != 0)
{
// If modulus value is not
// present in the queue
if (dp[i % n] > 1000000000)
{
// Compute digits modulus given number
// and update the queue and vectors
q.push(i % n)
dp[i % n] = 1
result[i % n] = [-1, i]
}
}
}
// While queue is not empty
while (q.length > 0)
{
// Remove the first element of the queue
let u = q.shift()
for (var i of arr)
{
// Compute new modulus values by using old
// queue values and each digit of the set
let v = (u * 10 + i) % n
// If value is not present in the queue
if (dp[u] + 1 < dp[v])
{
dp[v] = dp[u] + 1
q.push(v)
result[v] = [u, i]
}
}
}
// If required condition can't be satisfied
if (dp[0] > 1000000000)
return -1
else
{
// Initialize new vector
let ans = []
let u = 0
while (u != -1)
{
// Constructing the solution by backtracking
ans.push(result[u][1])
u = result[u][0]
}
// Reverse the vector
ans.reverse()
for (var i of ans)
{
// Return the required number
return i
}
}
}
// Driver code
let arr = [5, 2, 3]
let n = 12
console.log(findSmallestNumber(arr, n))
// This code is contributed by phasing17
Time Complexity: O(N*M), where N is the size of the input ArrayList arr
and M is the number 12 (used in the modulo operation and loop iterations)
Auxiliary Space: O(N), as we are using extra space for dp and queue. Where N is the number of elements in the array.
Similar Reads
Find the smallest binary digit multiple of given number
A decimal number is called a binary digit number if its digits are binary. For example, 102 is not a binary digit number and 101 is.We are given a decimal number N, we need to find the smallest multiple of N which is a binary digit number, Examples: Input : N = 2 Output: 10 Explanation: 10 is a mult
7 min read
Find the smallest number whose digits multiply to a given number n
Given a number 'n', find the smallest number 'p' such that if we multiply all digits of 'p', we get 'n'. The result 'p' should have minimum two digits.Examples: Input: n = 36 Output: p = 49 // Note that 4*9 = 36 and 49 is the smallest such number Input: n = 100 Output: p = 455 // Note that 4*5*5 = 1
8 min read
Smallest multiple of 3 which consists of three given non-zero digits
Given three non-zero digits 0 < A, B, C < 9. The task is to find the smallest number divisible by 3 all of whose digits are in set {A, B, C}. Note: It is not necessary to include all three digits. The result can be A, AA, AB, CCA etc.Examples: Input: A = 2, B = 4, C = 7 Output: 24 24 is the mi
7 min read
Get the kth smallest number using the digits of the given number
Given a non-negative number n and a value k. Find the kth smallest number that can be formed using the digits of the given number n. It is guaranteed that the kth smallest number can be formed. Note that the number could be very large and may not even fit into long long int. Examples: Input : n = 12
11 min read
Smallest even digits number not less than N
Given a number N, we need to write a program to find the smallest number not less than N, which has all digits even. Examples: Input: N = 1345 Output: 2000Explanation: 2000 is the smallest number not less than N, whose all digits are even. Input : N = 2397Output : 2400 Explanation: 2400 is the small
15+ 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
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
First N terms whose sum of digits is a multiple of 10
Given an integer N, the task is to print the first N terms whose sum of digits is a multiple of 10. First few terms of the series are 19, 28, 37, 46, 55, ...Examples: Input: N = 5 Output: 19 28 37 46 55Input: N = 10 Output: 19 28 37 46 55 64 73 82 91 109 Recommended: Please try your approach on {IDE
11 min read
Smallest integer with digit sum M and multiple of N
Given two positive integers N and M, the task is to find the smallest positive integer which is divisible by N and whose digit sum is M. Print -1 if no such integer exists within the range of int. Examples: Input: N = 13, M = 32 Output: 8879 8879 is divisible by 13 and its Sum of digits of 8879 is 8
5 min read
Minimum Possible sum of digits in a positive multiple of N
Given a number N, find the minimum possible sum of digits that can be obtained from a positive Multiple of N. Constraints : 1<=N<=10^5. Examples: Input : N = 6 Output : 3 Explanation: 6*2 = 12, sum of digits is 1+2 = 3. Input : N = 20 Output : 1 20*5 = 100, sum of digits is 1+0+0=1 Approach :
10 min read