Find next greater number with same set of digits in C++


In this problem, we are given an element N. We need to find the next greater number with the same set of digits. We need to find the smallest number with the same digit which is greater than N.

Let’s take an example to understand the problem,

Input

N = "92534"

Output

92543

Solution Approach

A simple solution to the problem to find the next greater element is by the following approach −

  • Traverse the number from least significant bit to most significant bit. And stop when the current element is smaller than the last element.

  • After this search for the smallest element in the remaining array. And find the smallest number and swap it with the number.

  • Then sort the remaining subarray and return the output.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
void findNextGreater(char number[], int n) {
   int i, j;
   for (i = n-1; i > 0; i--)
      if (number[i] > number[i-1])
         break;
   if (i==0) {
      cout<<"Next number is not possible";
      return;
   }
   int x = number[i-1], smallest = i;
   for (j = i+1; j < n; j++)
      if (number[j] > x && number[j] < number[smallest])
         smallest = j;
   char temp = number[smallest];
   number[smallest] = number[i-1];
   number[i-1] = temp;
   sort(number + i, number + n);
   cout<<number;
   return;
}
int main(){
   char number[] = "92534";
   int n = strlen(number);
   cout<<"The next number with same set of digits is ";
   findNextGreater(number, n);
   return 0;
}

Output

The next number with same set of digits is 92543

Updated on: 13-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements