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)
1using System.Linq;
public class Solution {
public int NextGreaterElement(int n) {
char[] digits = n.ToString().ToCharArray();
int i = digits.Length - 2;
while (i >= 0 && digits[i] >= digits[i + 1]) i--;
if (i < 0) return -1;
int j = digits.Length - 1;
while (digits[j] <= digits[i]) j--;
char temp = digits[i];
digits[i] = digits[j];
digits[j] = temp;
Array.Sort(digits, i + 1, digits.Length - i - 1);
try {
return int.Parse(new string(digits));
} catch (OverflowException) {
return -1;
}
}
public static void Main() {
Solution sol = new Solution();
Console.WriteLine(sol.NextGreaterElement(12));
}
}
In C#, the solution optimally executes swaps and sorting in segmented arrays, converting strings back with considerations for possible overflows.