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++
#include <bits/stdc++.h>
using namespace std;
int findSmallestNumber(vector< int >& arr, int n)
{
vector< int > dp(n, numeric_limits< int >::max() - 5);
vector<pair< int , int > > result(n, make_pair(-1, 0));
sort(arr.begin(), arr.end());
queue< int > q;
for ( auto i : arr) {
if (i != 0) {
if (dp[i % n] > 1e9) {
q.push(i % n);
dp[i % n] = 1;
result[i % n] = { -1, i };
}
}
}
while (!q.empty()) {
int u = q.front();
q.pop();
for ( auto i : arr) {
int v = (u * 10 + i) % n;
if (dp[u] + 1 < dp[v]) {
dp[v] = dp[u] + 1;
q.push(v);
result[v] = { u, i };
}
}
}
if (dp[0] > 1e9)
return -1;
else {
vector< int > ans;
int u = 0;
while (u != -1) {
ans.push_back(result[u].second);
u = result[u].first;
}
reverse(ans.begin(), ans.end());
for ( auto i : ans) {
return i;
}
}
}
int main()
{
vector< int > arr = { 5, 2, 3 };
int n = 12;
cout << findSmallestNumber(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int findSmallestNumber(ArrayList<Integer> arr, int n)
{
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 )));
Collections.sort(arr);
ArrayList<Integer> q = new ArrayList<Integer>();
for ( int i : arr) {
if (i != 0 ) {
if (dp.get(i % n) > 1000000000 ) {
q.add(i % n);
dp.set(i % n, 1 );
result.set(i % n, new ArrayList<Integer>(Arrays.asList(- 1 , i)));
}
}
}
while (q.size() != 0 ) {
int u = q.get( 0 );
q.remove( 0 );
for ( int i : arr) {
int v = (u * 10 + i) % n;
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 (dp.get( 0 ) > 1000000000 )
return - 1 ;
else {
ArrayList<Integer> ans = new ArrayList<Integer>();
int u = 0 ;
while (u != - 1 ) {
ans.add(result.get(u).get( 1 ));
u = result.get(u).get( 0 );
}
Collections.reverse(ans);
for ( int i : ans) {
return i;
}
}
return - 1 ;
}
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));
}
}
|
Python3
def findSmallestNumber(arr, n):
dp = [ float ( 'inf' )] * n
result = [( - 1 , 0 )] * n
arr.sort()
q = []
for i in arr:
if i ! = 0 :
if dp[i % n] > 10 * * 9 :
q.append(i % n)
dp[i % n] = 1
result[i % n] = - 1 , i
while len (q) > 0 :
u = q.pop( 0 )
for i in arr:
v = (u * 10 + i) % n
if dp[u] + 1 < dp[v]:
dp[v] = dp[u] + 1
q.append(v)
result[v] = u, i
if dp[ 0 ] > 10 * * 9 :
return - 1
else :
ans = []
u = 0
while u ! = - 1 :
ans.append(result[u][ 1 ])
u = result[u][ 0 ]
ans = ans[:: - 1 ]
for i in ans:
return i
if __name__ = = "__main__" :
arr = [ 5 , 2 , 3 ]
n = 12
print (findSmallestNumber(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int findSmallestNumber(List< int > arr, int n)
{
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});
arr.Sort();
List< int > q = new List< int >();
foreach ( int i in arr) {
if (i != 0) {
if (dp[i % n] > 1000000000) {
q.Add(i % n);
dp[i % n] = 1;
result[i % n] = new [] {-1, i};
}
}
}
while (q.Count != 0) {
int u = q[0];
q.RemoveAt(0);
foreach ( int i in arr) {
int v = (u * 10 + i) % n;
if (dp[u] + 1 < dp[v]) {
dp[v] = dp[u] + 1;
q.Add(v);
result[v] = new [] { u, i };
}
}
}
if (dp[0] > 1000000000)
return -1;
else {
List< int > ans = new List< int >();
int u = 0;
while (u != -1) {
ans.Add(result[u][1]);
u = result[u][0];
}
ans.Reverse();
foreach ( var i in ans) {
return i;
}
}
return -1;
}
public static void Main( string [] args)
{
List< int > arr = new List< int >( new [] { 5, 2, 3 });
int n = 12;
Console.WriteLine(findSmallestNumber(arr, n));
}
}
|
Javascript
let inf = 100000000000
function findSmallestNumber(arr, n){
let dp = new Array(n).fill(inf)
let result = new Array(n)
for ( var i = 0; i < n; i++)
result[i] = [-1, 0]
arr.sort()
let q = []
for ( var i of arr)
{
if (i != 0)
{
if (dp[i % n] > 1000000000)
{
q.push(i % n)
dp[i % n] = 1
result[i % n] = [-1, i]
}
}
}
while (q.length > 0)
{
let u = q.shift()
for ( var i of arr)
{
let v = (u * 10 + i) % n
if (dp[u] + 1 < dp[v])
{
dp[v] = dp[u] + 1
q.push(v)
result[v] = [u, i]
}
}
}
if (dp[0] > 1000000000)
return -1
else
{
let ans = []
let u = 0
while (u != -1)
{
ans.push(result[u][1])
u = result[u][0]
}
ans.reverse()
for ( var i of ans)
{
return i
}
}
}
let arr = [5, 2, 3]
let n = 12
console.log(findSmallestNumber(arr, n))
|
Time Complexity: O(N*N), as we are using nested loops to traverse N*N times. Where N is the number of elements in the array.
Auxiliary Space: O(N), as we are using extra space for dp and queue. Where N is the number of elements in the array.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
13 Oct, 2022
Like Article
Save Article