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


Input:  123                                                                                               
Output: 132

Input:  1465
Output: 1546
Next largest number using the same digits

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

If found then look for the digit (say min) at the right of index ‘i’ that is smaller than a[i] but greater than a[i-i].

Swap a[i-1] and min.

Sort all the digits after min in ascending order.

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

import java.util.*; 
public class Main { 
	public static void main(String[] args){ 
	    Scanner in=new Scanner(;
	    //Input a number and convert it into char array.
	    System.out.print("Enter a number: ");
		char a[]; 
		//store length of number in 'n'
		int i, n=a.length; 
		//check from back for a[i-1] < a[i]
		for(i=n-1; i>0; i--){ 
			if(a[i-1] < a[i]) 
		//If 'i' value reaches 0, it means digits are in descending order
		//Hence higher number cannot be formed using the same digits set
		if(i == 0) 
			for(i=0; i<n; i++) 
		    //If found then look for (a[i-1] < min < a[i]) after a[i]
			int min=i;
			for(int j=i+1; j<n; j++) 
			    //if found then copy its index to min
				if (a[j]>a[i-1] && a[j]<a[min]) 
					min = j; 
			//swap a[i-1] and a[min]
			char temp = a[i-1]; 
		    a[i-1] = a[min]; 
		    a[min] = temp; 
		    //sort all after min (i.e. after i inclusive) in ascending order
			Arrays.sort(a, i, n); 
			//output the result
			System.out.print("Next greater number: ");


Enter a number: 1465
Next greater number: 1546

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

Leave a Reply

2 × two =