If you have a few years of experience in Computer Science or research, and you’re interested in sharing that experience with the community, have a look at our **Contribution Guidelines**.

# Find the Next Higher Number

Last modified: September 29, 2020

## 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 , which is smaller than the digit on its right.** For example, If the given number is 12365, then the digit is 3 as 36.

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 is found, **we find the smallest digit on the right side of such that is greater than **. In our example, the digit is 5 since 5<6 and 5>3.

Next, **we swap the digits and in the given number**. In our example, the digits 3 and 5 are swapped in 12365 and we get 12**5**6**3**.

Lastly, **we reverse the sequence of digits after the digit to get the next higher number**. In our example, the sequence 63 is reversed in 12563, and we get 125**36**, 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.

## 4. Time Complexity

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

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

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

Thus, **the overall time complexity of the above algorithm is ()**.

## 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.