Given two numbers A and B, the task is to find the arrangement of digits of A such that it is just greater than the given number B, i.e., to find the minimum value permutation of A greater than B. If no such permutation is possible then print -1
Input: A = 9236, B = 3125
The minimum number greater than 3125 formed from the digits of A is 3269.
Input: A = 1234, B = 9879
- Take both the numbers as String input to make use of next_permutation().
- Use stol() to find the long value of B.
- Then find the lowest permutation of the number A.
- For each permutation of A, check whether the number is greater than B.
- If any permutation is greater than the number B then it is one of the possible answers. Select the minimum of all the possible answers.
- If no such number is present print -1.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.