I wrote a program that returns next bigger number created with the same digits, but it looks like code isn't fast enough to be able to pass the random tests, and gives "Execution Timed Out (16000 ms)" error.
public static String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
public static void getPermutations(String str, int l, int r, List<Long> permutations ) {
if (l == r)
permutations.add(Long.valueOf(str));
else {
for (int i = l; i <= r; i++) {
str = swap(str, l, i);
getPermutations(str, l + 1, r, permutations);
str = swap(str, l, i);
}
}
}
public static long nextBiggerNumber(long n) {
String numberTostring = Long.toString(n);
List<Long> permutations = new ArrayList<>();
getPermutations(numberTostring, 0 ,numberTostring.length() - 1, permutations);
permutations.sort(Comparator.naturalOrder());
for (long number : permutations) {
if (number > n) {
return number;
}
}
return -1;
}
Do you know how to improve this code?