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 -1 if no such number exists
  • Return -1 if 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
Next Permutation: The Dictionary MethodExample: 1234 โ†’ 12431234โ† Pivot: 3 < 4Process:Find rightmost increasing pair (3,4)Find smallest digit > 3 to the right (which is 4)Swap 3 and 4 โ†’ 1243Reverse suffix after position 2 (none needed here)Result:1243Time Complexity: O(n) | Space Complexity: O(n)
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

n
2n
โš  Quadratic Growth
Space Complexity
O(n! ร— n)

Storing all n! permutations, each of length n

n
2n
โš  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
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
86.0K Views
Medium-High Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen