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 <bits/stdc++.h>
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] < num[len - 1]) {
         firstDigitIndex = i;
         break;
      }
   }
   if (firstDigitIndex == -1) {
      return "-1";
   }
   int secondDigitIndex = -1;
   for (int i = len - 1; i > firstDigitIndex; i--) {
   if (num[i] > num[firstDigitIndex]) {
      if (secondDigitIndex == -1 || num[i] <= num[secondDigitIndex]) {
         secondDigitIndex = i;
         }
      }
   }
   char temp = num[firstDigitIndex];
   num[firstDigitIndex] = num[secondDigitIndex];
   num[secondDigitIndex] = temp;
   return num;
}

int main() {
   string num = "12345";
   cout << "Given number: " << num << endl;
   cout << "Next higher number: " << getNextHigherNumber(num) << endl;
   return 0;
}

Output

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

Given number: 12345
Next higher number: 12354

Updated on: 25-Oct-2021

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements