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
Next Greater Element III INPUT Number: n = 123 1 2 3 i=0 i=1 i=2 Digits Array: ['1', '2', '3'] Goal: Find smallest number > 123 using same digits Must fit in 32-bit integer Max: 2,147,483,647 ALGORITHM STEPS 1 Find Break Point Scan right-to-left, find i where d[i] < d[i+1] 1 2 3 i=1 (2<3) 2 Find Swap Target Find smallest digit > d[i] from right side 1 2 3 j=2 (3>2) 3 Swap d[i] and d[j] Swap positions 1 and 2 1 3 2 132 4 Reverse Suffix Reverse from i+1 to end (Already sorted here) 1 3 2 = 132 FINAL RESULT Next Greater Element: 1 3 2 Output: 132 Verification: 132 > 123 [OK] Same digits: 1,2,3 [OK] Fits 32-bit [OK] VALID ANSWER Key Insight: The Next Permutation algorithm finds the lexicographically next arrangement. For numbers, this gives the smallest greater value with same digits. The break point identifies where we can make a minimal increase, and reversing the suffix ensures we get the smallest possible arrangement after that point. TutorialsPoint - Next Greater Element III | Next Permutation Algorithm Time Complexity: O(n) | Space Complexity: O(n) where n = number of digits
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
89.2K Views
Medium Frequency
~25 min Avg. Time
1.8K 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