Next Greater Element III - Problem
Imagine you have a positive integer n, and you want to find the very next larger number that can be formed using the exact same digits. This is like rearranging the digits of a number to get the smallest possible number that's still greater than the original.
For example, if you have n = 123, the next greater number using the same digits would be 132. If you have n = 321, there's no way to rearrange the digits to make a larger number, so we return -1.
Key Requirements:
- Use the exact same digits as the input number
- Find the smallest number greater than
n - Return
-1if no such number exists - Return
-1if the result doesn't fit in a 32-bit integer
This problem is essentially about finding the next permutation of digits in lexicographical order!
Input & Output
example_1.py โ Basic Case
$
Input:
n = 12
โบ
Output:
21
๐ก Note:
The digits are [1,2]. The next greater permutation is [2,1], which gives us 21.
example_2.py โ Multiple Digits
$
Input:
n = 123
โบ
Output:
132
๐ก Note:
The digits are [1,2,3]. The next greater permutation is [1,3,2], giving us 132.
example_3.py โ No Solution
$
Input:
n = 321
โบ
Output:
-1
๐ก Note:
The digits [3,2,1] are in descending order, so no greater permutation exists.
Visualization
Tap to expand
Understanding the Visualization
1
Find the Pivot
Scan from right to find the first digit that's smaller than its right neighbor
2
Find Swap Target
From right, find the smallest digit that's larger than the pivot
3
Swap Digits
Exchange the pivot with the target digit
4
Reverse Suffix
Reverse all digits to the right of the original pivot position
Key Takeaway
๐ฏ Key Insight: The next permutation is found by making the smallest possible change from right to left, ensuring we get the lexicographically next arrangement of digits.
Time & Space Complexity
Time Complexity
O(n! ร n)
n! permutations, each taking O(n) time to generate and process
โ Quadratic Growth
Space Complexity
O(n! ร n)
Storing all n! permutations, each of length n
โ Quadratic Space
Constraints
- 1 โค n โค 231 - 1
- The input n is a positive integer
- Return -1 if no valid answer exists or result exceeds 32-bit integer limit
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code