Given a positive integer N, you can do the following operation at most once
a) Swap two digits of the integer N.
You need to determine the largest integer you can get by performing the above operation at most once.
The first line of input contains an integer ‘T’ representing the number of test cases.
The first line of each test case contains one integer ‘N’ denoting the number.
Output Format:
For each test case, print output one integer ‘X’, where ‘X’ is the largest integer you can get.
Print the output of each test case in a separate line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^9
Time limit: 1 sec
2
4589
99538
9584
99835
For the first test case, swap the first digit with the last digit, So, return 9584.
For the second test case, swap the third digit with the last digit. So, return 99835.
2
4321
18
4321
81
For the first test case, the number given is biggest among all possible answers, So, return 4321.
For the second test case, swap the first digit with the last digit. So, return 81.
Can you think of changing one digit at a time and check all the possible combinations?
The intuition here is that if there is a larger digit that is present later then swap these digits. It is optimal to swap the first such digit with the larger digit present after this digit position. The idea is to try to swap each digit with every other digit and then take the maximum number out of all numbers formed after swapping digits.
The algorithm is as follows :
O(logN * logN), where N is the given number.
Here we are iterating over all the pairs of digits of N which is of the order logN * logN. So, the overall time complexity is O(logN * logN).
O(1)
Since we are using constant extra space.