Problem
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
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Here is a similar problem - Arrange Given Number To Form The Biggest Number Possible.
This is also similar code: Next Greater number with given set of digits
Solution
Method 1 - Greedy Approach
Lets look at example 3 - 423862.
- Go through each digit from right to left.
- Find the first digit that is not in descending order. In the example, it’s 3, 423862.
- For all digits after the current digit (862), find the smallest one that is also greater than the current digit, which is 6. Swap it with the current digit. ⇨ 423862
- So the current number is 426832.
- The last step is to sort all digits after the current digit (6) in ascending order, so we get 426238.
Code
|
|
Complexity
- ⏰ Time complexity:
O( log n)
wheren
is number of digits in number. - 🧺 Space complexity:
O(1)