Given two integers A and B, the task is to find the greatest number ? B that can be formed using all the digits of A.
Examples:
Input: A = 123, B = 222
Output: 213
123, 132 and 213 are the only valid numbers which are ? 222.
213 is the maximum among them.
Input: A = 3921, B = 10000
Output: 9321
Approach: Let’s construct the answer digit by digit starting from the leftmost. We need to build a lexicographically maximal answer so we should choose the greatest digit in each step.
Iterate over all possible digits starting from the greatest. For each digit check if it’s possible to put it in this position. For this, construct minimal suffix (greedily put the lowest digit) and compare the resulting number with B. If it is less than or equal to B then proceed to the next digit.
Below is the implementation of the above approach:
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;
// Function to return the greatest number // not gtreater than B that can be formed // with the digits of A string Permute_Digits(string a, long long b)
{ // To store size of A
int n = a.size();
// To store the required answer
string ans = "" ;
// Traverse from leftmost digit and
// place a smaller digit for every
// position.
for ( int i = 0; i < n; i++) {
// Keep all digits in A
set< char > temp(a.begin(), a.end());
// To avoid leading zeros
if (i == 0)
temp.erase(0);
// For all possible values at ith position from
// largest value to smallest
for ( auto j = temp.rbegin(); j != temp.rend(); ++j) {
// Take largest possible digit
string s1 = ans + *j;
// Keep duplicate of string a
string s2 = a;
// Remove the taken digit from s2
s2.erase(s2.find(*j), 1);
// Sort all the remaining digits of s2
sort(s2.begin(), s2.end());
// Add s2 to current s1
s1 += s2;
// If s1 is less than B then it can be
// included in the answer. Note that
// stoll() converts a string to lomg
// long int.
if (stoll(s1) <= b) {
ans += *j;
// change A to s2
a = s2;
break ;
}
}
}
// Return the required answer
return ans;
} // Driver code int main()
{ string a = "123" ;
int b = 222;
cout << Permute_Digits(a, b);
return 0;
} |
// Java implementation of the approach import java.util.*;
class GFG
{ // Function to return the greatest number
// not gtreater than B that can be formed
// with the digits of A
static String Permute_Digits(String a, int b)
{
// To store size of A
int n = a.length();
// To store the required answer
String ans = "" ;
// Traverse from leftmost digit and
// place a smaller digit for every
// position.
for ( int i = 0 ; i < n; i++) {
// Keep all digits in A
HashSet<Character> temp = new HashSet<Character>();
for ( int x= 0 ;x<a.length();x++){
if (a.charAt(x) != '0' ) temp.add(a.charAt(x));
}
// For all possible values at ith position from
// largest value to smallest
char [] reverse = new char [temp.size()];
int pos = temp.size() - 1 ;
for ( char x : temp)
{
reverse[pos--] = x;
}
for ( int j = 0 ; j < reverse.length; j++) {
// Take largest possible digit
String s1 = ans + reverse[j];
// Keep duplicate of string a
String s2 = "" + a;
// Remove the taken digit from s2
int ind = s2.indexOf(reverse[j]);
if (ind != - 1 )
s2 = s2.substring( 0 , ind) + s2.substring(ind + 1 );
// Sort all the remaining digits of s2
char [] s2arr = s2.toCharArray();
Arrays.sort(s2arr);
s2 = new String(s2arr);
// Add s2 to current s1
s1 += s2;
// If s1 is less than B then it can be
// included in the answer. Note that
// Number() converts a string to Number
if (Integer.valueOf(s1) <= b) {
ans += reverse[j];
// change A to s2
a = s2;
break ;
}
}
}
// Return the required answer
return ans;
}
// Driver code
public static void main(String[] args)
{
String a = "123" ;
int b = 222 ;
System.out.println(Permute_Digits(a, b));
}
} // This code is contributed by phasing17 |
# Python implementation of the approach # Function to return the greatest number # not gtreater than B that can be formed # with the digits of A def permuteDigits(a: str , b: int ) - > str :
# To store size of A
n = len (a)
# To store the required answer
ans = ""
# Traverse from leftmost digit and
# place a smaller digit for every
# position.
for i in range (n):
# Keep all digits in A
temp = set ( list (a))
# To avoid leading zeros
if i = = 0 :
temp.discard( 0 )
# For all possible values at ith position from
# largest value to smallest
for j in reversed ( list (temp)):
# Take largest possible digit
s1 = ans + j
# Keep duplicate of string a
s2 = list (a).copy()
# Remove the taken digit from s2
s2.remove(j)
# Sort all the remaining digits of s2
s2 = ''.join( sorted ( list (s2)))
# Add s2 to current s1
s1 + = s2
# If s1 is less than B then it can be
# included in the answer. Note that
# int() converts a string to integer
if int (s1) < = b:
ans + = j
# change A to s2
a = ''.join( list (s2))
break
# Return the required answer
return ans
# Driver Code if __name__ = = "__main__" :
a = "123"
b = 222
print (permuteDigits(a, b))
# This code is contributed by # sanjeev2552 |
// C# implementation of the approach using System;
using System.Collections.Generic;
class GFG
{ // Function to return the greatest number
// not gtreater than B that can be formed
// with the digits of A
static string Permute_Digits( string a, int b)
{
// To store size of A
int n = a.Length;
// To store the required answer
string ans = "" ;
// Traverse from leftmost digit and
// place a smaller digit for every
// position.
for ( int i = 0; i < n; i++) {
// Keep all digits in A
HashSet< char > temp = new HashSet< char >();
for ( int x=0;x<a.Length;x++){
if (a[x] != '0' ) temp.Add(a[x]);
}
// For all possible values at ith position from
// largest value to smallest
char [] reverse = new char [temp.Count];
temp.CopyTo(reverse);
Array.Reverse(reverse);
for ( int j = 0; j < reverse.Length; j++) {
// Take largest possible digit
string s1 = ans + reverse[j];
// Keep duplicate of string a
string s2 = "" + a;
// Remove the taken digit from s2
if (s2.IndexOf(reverse[j]) != -1)
s2 = s2.Remove(s2.IndexOf(reverse[j]), 1);
// Sort all the remaining digits of s2
char [] s2arr = s2.ToCharArray();
Array.Sort(s2arr);
s2 = new string (s2arr);
// Add s2 to current s1
s1 += s2;
// If s1 is less than B then it can be
// included in the answer. Note that
// Number() converts a string to Number
if (Convert.ToInt32(s1) <= b) {
ans += reverse[j];
// change A to s2
a = s2;
break ;
}
}
}
// Return the required answer
return ans;
}
// Driver code
public static void Main( string [] args)
{
string a = "123" ;
int b = 222;
Console.Write(Permute_Digits(a, b));
}
} // This code is contributed by phasing17 |
<script> // JavaScript implementation of the approach // Function to return the greatest number // not gtreater than B that can be formed // with the digits of A function Permute_Digits(a,b)
{ // To store size of A
let n = a.length;
// To store the required answer
let ans = "" ;
// Traverse from leftmost digit and
// place a smaller digit for every
// position.
for (let i = 0; i < n; i++) {
// Keep all digits in A
let temp = new Set()
for (let i=0;i<n;i++){
if (a[i] !== '0' )temp.add(a[i])
}
// For all possible values at ith position from
// largest value to smallest
let reverse = [...temp].reverse();
for (let j = 0; j < reverse.length; j++) {
// Take largest possible digit
let s1 = ans + reverse[j];
// Keep duplicate of string a
let s2 = a;
// Remove the taken digit from s2
s2 = s2.replace(reverse[j], '' );
// Sort all the remaining digits of s2
s2 = [...s2].sort((a,b)=>a-b).join( "" );
// Add s2 to current s1
s1 += s2;
// If s1 is less than B then it can be
// included in the answer. Note that
// Number() converts a string to Number
if (Number(s1) <= b) {
ans += reverse[j];
// change A to s2
a = s2;
break ;
}
}
}
// Return the required answer
return ans;
} // Driver code let a = "123" ;
let b = 222; document.write(Permute_Digits(a, b)); // This code is contributed by shinjanpatra. </script> |
213
Time Complexity: O(|a|2)
Auxiliary Space: O(|a|)
Optimizations : We can use multiset to keep all occurrences of a digit in set. We can also do binary search using lower_bound() in C++ to quickly find the digit to be placed.