Next Greater Element III (LeetCode 556): Solution and Explanation

Medium
Math
Two Pointers
String

Given a positive integer n, return the smallest integer greater than n that uses exactly the same digits, or -1 if none exists or it exceeds 2^31 - 1.

Intuition

To make a number just slightly larger, change it as far to the right as possible. A change at a more significant position always moves the number further.

Read the digits from the right. As long as they do not increase, the suffix you have seen is already arranged in its largest possible order, so no rearrangement of it alone can make the number bigger.

The first digit that breaks this pattern, the pivot, is the rightmost digit that can grow. Replace it with the smallest larger digit from the suffix, which gives the smallest possible increase at that position.

After the swap, the suffix is still in descending order. Reversing it puts it in ascending order, the smallest arrangement, so the result is the very next number. The final answer must also fit in a 32-bit signed integer.

Approach: Next permutation of the digits

  1. Write n as a list of digits.
  2. Find the largest index i with digits[i] < digits[i + 1]. If there is none, return -1.
  3. Find the largest index j with digits[j] > digits[i] and swap the two digits.
  4. Reverse digits[i + 1:].
  5. Convert back to a number and return it if it is at most 2^31 - 1, otherwise -1.

Step-by-step example

n = 12
  1. digits = [1, 2]. Start with i = 0 and compare 1 with 2.
  2. 1 < 2, so index 0 is the pivot.
  3. Scanning from the right, 2 is the first digit greater than 1, so j = 1. Swap them: [2, 1].
  4. The tail after the pivot is a single digit, so reversing changes nothing.
  5. 21 is at most 2^31 - 1, so the answer is 21.

Code: Python, Java, C++

1class Solution:
2    def nextGreaterElement(self, n: int) -> int:
3        digits = list(str(n))
4        i = len(digits) - 2
5        while i >= 0 and digits[i] >= digits[i + 1]:
6            i -= 1
7        if i < 0:
8            return -1
9        j = len(digits) - 1
10        while digits[j] <= digits[i]:
11            j -= 1
12        digits[i], digits[j] = digits[j], digits[i]
13        digits[i + 1:] = reversed(digits[i + 1:])
14        result = int("".join(digits))
15        return result if result < 2 ** 31 else -1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(d)

Each of the scans, the swap and the reversal touch each of the d digits at most once, and d is at most 10.

Space

O(d)

The digits are stored in a list or character array.

Other approaches

Try every permutation (time O(d! * d), space O(d))

Generate all arrangements of the digits and keep the smallest one greater than n. With 10 digits that is up to 3.6 million permutations, which is far too slow compared with the linear scan.

Sort the tail instead of reversing (time O(d log d), space O(d))

After the swap, sort the suffix ascending. It works but costs O(d log d); reversing is enough because the suffix is already in descending order.

Common mistakes

  • Building the result in a 32-bit int. The rearranged number can exceed 2^31 - 1 even though n fits, so build it in a 64-bit type before comparing.
  • Using > instead of >= when scanning for the pivot. Equal neighbours belong to the non-increasing tail.
  • Picking the first digit larger than the pivot from the left of the tail instead of the right. The tail is descending, so the rightmost larger digit is the smallest one.
  • Forgetting to reverse the tail, which gives a larger number than the true next one.

Frequently asked questions

Why is reversing the tail enough, without sorting?

Before the swap the tail is non-increasing. The swap puts the pivot's old digit where the smallest larger digit was, and that keeps the tail non-increasing. A non-increasing sequence reversed is non-decreasing, which is sorted.

When is the answer -1?

When the digits never rise from left to right, such as 21 or 4321, there is no larger arrangement. It is also -1 when the next arrangement is larger than 2147483647, such as for n = 2147483486.

How is this related to the Next Permutation problem?

It is the same algorithm applied to the digits of n, plus the conversion back to a number and the 32-bit check.