Given a number, how do we find the next greater number with the same digits?

For example if the given number is 123, the next greater number with the same digits is 132.

Similarly for 23876, the output is 26378.

If all the digits of the number are in decreasing order (Eg. 54321), there is no greater number with the same digits.

Let us look at the solution approach. If we simply sort the digits of the number in descending order, we will surely get the greater number with the same digits.

For example if we sort the digits of 123, we get 321.

But we are looking for the least among all greater numbers. In the above example 132 is least among {132, 213, 231, 312, 321}. How to form such a number?

If we swap any two digits a number, it’s value either increases or decreases depends on their order.

For example consider 58762.

- If we swap 8,7 the value (57862) decreases because the bigger digit appears before smaller digit.
- If we swap 5,6 the value (68752) increases because the lesser digit appears before the bigger digit.

So we have to find a pair of digits such that the lesser digit appears before the bigger digit.

We know that as we move from right to left digits in a number, the place value of them increases. So to keep the value as low as possible, we need to find such a pair from right to left.