13/07/2021

[Java] Find the next bigger number using same digits

Given a number, find the next number which is bigger than the given one and has the same digits.

Example:

9876 - no next exists

6789 - 6798

8276 - 8627

We first need to convert the number to an array for digit manipulation, we can convert it first to a string and then to the array.
Then, we need to identify (if any) a digit that can be swapped in another place. If it exists, it will be the first digit from the right which is smaller than the next digit.

Example: 9876
has no valid digit since that is already the biggest number that can be made with those digits, notice all digits are in decreasing order

Example: 6789
the first digit smaller than the next from the right is 8, we can use it to make 6798 which is the next bigger number than 6789 using same digits

But simply swapping two digits is not enough, example: 8276, a swap would give 8672 which is bigger but not the next, that would be 8627.
We notice that after the swap, the rest of the digits on the right of the swapped one are sorted in increasing order.

If we do that, we have our answer, this reordering can be done in linear time since in the first portion we stop as soon as we find an element that breaks the increasing sequence right to left.

If there was no such element, we are in the first example where no next number can be built.

Complexity is O(N) for both time and space.

You can check my implementation of smallestBiggerNumWithSameDigits on my Gist along with some tests in SmallestBiggerNumWithSameDigitsJTests.

No comments:

Post a Comment

With great power comes great responsibility