Leetcode 556. Next Greater Element III
Given a positive integer n
, find the smallest integer which has exactly the same digits existing in the integer n
and is greater in value than n
. If no such positive integer exists, return -1
.
Example:
Input: n = 12 Output: 21
Input: n = 21 Output: -1
Q: Can n
contain leading zeros?
A: No, n
will be a positive integer with no leading zeros.
Q: What is the range of n
?
A: The constraint is not explicitly given, but assume it will fit within the bounds of a 32-bit signed integer (1 <= n <= 2^31 - 1
).
To solve the problem, we follow these steps:
i
.i
and swap them.i
to get the smallest lexicographical order.Here are the detailed steps:
n
to a character array arr
for easy manipulation of digits.i
.-1
.arr[i]
and swap them.i + 1
to the end.-1
.class Solution {
public int nextGreaterElement(int n) {
char[] number = Integer.toString(n).toCharArray();
int i = number.length - 2;
// Step 1: Find first decreasing digit
while (i >= 0 && number[i] >= number[i + 1]) {
i--;
}
// If no such element is found, return -1
if (i < 0) return -1;
int j = number.length - 1;
// Step 2: Find the next larger digit to swap with
while (number[j] <= number[i]) {
j--;
}
// Step 3: Swap the elements
swap(number, i, j);
// Step 4: Reverse the digits after index i
reverse(number, i + 1, number.length - 1);
// Convert back to integer and be cautious with overflow
try {
return Integer.parseInt(new String(number));
} catch (NumberFormatException e) {
return -1;
}
}
private void swap(char[] arr, int i, int j) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private void reverse(char[] arr, int start, int end) {
while (start < end) {
swap(arr, start, end);
start++;
end--;
}
}
}
d
is the number of digits in the number n
. This is because we are performing a couple of linear scans (to find the pivot and the swap candidate) and one reverse operation.This approach ensures that we effectively find the next greater permutation with the least lexicographical order in a constrained time frame.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?