Next Greater Element III
viaLeetCode
Problem Given a positive 32-bit integer n, return the smallest integer that uses exactly the same digits and is strictly greater than n. If none exists within 32-bit range, return -1.
Input / Output
- Input: int n.
- Output: next greater permutation of n's digits, or -1.
Constraints
- n up to 2^31 − 1; answer must also fit in 32 bits.
Example
- n = 12 → 21; n = 21 → -1; n = 12443322 → 13222344.
Expected approach
- Next-permutation on the digit array: scan from the right for the first digit d[i] < d[i+1] (pivot); if none, return -1 (digits non-increasing → largest arrangement). Otherwise swap d[i] with the smallest digit to its right that is larger, then reverse the suffix after i to make it minimal. Check the 32-bit bound before returning. O(len) time, O(1) extra space.
asked …