Description
Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1. The result must fit in 32-bit integer.
Examples
Input:
n = 12Output:
21Explanation:
21 is next greater with same digits.
Input:
n = 1234Output:
1243Explanation:
To find the next greater number with same digits, the task requires find the rightmost digit that can be increased. Starting from right: 4 can't be increased, 3 can be swapped with 4 to get 1243, which is the smallest number greater than 1234 using the same digits.
Input:
n = 4321Output:
-1Explanation:
The digits are arranged in descending order (4321), which means this is already the largest possible number that can be formed using these digits. No greater arrangement exists, so returning -1.
Constraints
- •
1 ≤ n ≤ 2^31 - 1