Problem Description
Given a positive integer n, determine the smallest integer that has exactly the same digits as n and is greater in value than n. If no such integer exists or the result does not fit in a 32-bit integer, return -1.
Key Insights
- Transform the problem into finding the next permutation of the digit sequence of n.
- Traverse the digits from right to left to find the first digit that is smaller than its next digit (this becomes the pivot).
- If no pivot exists (i.e., the digits are in non-increasing order), then no next greater permutation exists.
- Once the pivot is found, locate the smallest digit greater than the pivot in the suffix.
- Swap the pivot with this digit and reverse the suffix to form the smallest possible number greater than n.
- Finally, check if the result fits within the 32-bit integer range.
Space and Time Complexity
Time Complexity: O(d) where d is the number of digits in n (in worst-case each digit is processed multiple times) Space Complexity: O(d) if considering the space to store the digits; otherwise, O(1) extra space if the digits are processed in place.
Solution
The solution relies on generating the next permutation of the digits of n. Here’s the approach:
- Convert n to a list of characters (digits).
- Starting from the end, find the first digit that is smaller than the digit immediately after it (this is the pivot).
- If no pivot is found, return -1 because n is the largest possible permutation.
- From the end of the list, find the first digit that is greater than the pivot.
- Swap the pivot with that digit.
- Reverse the subarray after the pivot position to get the smallest order.
- Convert the list back to an integer and check the 32-bit integer limitation. Data structures used include an array (or list) to hold the digits, and the algorithm mainly uses two-pointer techniques for reverse operations.