Next Greater Element III

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
class Solution {
    public int nextGreaterElement(int n) {
        String number = Integer.toString(n);
        char[] str = number.toCharArray();
        boolean anyChange = false;
        for (int i = str.length - 2; i >= 0; i--) {
            if (str[i] < str[i + 1]) {
                // Finding element just greater than str[i] in str[i+1...]
                int j = i + 1;
                while (j < str.length && str[j] > str[i])
                    j++;
                j--;
                // Now swap digits at i & j
                char t = str[i];
                str[i] = str[j];
                str[j] = t;
                // Now reverse the part str[i+1...]
                int p1 = i + 1, p2 = str.length - 1;
                while (p1 < p2) {
                    char temp = str[p1];
                    str[p1] = str[p2];
                    str[p2] = temp;
                    p1++;
                    p2--;
                }
                anyChange = true;
                break;
            }
        }
        if (!anyChange)
            return -1;
        else {
            String num = new String(str);
            return (Long.parseLong(num) > Integer.MAX_VALUE ? -1 : Integer.parseInt(num));
        }
    }
}

Last updated