Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integernand is greater in value thann. If no such positive integer exists, return -1.
Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.
Example 1:
Input: n = 12
Output: 21
Example 2:
Input: n = 21
Output: -1
Constraints:
1 <= n <= 231 - 1
Solutions
Solution 1
Thinking
We need the next greater integer that is a permutation of \(n\)'s digits. That is exactly the next-permutation algorithm.
Find the rightmost descent \(i\), then the rightmost \(j\) that is larger than \(cs[i]\), swap, and reverse the suffix into increasing order. No descent means \(n\) is already maximal. Overflow past \(32\)-bit also yields \(-1\).