Leetcode 556. Next Greater Element III
Given a positive integer n
, find the smallest positive 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
n
be very large?
n
will be within the bounds of a standard integer type.n
is always positive?
n
is a positive integer.right to left
ensures the smallest possible change yielding the next greater number).#include <iostream>
#include <string>
#include <algorithm>
int nextGreaterElement(int n) {
std::string num = std::to_string(n);
int len = num.size();
// Step 2: Find first decreasing digit from the right
int i = len - 2;
while (i >= 0 && num[i] >= num[i + 1]) {
i--;
}
// If no such digit is found, return -1
if (i < 0) return -1;
// Step 3: Find the smallest digit on the right of `i` that is larger than num[i]
int j = len - 1;
while (num[j] <= num[i]) {
j--;
}
// Step 4: Swap
std::swap(num[i], num[j]);
// Step 5: Reverse the digits after `i`
std::reverse(num.begin() + i + 1, num.end());
// Convert string back to integer
long result = std::stol(num);
// Check if the result is within the 32-bit integer range
return (result > INT_MAX) ? -1 : static_cast<int>(result);
}
// Test the function
int main() {
int n = 12;
std::cout << "Next greater element of " << n << " is: " << nextGreaterElement(n) << std::endl;
n = 21;
std::cout << "Next greater element of " << n << " is: " << nextGreaterElement(n) << std::endl;
return 0;
}
The time complexity of the above approach is (O(k)), where (k) is the number of digits in the number n
. The key operations such as finding indices and swapping digits happen in constant time, and the sorting operation performed on the suffix is (O(k \log k)), which is manageable for typical input sizes.
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?