Write a program in java to output the next largest number using the same digits if possible or else output the same.


The trick is to look for the digit (say a[i]) which is greater than the digit value at its left (say a[i-1]).

If found then look for the digit (say a[j]) at the right of index ‘i’ which smaller than a[i] but at the same time greater than a[i-i].

Swap a[j] and a[i-1].

Sort all the digits at the right of index ‘i’ (inclusive) in ascending order.

The final outcome will be the nearest greatest integer of the same digits.

next greater number using same digits

Let’s implement the same in Java.


If you have any doubts or suggestions then please comment below.

Leave a Reply

14 − ten =