Next Greater Element III

Updated on 26 June, 2025
Next Greater Element III header image

Problem Statement

Given a positive integer n, the objective is to determine the smallest integer that comprises exactly the same digits as n but has a greater numerical value. If such an integer does not exist, the function should return -1. An additional condition is that the resultant integer should fit within a standard 32-bit integer range. If a potential solution exists but it exceeds the maximum value that a 32-bit integer can hold (i.e., it doesn't fit within the 32-bit integer range), the function should also return -1. This problem is a classic next permutation problem with the additional constraint of the 32-bit integer limitation.

Examples

Example 1

Input:

n = 12

Output:

21

Example 2

Input:

n = 21

Output:

-1

Constraints

  • 1 <= n <= 231 - 1

Approach and Intuition

To solve this problem, we can utilize the concept of finding the next lexicographical permutation of the digits:

  1. Identify the rightmost digit that is smaller than the digit immediately to its right. This digit is termed as the 'pivot'.
  2. If such a pivot does not exist, this indicates that we are dealing with the highest permutation of these digits, and therefore, a return value of -1 is appropriate.
  3. If a pivot is found, the next step is to locate the smallest digit on the right side of the pivot that is larger than the pivot itself because swapping these will guarantee the next smallest configuration.
  4. Swap the pivot with this chosen digit.
  5. Finally, to ensure that the resulting number is the smallest possible number larger than n, the digits to the right of the original pivot should be reversed (since they were originally in descending order to make the largest number possible with those digits).

By following these steps, the number generated will have the same digits as n and will be the immediate next larger number. After generating this next permutation, a final check is necessary to ensure the result can be represented as a 32-bit integer. If the resulting integer exceeds the 32-bit integer maximum value, then return -1, otherwise, return the new integer.

Key Considerations

  • The approach hinges on finding the correct pivot and then correctly identifying the smallest larger digit to create the next permutation.
  • Ensuring the result fits within a 32-bit integer is critical and must be checked after determining the next permutation.

With these steps and considerations, the problem can be efficiently and effectively addressed within the given constraints.

Solutions

  • Java
java
public class Solution {
    public int findNextGreater(int number) {
        char[] digits = Integer.toString(number).toCharArray();
        int index = digits.length - 2;
        while (index >= 0 && digits[index + 1] <= digits[index]) {
            index--;
        }
        if (index < 0)
            return -1;
        int swapIndex = digits.length - 1;
        while (swapIndex >= 0 && digits[swapIndex] <= digits[index]) {
            swapIndex--;
        }
        exchange(digits, index, swapIndex);
        reversePortion(digits, index + 1);
        try {
            return Integer.parseInt(new String(digits));
        } catch (Exception ex) {
            return -1;
        }
    }
    private void reversePortion(char[] array, int begin) {
        int left = begin, right = array.length - 1;
        while (left < right) {
            exchange(array, left, right);
            left++;
            right--;
        }
    }
    private void exchange(char[] array, int x, int y) {
        char t = array[x];
        array[x] = array[y];
        array[y] = t;
    }
}

The Java solution provided investigates a method to find the next greater number formed by the digits of a given integer, a common type of challenge in numerical manipulation problems. Here's a summary of how the solution works:

  • Convert the integer into a character array of its digits for simpler manipulation.
  • Start from the second last digit, traverse backwards to identify the first digit (index) which violates the increasing order from the behind.
  • If no such digit is found (meaning the digits are sorted in descending order from left to right), return -1 as no greater number can be formed.
  • Locate the smallest digit on the right side of digits[index] that is larger than digits[index] to swap with. This ensures the next number is the smallest possible greater number.
  • Swap the identified digits.
  • Finally, reverse the digits following the index to get the smallest lexicographic order possible for the remaining digits to ensure the resultant number is the next immediate greater number.
  • Convert the character array back to an integer and return, while handling any potential overflow errors with returning -1.

This efficient algorithm revolves around the manipulation of digit positions and order within the number to achieve the desired result. It employs utility methods like reversing portions of arrays and swapping elements which are crucial for achieving the correct number form. This approach, while straightforward in logic, requires careful handling of indices and conditions to function correctly, particularly in edge cases like dealing with the largest possible number of a set of digits.

Comments

No comments yet.