My Java solution with explanation in comments (3ms)


  • 1
        public int nextGreaterElement(int n) {
    
            char[] cArr = String.valueOf(n).toCharArray();
    
            // i is the leftmost digit that should be exchanged
            int i = cArr.length - 1;
            while (i > 0 && cArr[i] <= cArr[i-1]) i--;
    
            if (i <= 0) return -1;
    
            // j is the digit that should be exchanged with digit at i
            int j = cArr.length - 1;
            while (j >= i && cArr[j] <= cArr[i-1]) j--;
    
            // Exchange the digits at location i and j
            char tmp = cArr[j];
            cArr[j] = cArr[i-1];
            cArr[i-1] = tmp;
    
            // Sort the digits from location i to the end
            Arrays.sort(cArr, i, cArr.length);
    
            try {
               return Integer.parseInt(String.valueOf(cArr));
            } catch (Exception e) {
                // Intentionally left blank
            }
            return -1;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.