Find largest number smaller than N with same set of digits in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a string N that represents a number. Our task is to find the largest number smaller than N with the same set of digits. 

 Problem Description: we need to find a number using all the digits of the given number which is the largest smaller number than N.

Let’s take an example to understand the problem, 

Input: N = “54314”

Output: 54341

Solution Approach

A simple solution to the problem is by finding the digit of the number which can be moved to find the largest smaller number. Now, the number should be greater than its right success in order to solve the purpose.

For this we will traverse the number form right to left and find the element greater than the last elements.

Then find the greatest element in the right subarray, and replace it with the current element. After the sort the subarray is a descending order. This will be your greatest smaller element.

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

void calcGreatestSmallerElement(string N, int size) {
   
   int i, j;
   for (i = size - 1; i > 0; i--)
      if (N[i] < N[i - 1])
         break;

   if (i == 0) {
      cout << "Previous number is not possible";
      return;
   }

   int x = N[i - 1], greatest = i;
   for (j = i; j < size; j++)
      if (N[j] < x && N[j] > N[greatest])
         greatest = j;

   swap(N[greatest], N[i - 1]);
   sort(N.begin() + i, N.begin() + size, greater<char>());

   cout<<"The Greatest smaller number with same set of digits is "<<N;

   return;
}

int main() {
   
   string N = "654232";
   int size = N.length();
   cout<<"The number is "<<N<<endl;
   calcGreatestSmallerElement(N, size);

   return 0;
}

Output

The number is 654232
The Greatest smaller number with same set of digits is 654223
raja
Published on 25-Jan-2021 04:54:30
Advertisements