Next higher number using atmost one swap operation in C++

Given a number n, swap any two digits of the number so that the resulting number is greater than the number n. If it's not possible then print -1. Let's see an example.

Input

12345

Output

12354

We have swapped the digits 4 and 5. And we got the higher number with one swap.

Algorithm

  • It's not possible to form the number if the digits of the number are in decreasing order.

  • Find the index of the digit from the right of the number which is less than the last digit.

  • Find the index of the digit which is greater than the previous digit and less than all digits.

  • Swap two digits and return the new number.

  • Return the new number.

Implementation

Following is the implementation of the above algorithm in C++

#include 
using namespace std;
string getNextHigherNumber(string num) {
   int len = num.size();
   int firstDigitIndex = -1;
   for (int i = len - 2; i >= 0; i--) {
      if (num[i]  firstDigitIndex; i--) {
   if (num[i] > num[firstDigitIndex]) {
      if (secondDigitIndex == -1 || num[i] 

Output

If you run the above code, then you will get the following result.

Given number: 12345
Next higher number: 12354
Updated on: 2021-10-25T03:51:21+05:30

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements