Quick revision
The short answer
Finding the next larger number with the same digits is the next permutation problem, from the math and bits family. Reading from the right, we find the pivot, the first digit that is smaller than the digit after it, swap it with the smallest larger digit to its right, and reverse the digits after the pivot so they are as small as possible; with no pivot there is no answer. It takes O(d) time and O(d) space for d digits.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Count upward and compare sorted digits | O(g x d log d), g the gap | O(d) |
| Build and sort all arrangements | O(d! x d) | O(d! x d) |
| Pivot, swap, reverse | O(d) | O(d) |
What to remember
We found the next larger number with the same digits by changing the shortest possible tail. The pivot is the first digit, read from the right, that is smaller than the digit after it; we swap it with the smallest larger digit to its right and reverse the tail so it is as small as possible, returning -1 when there is no pivot or the result does not fit in an int. That is O(d) time and space. The clue to remember is the next arrangement in order: read from the right for the first break in the descending tail.
1What the question asks, told with six number cards
Imagine six cards on a table, each with one digit printed on it, laid in a row so that they read 534976. You may pick the cards up and lay them down again in any order you like, but you may not add a card or throw one away. Every way of laying them down is a number made from exactly the same digits. Mathematicians call each such ordering a permutation, which simply means an arrangement. Our task is to find, among all the arrangements, the one that is just a little bigger than the one on the table: the next one up.
That sounds as if we must think about hundreds of arrangements, which is what makes the question feel big. It is smaller than it looks. A card on the left counts for far more than a card on the right: the first card of 534976 is worth five hundred thousand, the last only six. So to grow the number as little as possible, we leave the left cards alone and disturb only a few cards at the right end. The whole solution is a careful way of deciding how few cards to pick up.
Let us try it on paper. Pick up only the last card, the 6, and there is nothing to rearrange. Pick up the last two, 7 and 6; they can lie as 76 or 67, and 67 is smaller, so nothing bigger can be made. Pick up the last three, 9, 7 and 6; their biggest arrangement is 976, which is already on the table. Now pick up the last four, 4, 9, 7 and 6. At last there is room to grow, because the 4 can be replaced by a larger card. The answer, as we will see, is 536479.
Top row: the digits of 534976. Bottom row: the digits of the answer, 536479, made from the same six cards.
1The top row is 534976. The bottom row is the answer, 536479: the first two digits stay, the 4 grows to a 6, and the digits after it are laid smallest first.
What to assume
- What is the input?
- We assume a positive Java int.
- What if no larger arrangement exists, as for 4321, whose cards already lie biggest first, or the single digit 7?
- We return -1.
- What if the next arrangement does not fit in an int?
- For 2147483486 it is 2147483648, one more than
Integer.MAX_VALUE, so we return -1 there too. - Can digits repeat, as in 115?
- Yes, and the answer, 151, must be strictly larger. Two more examples to keep in mind: 1234 gives 1243, and 1020 gives 1200.
A careful candidate asks a few questions first. What is the input? We assume a positive Java int. What if no larger arrangement exists, as for 4321, whose cards already lie biggest first, or the single digit 7? We return -1. What if the next arrangement does not fit in an int? For 2147483486 it is 2147483648, one more than Integer.MAX_VALUE, so we return -1 there too. Can digits repeat, as in 115? Yes, and the answer, 151, must be strictly larger. Two more examples to keep in mind: 1234 gives 1243, and 1020 gives 1200.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to spot the pattern when a question asks you to rearrange digits
On a first reading most of us think of the number as a quantity, something to add to, and the first idea is to count upward, n + 1, n + 2, until the digits match. That is natural, and we will try it honestly next. But it treats the question as arithmetic, when the question never asks us to add anything. It asks us to rearrange.
So let us take the clues one at a time. The first is the phrase exactly the same digits. It tells us that the answer is one of the arrangements of the cards we already hold, so we are choosing an order, not computing a value. In code the digits are a short array of characters, and the problem becomes one about the order of an array.
The second clue is the word next, beside the word larger. Imagine every arrangement of 5, 3, 4, 9, 7 and 6 listed from smallest to largest, the way words are listed in a dictionary. Next larger means the entry straight after ours. Any bigger arrangement, such as 976543, would be easy; we want the closest one. When a question asks for the very next item in sorted order, the change should happen as far to the right as possible, because the right end changes the value least.
These clues point to the math and bits family, which collects problems about the digits and bits of numbers, and inside it to a well known method called next permutation. The name says what it does: given one arrangement, it produces the next one in sorted order. The rule to carry to new problems is to read the sequence from the right and find the first item that is smaller than the item after it, because everything to the right of that place is already as large as it can be. C++ ships the same steps as next_permutation.
Two other patterns look similar but do not fit. Backtracking, the pattern for questions that ask for all arrangements, could build every permutation and find ours, but ten cards give 3,628,800 arrangements when we need one. Sorting the digits gives the smallest or largest arrangement, never the next one, although a small sorting step does appear at the end of our answer.
3The honest first attempt, counting upward one number at a time
The honest first attempt, the brute force, does exactly what the question says. Start at n + 1 and test each number in turn by sorting its digits and comparing them with the sorted digits of n. If the two sorted strings are equal, the number uses the same digits, and since we counted upward, it is the smallest such number. Trying the simple thing first is a good habit: it gives an answer we trust and something to measure a better idea against.
To stop when there is no answer, we never count past the largest arrangement, the sorted digits read backwards. For 4321 that limit is 4321 itself, so the loop never runs and we return -1.
Let us count. From 534977 the loop tests 1,503 numbers before reaching 536479, sorting six characters each time. For 218765 the answer is 251678, so it tests 32,913 numbers. Notice that the number of tests has nothing to do with the number of digits; it depends only on the gap between n and the answer.
How big can that gap become? For 1999999999 the next arrangement is 9199999999, so the loop would test more than seven billion numbers. With g for the gap and d for the number of digits, the time is O(g x d log d), read as order g times d log d, where d log d is the cost of one sort. The extra memory, called the space, is only O(d).
So where is the waste? Look at the numbers tested: 534977, 534978, 534979, 534980, and on. Almost all contain digits that n does not have, such as an 8 or a 0, and each still costs a sort. The loop churns the right-hand digits hundreds of times when we could reason once about which digit must change. And the answer keeps the first two digits, 5 and 3, exactly as they were. A good method keeps as many left digits as possible and decides, by thinking rather than trying, how short a tail it must rearrange.
4Getting to pivot, swap and reverse, one observation at a time
Let us start from that thought and take one small step at a time. A tail here means the last few digits of the number. For each tail, from the shortest upward, we ask whether its cards can be rearranged into something larger, exactly as we did on paper in the first section.
When can a tail not be made larger? Look at 976. Its digits fall from left to right, biggest first, so the biggest card already sits in the most valuable place. We call such a tail descending, and a descending tail cannot grow. A tail with even one digit smaller than the digit after it can grow, because swapping those two alone would make it bigger.
So we read from the right for the first digit that is smaller than the digit to its right. In 534976 we compare 7 with 6, then 9 with 7, then 4 with 9, and stop, because 4 is smaller than 9. That 4, at index 2, is called the pivot, the digit the change turns on, and everything to its right is descending. If we reach the left end without a pivot, the number is already the largest arrangement and we return -1.
Now the question a beginner usually asks. The pivot must grow, but which digit should take its place? Why not simply swap the 4 with its neighbour, the 9? Let us try it. That gives 539476, which is larger, but not the next one, because 536479 lies between them. The pivot's place is worth thousands, so it should grow by the smallest amount: we replace the 4 with the smallest digit to its right that is still larger than 4. Of 9, 7 and 6, that is the 6.
Finding that digit is easy. The tail is descending, so if we start at the right end and walk left, the first digit larger than the pivot is the smallest such digit. For 534976 the 6 at the end is already larger than 4, so we stop at once, swap, and get 536974.
We are nearly done. The 6 in the pivot's place already makes the number larger than 534976, whatever follows it, so the digits after it should now be as small as possible, smallest first. After the swap the tail 974 is still descending, because the 4 went where the 6 sat, with larger digits before that spot and no larger ones after it. A descending tail becomes ascending simply by reversing it, so 974 becomes 479 and the number becomes 536479.
Why is this the next number and not merely a larger one? Each step was forced. The pivot is the rightmost place where growth is possible, it grows by the least amount, and then the tail takes its smallest order. No choice was left open, so nothing lies between 534976 and 536479.
The mistake beginners make most often is with repeated digits, because a strict comparison looks tidier. Take 1221, whose answer is 2112. If the swap search loops while d[j] < d[i], it stops at the last 1, swaps a 1 with a 1, and the reverse produces 1122, smaller than where we started. If the pivot search loops while d[i] > d[i + 1], the pivot lands on the second 2, and the swap search walks off the left end of the array. Equal digits must be skipped in both searches.
5Watching pivot, swap and reverse work on 534976
The picture plays the three steps on 534976. Each box is one digit, with its index above it. The marker i shows the pivot search, j the swap search, and l and r the two ends of the reverse, while the panel keeps what we have found. Watch how few digits are touched: the 5 and the 3 never change, just as the paper exercise promised.
Each box is one digit with its index above it. Only the digits from index 2 onwards are ever touched.
- i
- 4
- tail so far
- 6
1The pivot search starts with i at index 4 and compares 7 with the 6 on its right. 7 is not smaller, so this pair is still descending and i moves left.
- i
- 3
- tail so far
- 7 6
2At index 3 we compare 9 with 7. 9 is not smaller either, so the tail 976 is still descending and cannot grow. i moves left again.
- i
- 2
- pivot
- 4
- tail
- 9 7 6
3At index 2 we compare 4 with 9. 4 is smaller, so the loop stops: the 4 is the pivot, and everything to its right, 9 7 6, is descending.
- i
- 2
- j
- 5
- pivot
- 4
- swap digit
- 6
4The swap search starts with j at the right end. d[5] is 6, which is larger than the pivot 4, so the loop stops at once with j = 5.
- i
- 2
- j
- 5
- digits
- 536974
5We swap the pivot with the 6. The number is now 536974, already larger than 534976, and the tail 9 7 4 is still descending.
- l
- 3
- r
- 5
- digits
- 536974
6To make the tail as small as possible we reverse it. l starts just after the pivot, at index 3, and r at the last index, 5.
- l
- 4
- r
- 4
- digits
- 536479
7We swap 9 and 4, then l and r both move to index 4. Now l is not less than r, so the reverse is finished; the middle 7 stays where it is.
- result
- 536479
- fits in int
- yes
8The digits read 536479. It is parsed as a long, it is below
Integer.MAX_VALUE, so the method returns 536479.
Let us read the frames back. The first three are the pivot search: two comparisons find no dip, and the third, 4 against 9, does. The fourth is the swap search, which stops at once because the last digit, 6, already beats the pivot. The fifth is the moment the number grows, to 536974. The sixth and seventh reverse the tail; three digits need only one swap, because the middle digit stays in the middle.
Try 218765 yourself on paper. Reading from the right, the first digit smaller than its neighbour is the 1 at index 1. The rightmost digit larger than 1 is the final 5. Swapping gives 258761, and reversing 8761 gives 1678, so the answer is 251678.
6The complete Java program
Here is the full program. It works on the characters of the number's decimal string, which keeps the three steps readable, and parses the result as a long so that an answer too big for an int can be noticed. main runs the examples, repeated digits, zeros, a single digit and an overflow.
Let us read nextBigger in the order it runs. First we turn the number into a char array, d, so that we can swap digits in place. Comparing chars such as '4' and '9' works, because '0' to '9' are stored in order.
Then comes the pivot search. i starts at d.length - 2, because we compare each digit with the one after it and the last digit has nothing after it. The loop moves i left while d[i] >= d[i + 1], that is, while the tail is still descending. When it stops, either i is -1 and we return -1, or d[i] is the pivot.
Next, j starts at the last index and moves left while d[j] <= d[i]. It cannot run past the pivot, because the digit just after the pivot is larger than it. When it stops, d[j] is the smallest larger digit, and swap(d, i, j) exchanges the two.
The for loop does the reverse. l starts just after the pivot and r at the end, and they swap and walk towards each other until they meet. Finally Long.parseLong turns the digits back into a number, and if it is above Integer.MAX_VALUE we return -1, which is why 2147483486 prints -1.
7How much it costs, and the cases at the edges
Let us count on the example first. The pivot search made three comparisons, the swap search one, and the reverse one swap. Each loop visits at most the d digits once, so the work is at most about 3d steps and the time is O(d). An int has at most ten digits, so this is a handful of steps, against billions for counting upward. The only extra memory is the char array and the string we parse, so the space is O(d).
| Approach | Time | Extra space |
|---|---|---|
| Count upward and compare sorted digits | O(g x d log d), g the gap | O(d) |
| Build and sort all arrangements | O(d! x d) | O(d! x d) |
| Pivot, swap, reverse | O(d) | O(d) |
The edge cases are handled by the code we have read. A number whose digits never rise, such as 4321 or 7, has no pivot, so we return -1. Repeated digits, as in 115 and 1221, are handled by the non-strict comparisons. Zeros inside, as in 1020, are safe because only digits after the pivot move, so a zero never reaches the front. An answer above Integer.MAX_VALUE, as for 2147483486, returns -1. A quick self-check in the interview: the sorted digits of input and output must match, and the output must be larger.
8Follow-up questions
How would you find the next smaller number with the same digits?
We mirror every step. Reading from the right, we look for the first digit that is larger than the digit after it; that is the pivot, and the tail after it is ascending. We swap the pivot with the largest digit to its right that is still smaller than it, then reverse the tail so it becomes descending, its largest arrangement, and the number shrinks as little as possible. If there is no pivot, no smaller arrangement exists. One extra check is needed: the result must not start with 0. For 1023, which is already the smallest arrangement that does not start with 0, the steps would produce 0321, so we return -1.
Can you do it without turning the number into a string?
Yes. We peel digits off the right end with n % 10, which gives the last digit, and n / 10, which removes it, while each new digit is at least as large as the one before it. The first smaller digit is the pivot. The peeled digits sit in a small array, so we pick the swap digit there and rebuild the number with result * 10 + digit, writing the tail in ascending order. The cost is still O(d); the string version is just easier to read.
9Conclusion
We found the next larger number with the same digits by changing the shortest possible tail. The pivot is the first digit, read from the right, that is smaller than the digit after it; we swap it with the smallest larger digit to its right and reverse the tail so it is as small as possible, returning -1 when there is no pivot or the result does not fit in an int. That is O(d) time and space. The clue to remember is the next arrangement in order: read from the right for the first break in the descending tail.
Open with
I take a positive int and return the smallest larger number with the same digits, or minus one if there is none or it overflows an int. Counting upward and comparing sorted digits works, but the gap can be billions.
Then, if they want more
The next larger number should keep as many leading digits as possible, so I want the shortest tail I can rearrange into something larger. This is next permutation. A tail whose digits fall from left to right is already its largest arrangement, so reading from the right I look for the first digit smaller than the digit after it.
That is the pivot. If there is none, the digits are in descending order and I return minus one. Otherwise I swap the pivot with the smallest larger digit to its right, which is the rightmost larger digit because the tail is descending. Then I reverse the tail so it becomes ascending, its smallest arrangement.
For 534976 the pivot is 4, I swap it with 6 to get 536974, and reversing 974 gives 536479. It is O(d) time and space. I use non-strict comparisons so repeated digits work, and I parse the result as a long to catch overflow.
About this answer
- Last updated
- 14 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 19 times in that collection. How it is counted
- Official documentation
- java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Find the next larger number that uses exactly the same digits as a given number.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-next-larger-number-that-uses-exactly-the-same-digits-as-dcb201/