Next Greater Element III
Problem statement
Given a positive integer n, rearrange exactly its decimal digits to obtain the smallest integer strictly greater than n. Return that value if it fits a signed 32-bit positive integer; otherwise return -1.
Use every digit exactly as many times as it occurs in n. Do not introduce a leading zero. This practice interpretation follows the named LC556 task in the collected report; the report also questions a reversed number reference.
Function
nextGreaterElement(n: int) → intExamples
Example 1
n = 1243return = 1324The rightmost increase is at digit 2. Swap it with 3, then arrange the remaining digits in increasing order: 1324. Every arrangement with the original prefix 12 is at most 1243, so none lies strictly between 1243 and 1324.
Example 2
n = 31return = -1The digits are already in descending order, so no larger rearrangement exists. Return -1.
Constraints
1 <= n <= 2147483647- The result must fit a signed 32-bit positive integer.