556. Next Greater Element III
Problem description:
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:
1 | Input: n = 12 |
Example 2:
1 | Input: n = 21 |
Constraints:
1 <= n <= 231 - 1
Solution:
Imagine n = 234157641
.
Our goal is to find next number with the same digits, which is greater than given one and which is the smallest one. It makes sense to try to take our number as close to original one as possible.
Let us try to do it: can it start from 2....
, yes, for example 24...
. Can it start with 2341...
? Yes, it can be 23417...
. Can it start with 23415...
? No, it can not, and the reason, that the rest what we have 7641
already biggest number given digits 7, 6, 4, 1
.
So, we can see now, how our algorithm should work:
- Start from the end and look for increasing pattern, it our case
7641
. - If it happen, that all number has increasing pattern, there is no bigger number with the same digits, so we can return
1
. - Now, we need to find the first digit in our ending, which is less or equal to
digits[i-1]
: we have ending5 7641
and we are looking for the next number with the same digits. What can go instead of5
: it is6
! Let us change these two digits, so we have6 7541
now. Finally, we need to reverse last ditits to get6 1457
as our ending.
1 | class Solution: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: