Skip to main content

Next Greater Element III - Solution & Explanation

MediumMathTwo PointersString14 min readAsked at: Amazon, Microsoft, Meta +8
Practice this problem

Problem Statement

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 that 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.

 

Example 1:

Input: n = 12
Output: 21

Example 2:

Input: n = 21
Output: -1

 

Constraints:

  • 1 <= n <= 231 - 1

Approach Overview

Problem Overview: Given a positive 32-bit integer n, rearrange its digits to form the next greater integer using exactly the same digits. If no such integer exists, or the result exceeds the 32-bit signed integer range, return -1.

Approach 1: Next Permutation (O(n) time, O(1) space)

This problem is essentially the classic next permutation task applied to the digits of an integer. Convert the number into a digit array or string. Traverse from right to left to find the first index where digits[i] < digits[i+1]. This position marks the pivot where a larger permutation can be formed. Then scan the suffix from the end to locate the smallest digit greater than digits[i], swap them, and reverse the suffix after i to make it the smallest possible arrangement. The algorithm performs a few linear scans over the digits, giving O(n) time with constant extra space. This technique is a common permutation trick when working with digit manipulation problems involving string processing and two pointers style scanning from both ends.

Approach 2: Mathematical Permutation Logic (O(n) time, O(1) space)

This approach derives the same idea directly through mathematical reasoning about digit order. Starting from the least significant digit, identify the first digit that breaks the non-increasing sequence when moving left. That digit is the pivot. The digits to the right are already in descending order, meaning they form the largest permutation of that suffix. To get the next greater number, swap the pivot with the smallest digit in that suffix that is larger than it. After the swap, reorder the suffix into ascending order so the resulting number is the smallest valid integer greater than the original. The process involves simple digit comparisons and swaps, making it efficient and memory-friendly. It highlights the role of permutation ordering in math-based digit manipulation problems.

Recommended for interviews: The Next Permutation approach is the expected solution. Interviewers often look for recognition that the task is identical to the next lexicographical permutation problem. Implementing the pivot search, swap, and suffix reversal in O(n) time demonstrates solid understanding of permutations and in-place array manipulation. The mathematical explanation helps justify why the algorithm works, but the next permutation implementation is typically what candidates code during interviews.

Approach 1: Approach 1: Next Permutation

This approach uses the concept of finding the next permutation of the digits of the number. We traverse the digits from right to left to find the first digit that is smaller than the digit next to it. Once found, we swap it with the smallest larger digit on its right and then reverse the sequence following the swapped digit.

The solution involves converting the integer to a string and manipulating the characters to find the next permutation. We ensure to swap the digits right before reversing the tail end. We also handle possible overflow scenarios by checking if the result exceeds the 32-bit limit.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log n) (due to sorting in worst case)
Space Complexity: O(1) (in-place swap and conversion)

Try this approach in the editor →

Approach 2: Approach 2: Mathematical Permutation Logic

This approach entails understanding mathematical permutation generation principles. First, identify the point where the digits stop increasing when moving left-to-right, then swap it. Finally, regenerate that segment to form the smallest sequential increase.

This method parses digits from the number to locate the next higher permutation swap, initiating a reverse rotation to create the smallest increment. It precisely tracks indices, ensuring accurate results.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^2) (as it checks for minimum swap position for small digits segment)
Space Complexity: O(n) (array storage)

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Approach 1: Next Permutation

Time Complexity: O(n log n) (due to sorting in worst case)
Space Complexity: O(1) (in-place swap and conversion)

Approach 2: Mathematical Permutation Logic

Time Complexity: O(n^2) (as it checks for minimum swap position for small digits segment)
Space Complexity: O(n) (array storage)

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Next PermutationO(n)O(1)General case. Standard algorithm for generating the next lexicographical permutation of digits.
Mathematical Permutation LogicO(n)O(1)Useful for reasoning about digit order and permutation behavior without explicitly referencing the next permutation algorithm.

Video Solution

Next Greater Element - III | Arrays & Strings | leetcode 556 Solution in Hindi • Pepcoding • 19,312 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Next Greater Element III easy or hard?
Next Greater Element III is considered a Medium difficulty problem. The implementation itself is short, but recognizing that the task is equivalent to the next lexicographical permutation problem requires algorithmic insight.
Next Greater Element III Python/Java solution
Python and Java implementations follow the same steps: convert the integer to a character or digit array, apply the next permutation logic, then reconstruct the integer and check the 32-bit limit. The logic remains identical across languages with only syntax differences.
How to solve Next Greater Element III in O(n)?
Scan the digits from right to left to find the first index i where digits[i] < digits[i+1]. Then find the smallest digit greater than digits[i] to its right and swap them. Finally reverse the digits after index i so the suffix becomes the smallest possible order. This sequence of operations produces the next lexicographically greater permutation in linear time.
What is the best approach for Next Greater Element III?
The optimal approach is the Next Permutation algorithm. Convert the integer to a digit array, find the pivot where digits stop increasing from right to left, swap it with the smallest larger digit in the suffix, then reverse the suffix. This produces the smallest number greater than the original using the same digits in O(n) time and O(1) space.
Is Next Greater Element III asked at Google/Amazon/Meta?
Variants of permutation and next greater element problems frequently appear in interviews at companies like Google, Amazon, and Meta. The question tests understanding of permutations, greedy digit manipulation, and in-place array transformations.
What data structure is used in Next Greater Element III?
The algorithm typically converts the integer into an array or string of digits so it can be manipulated like a sequence. Operations involve scanning, swapping elements, and reversing a suffix, which are standard array or string manipulation techniques.
What is the time complexity of Next Greater Element III?
The optimal solution runs in O(n) time where n is the number of digits. The algorithm performs a few linear passes: finding the pivot, locating the next larger digit, and reversing the suffix. Space complexity remains O(1) since all operations are done in place on the digit array.

Ready to solve this problem?

Practice Next Greater Element III with our built-in code editor and test cases.

Practice on FleetCode