Skip to content
Problem 556 · LeetCode 556(opens in a new tab)

Next Greater Element III

MediumMath

You are given a positive whole number n. Rearrange its digits to make a new number that is bigger than n, and among all such numbers pick the smallest one. Every digit of n must be used exactly as often as it appears.

If no arrangement is bigger than n, return -1. Also return -1 when the answer does not fit in a signed 32-bit integer, that is, when it is above 2,147,483,647.

Example 1

Input:  n = 1432
Output: 2134
Why:    the next arrangement of 1, 4, 3, 2 in size order
2 more examples and the constraints

Example 2

Input:  n = 4310
Output: -1
Why:    the digits only fall, so 4310 is already the largest

Example 3

Input:  n = 2147483486
Output: -1
Why:    the next arrangement, 2147483648, is too big for 32 bits

Constraints

  • 1 ≤ n ≤ 2,147,483,647
  • n has at most 10 digits

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every arrangementO(d!·d)
  2. Next permutationO(d)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 10-digit nVerdict
Try every arrangementO(d!·d)
Mention it, then move on
Next permutationO(d)
Best; three short scans

d = number of digits in n, at most 10.

Edge cases to test

  • Single digit. n = 7 has no other arrangement: -1.
  • Digits only fall. 4310 or 999 is already the largest: -1.
  • Repeated digits. 115 gives 151; the scans must use ≤ and ≥ so equal digits are skipped.
  • Answer too big. 2147483486 would become 2147483648: -1.
  • Answer exactly at the limit. 2147483476 gives 2147483647, which still fits.

Common mistakes

  • Sorting the tail instead of reversing it: correct, but O(d log d) and easy to get wrong.
  • Using < instead of ≤ when searching for j, so equal digits get swapped and nothing grows.
  • Building the answer in a 32-bit int, so the overflow check itself overflows.

How to talk through it

  1. 1Clarify. Must every digit be used? What do I return when nothing is bigger, or the answer overflows?
  2. 2Give the brute force. Try every ordering of the digits; say it is O(d!) and why that only works because d ≤ 10.
  3. 3Explain the pivot. A falling tail cannot grow on its own, so the change must happen just left of it.
  4. 4Code the three steps. Find the pivot, swap with the rightmost bigger digit, reverse the tail. Check 32 bits last.
  5. 5Test out loud. Run a falling number, repeated digits, and an answer just above the limit.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?