Search

# TCS Codevita | Exchange Digits

In this blog, we will discuss the TCS Codevita 2019 problem.

Before running through the solution will recommend you to try it by yourself first.

Problem Description:

Compute the nearest larger number by interchanging 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.

Constraints:

1 <=a, b <=10000000

Input Format:

2 numbers, a and b, separated by space.

Output:

A single number, greater than b.

If not possible, print -1.

Explanation:

Example 1:

Input:

`459 500`

Output:

`549`

Example 2:

Input:

`645757 457765`

Output:

`465577`

Example 3:

Input:

`5964 9984`

Output:

`-1`

Implementation using C++:

```#include <bits/stdc++.h>
using namespace std;
int main()
{
string a, b;
cin >> a >> b;
sort(a.begin(), a.end());
string temp = a;
int check = 1;
while(stoi(temp) <= stoi(b))
{
//see below for explanation
bool temp1 = next_permutation(a.begin(), a.end());
temp = a;
if(!temp1)
{
check = 0;
break;
}
}
if(check)
cout << stoi(a) << endl;
else
cout << "-1\n";

return 0;
}```

**You might be wondering what is stoi and next_permutation.

• The stoi() function takes a string as an argument and returns its value

• stoi("3.5248") is 3

• stoi("15245 programmerdoor") is 15245

• And it works only on C++11 or above

• next_permutation returns true if the function could rearrange the object as a lexicographically greater permutation.

• Otherwise, the function returns false to indicate that the arrangement is not greater than the previous

Happy Coding!

Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.

See All