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)
1#include <iostream>
2#include <string>
3#include <algorithm>
4
5int nextGreaterElement(int n) {
6 std::string digits = std::to_string(n);
7 int i = digits.size() - 2;
8 while (i >= 0 && digits[i] >= digits[i + 1]) i--;
9 if (i < 0) return -1;
10 int j = digits.size() - 1;
11 while (digits[j] <= digits[i]) j--;
12 std::swap(digits[i], digits[j]);
13 std::reverse(digits.begin() + i + 1, digits.end());
14 long long result = std::stoll(digits);
15 return (result > INT_MAX) ? -1 : result;
16}
17
18int main() {
19 int n = 12;
20 std::cout << nextGreaterElement(n) << std::endl;
21 return 0;
22}
In this implementation, we use the C++ STL to manage string manipulations for finding the next permutation. Swapping and reversing the sequence are done using built-in functions, ensuring concise and efficient operations.
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.