Next Greater Element III

Given a positive integer n, find the smallest integer that has exactly the same digits as n and is greater in value than n. If no such positive integer exists, return -1.

Note that the returned integer should fit in a 32-bit integer. If there is a valid answer but it does not fit in a 32-bit integer, return -1.

Example 1
Inputn = 12
Output21
The smallest integer greater than 12 using exactly the same digits is 21.
Example 2
Inputn = 21
Output-1
There is no integer greater than 21 using exactly the same digits.

Constraints

  • 1 <= n <= 2^31 - 1

Asked at 13 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate