1. Introduction

In this article, we’re going to learn an algorithm to find the next higher number than a given non-negative number using the same set of digits.

In the case where the given number is already the highest possible number we can make with the given set of digits, the algorithm should return the given number itself.

2. Illustration

Let’s first understand the solution approach.

At first, we traverse the given number from the rightmost digit to find the first digit \bm{D}, which is smaller than the digit on its right. For example, If the given number is 12365, then the digit D is 3 as 3<6.

In the case, when all the digits are higher than the digit on their right, such as in 4321, we return the given number itself as it is the highest possible number with the given set of digits.

Once the digit D is found, we find the smallest digit \bm{S} on the right side of D such that S is greater than \bm{D}. In our example, the digit S is 5 since 5<6 and 5>3.

Next, we swap the digits \bm{S} and \bm{D} in the given number. In our example, the digits 3 and 5 are swapped in 12365 and we get 12563.

Lastly, we reverse the sequence of digits after the digit \bm{S} to get the next higher number. In our example, the sequence 63 is reversed in 12563, and we get 12536, which is the next higher number than the given number 12365.

3. Algorithm

Let’s take a look at the pseudocode of the above-discussed algorithm:

algorithm findNextHigherNumber(str, n):
    // INPUT
    //   str = The string of the given number
    //   n = The length of the string
    // OUTPUT
    //   str = The string of the next higher number

    for i <- n - 1 to 1:
        if str[i] > str[i - 1]:
            break

    if str[i] > str[i - 1]:
        D <- str[i - 1]
        S <- str[i]
        for j <- i + 1 to n - 1:
            if str[j] > D and str[j] < S:
                S <- str[j]
        
        Swap the digits S and D
        Reverse the sequence of digits after the digit S
        return str
    else:
        return str

4. Time Complexity

Let’s assume that n denotes the number of digits of the given number.

Then, each of the first and the second steps of the algorithm takes O(n) time to find the required digits using a linear search.

The third step consumes O(1) time to perform the swap operation. The fourth step takes O(n) time to reverse the sequence of digits.

Thus, the overall time complexity of the above algorithm is \textbf{O}(\textbf{n}).

5. Conclusion

In this article, we’ve first learned an algorithm to find the next higher number than a given non-negative number using the same set of digits. Next, we analyzed the time complexity of the discussed algorithm.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.