Program to get next integer permutation of a number in C++

C++Server Side ProgrammingProgramming

Suppose we have a number n, we have to find the next bigger permutation of its digits. When n is already in its largest permutation, then rotate it down to the smallest permutation.

So, if the input is like n = 319, then the output will be 391.

To solve this, we will follow these steps −

  • Define a function makeArray(), this will take x,

  • Define an array ret

  • while x is non-zero, do −

    • insert x mod 10 at the end of ret

    • x := x / 10

  • reverse the array ret

  • return ret

  • Define a function combine(), this will take an array v,

  • ret := 0

  • for each element i in v

    • ret := ret * 10

    • ret := ret + i

  • return ret

  • Define a function getIndex(), this will take an array v,

  • ret := -1

  • for initialize i := size of v, when i >= 1, update (decrease i by 1), do −

    • if v[i] > v[i - 1], then −

      • ret := i

      • Come out from the loop

  • if ret is not equal to -1, then −

    • x := v[ret - 1]

    • idx := ret

    • for initialize j := ret + 1, when j < size of v, update (increase j by 1), do −

      • if v[j] < v[idx] and v[j] > x, then −

        • idx := j

    • exchange v[ret - 1] and v[idx]

  • return ret

  • From the main method do the following −

  • Define an array v := makeArray(num)

  • idx := getIndex(v)

  • if idx is same as -1, then −

    • sort the array v

  • Otherwise

    • sort the array v

  • return combine(v)

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   vector<int> makeArray(int x) {
      vector<int> ret;
      while (x) {
         ret.push_back(x % 10);
         x /= 10;
      }
      reverse(ret.begin(), ret.end());
      return ret;
   }
   int combine(vector<int>& v) {
      int ret = 0;
      for (int i : v) {
         ret *= 10;
         ret += i;
      }
      return ret;
   }
   int getIndex(vector& v) {
      int ret = -1;
      for (int i = v.size() - 1; i >= 1; i--) {
         if (v[i] > v[i - 1]) {
            ret = i;
            break;
         }
      }
      if (ret != -1) {
         int x = v[ret - 1];
         int idx = ret;
         for (int j = ret + 1; j < v.size(); j++) {
            if (v[j] < v[idx] && v[j] > x) {
               idx = j;
            }
         }
         swap(v[ret - 1], v[idx]);
      }
      return ret;
   }
   int solve(int num) {
      vector<int> v = makeArray(num);
      int idx = getIndex(v);
      if(idx == -1) {
         sort(v.begin(), v.end());
      }
      else {
         sort(v.begin() + idx, v.end());
      }
      return combine(v);
   }
};
int solve(int n) {
   return (new Solution())->solve(n);
}
int main(){
   int n = 319;
   cout << solve(n);
}

Input

319

Output

391
raja
Updated on 22-Dec-2020 06:36:12

Advertisements