Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.

Example 1:

Input:
 12

Output:
 21

Example 2:

Input:
 21

Output:
 -1
public class Solution {
    public int nextGreaterElement(int n) {
        char[] array = (n+"").toCharArray();
        if (array.length <= 1) {
           return -1;
        }
        int i = 0;
       // start from the right most and find the first digit that smaller than its next digit
        for(i = array.length - 1; i > 0; i--) {
            if (array[i-1] < array[i]) {
                break;
            }
        }

        // corner case, increasing array from right to left
        if (i == 0) {
            return -1;
        }

        char smallest = array[i - 1];
        int index  = i ;

        // find the smallest number (bigger than x) from i to end 
        for (int j = i + 1; j < array.length; j++) {
            if (array[j] > smallest && array[j] <= array[index]) {
                index = j;
            }
        }

        // swap the smallest and smallest bigger of right side
        char temp = array[index];
        array[index] = array[i - 1];
        array[i - 1] = temp;

        // sort the array index after (i-1) in ascending order
        Arrays.sort(array, i, array.length);

        long result = Long.parseLong(new String(array));
        return (result <= Integer.MAX_VALUE && result > n) ? (int) result : -1;
    }
}

results matching ""

    No results matching ""