Find next greater number with same set of digits
Pattern: Next permutation and rearrangement
Next permutation on the digits of a number. Find the first digit from the right that is smaller than its neighbour, swap it with the smallest bigger digit after it, and reverse the rest. If the digits never rise, there is no answer.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
You are given a positive number as a string of digits. Return the smallest number that uses exactly the same digits and
is greater than it, also as a string. If no such number exists, return "-1". For example, "218765" gives
"251678", "1234" gives "1243", and "4321" gives "-1".
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name
nextGreater and the "-1" answer are this guide's own. A string is used so very long numbers work too.
Think first
- How is this the same as Next Permutation?
- When does a number have no bigger rearrangement of its digits?
- Why does changing the rightmost possible digit give the smallest bigger number?
Hints
Brute force, and why it fails
Try every arrangement of the digits and keep the smallest one that is bigger: O(n! × n). This guide does that on small tests to check the answers. The next-permutation steps take O(n).
The key insight
Comparing equal-length numbers is comparing digit by digit from the left, which is dictionary order. So "next greater number with the same digits" is exactly "next permutation", except that wrapping around is not allowed.
Dry run
number = 534976. From the right, 6, 7 and 9 rise. Then 4 is smaller than 9, so i = 2.
The plan
i = n - 2
while i >= 0 and d[i] >= d[i + 1]: i = i - 1
if i < 0: return "-1"
j = n - 1
while d[j] <= d[i]: j = j - 1
swap d[i], d[j]
reverse d from i + 1 to n - 1
return d as a string
Complexity
- Time
O(n)- Space
O(n)
Here n is the number of digits. The scans and the reversal are O(n). Java and Python copy the string into an array
of digits; C++ can change its own copy.
Edge cases
- One digit, such as
"7":"-1". - Digits only falling or all equal, such as
"4321"or"111":"-1". - Zeros, such as
"1099":"1909". A leading zero never appears, because the answer is bigger than the input. - Repeats, such as
"1112":"1121".
I've built my logic, show the code
Java
class Solution {
public String nextGreater(String number) {
char[] d = number.toCharArray();
int n = d.length;
int i = n - 2;
while (i >= 0 && d[i] >= d[i + 1]) i--; // first digit, from the right, smaller than its neighbour
if (i < 0) return "-1"; // digits never rise: this is already the largest
int j = n - 1;
while (d[j] <= d[i]) j--; // smallest digit on the right bigger than d[i]
char t = d[i]; d[i] = d[j]; d[j] = t;
for (int l = i + 1, r = n - 1; l < r; l++, r--) { t = d[l]; d[l] = d[r]; d[r] = t; }
return new String(d);
}
}C++
class Solution {
public:
string nextGreater(string number) {
int n = static_cast<int>(number.size());
int i = n - 2;
while (i >= 0 && number[i] >= number[i + 1]) i--; // first digit, from the right, smaller than its neighbour
if (i < 0) return "-1"; // digits never rise: this is already the largest
int j = n - 1;
while (number[j] <= number[i]) j--; // smallest digit on the right bigger than number[i]
swap(number[i], number[j]);
reverse(number.begin() + i + 1, number.end());
return number;
}
};Python
class Solution:
def nextGreater(self, number: str) -> str:
d = list(number)
i = len(d) - 2
while i >= 0 and d[i] >= d[i + 1]: # first digit, from the right, smaller than its neighbour
i -= 1
if i < 0:
return "-1" # digits never rise: this is already the largest
j = len(d) - 1
while d[j] <= d[i]: # smallest digit on the right bigger than d[i]
j -= 1
d[i], d[j] = d[j], d[i]
d[i + 1:] = reversed(d[i + 1:])
return "".join(d)Common mistakes
- Wrapping around to the smallest arrangement as Next Permutation does, instead of returning
"-1". - Converting the string to an integer type, which overflows for long numbers.
- Comparing digits as
>instead of>=, which breaks numbers with repeated digits.