Next Greater Element III - Problem
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.
Note: 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.
Input & Output
Example 1 — Basic Next Permutation
$
Input:
n = 123
›
Output:
132
💡 Note:
The digits are [1,2,3]. The next greater permutation is [1,3,2], which forms 132.
Example 2 — No Greater Permutation
$
Input:
n = 321
›
Output:
-1
💡 Note:
The digits are [3,2,1] in descending order. No rearrangement can create a larger number.
Example 3 — Larger Number
$
Input:
n = 12443322
›
Output:
13222344
💡 Note:
Find rightmost ascending pair (2<4), swap with next larger digit, then arrange remaining digits in ascending order.
Constraints
- 1 ≤ n ≤ 231 - 1
- n is a positive integer
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given number n with specific digit arrangement
2
Process
Find next lexicographically greater permutation of digits
3
Output
Return the next greater number or -1 if impossible
Key Takeaway
🎯 Key Insight: Use next permutation algorithm to efficiently find the lexicographically next arrangement of digits
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code