Sponsored
Sponsored
This approach uses the concept of finding the next permutation of the digits of the number. We traverse the digits from right to left to find the first digit that is smaller than the digit next to it. Once found, we swap it with the smallest larger digit on its right and then reverse the sequence following the swapped digit.
Time Complexity: O(n log n) (due to sorting in worst case)
Space Complexity: O(1) (in-place swap and conversion)
1function nextGreaterElement(n) {
2 let digits = n.toString().split('');
3 let i = digits.length - 2;
4 while (i >= 0 && digits[i] >= digits[i + 1]) i--;
5 if (i === -1) return -1;
6 let j = digits.length - 1;
7 while (digits[j] <= digits[i]) j--;
8 [digits[i], digits[j]] = [digits[j], digits[i]];
9 let result = parseInt(digits.slice(0, i + 1).concat(digits.slice(i + 1).reverse()).join(''));
10 return result > 2**31 - 1 ? -1 : result;
11}
12
13console.log(nextGreaterElement(12));
The JavaScript solution follows a similar pattern with array manipulations to find the next greater permutation. The method leverages array methods to reverse portions of the sequence and joins arrays to form the final result.
This approach entails understanding mathematical permutation generation principles. First, identify the point where the digits stop increasing when moving left-to-right, then swap it. Finally, regenerate that segment to form the smallest sequential increase.
Time Complexity: O(n^2) (as it checks for minimum swap position for small digits segment)
Space Complexity: O(n) (array storage)
1#include <vector>
#include <algorithm>
int nextGreaterElement(int n) {
std::string digits = std::to_string(n);
int i = digits.length() - 2;
while (i >= 0 && digits[i] >= digits[i + 1]) i--;
if (i < 0) return -1;
int j = i + 1;
while (j + 1 < digits.length() && digits[j + 1] > digits[i]) j++;
std::swap(digits[i], digits[j]);
std::sort(digits.begin() + i + 1, digits.end());
long long result = std::stoll(digits);
return (result > INT_MAX) ? -1 : result;
}
int main() {
int n = 12;
std::cout << nextGreaterElement(n) << std::endl;
return 0;
}
This solution considers creating permutations by sorting sub-sequences post-swap for incremental growth. It checks near-linear progression of larger values.