Array ( [0] => [1] => questions [2] => Basic [3] => Exchange-Of-Digits ) Codevita Previous Questions | Exchange Of Digits | THE INQUISITIVE





Exchange Of Digits

LEVEL:Beginner

Description

Compute the nearest larger number by interchanging its digits updated.Given 2 numbers a and b find the smallest number greater than b by interchanging the digits of a and if not possible print -1.

Input Format

2 numbers a and b, separated by space.
Constraints:
1 <= a,b <= 10000000

Output Format

A single number greater than b.
If not possible, print -1


Example 1:

Input
459 500
Output
549
Example 2:

Input
645757 457765
Output
465577
Example 3:

Input
459 500
Output
549

oops

Login to see Discussion




Approach

Find all the permutations for the first number, sort the permutations and initialize the flag value as 0. Iterate through each permutation and compare it with second number, if the permutation is greater than the second number change the flag value to 1. At last, is the flag value is 1 print the number and if flag is 0 print '-1'.


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution