Skip to content
Related Articles

Related Articles

Find the minimum permutation of A greater than B

View Discussion
Improve Article
Save Article
  • Last Updated : 29 Nov, 2021

Given two numbers A and B, the task is to find the arrangement of digits of A such that it is just greater than the given number B, i.e., to find the minimum value permutation of A greater than B. If no such permutation is possible then print -1
Examples: 
 

Input: A = 9236, B = 3125 
Output: 3269 
Explanation: 
The minimum number greater than 3125 formed from the digits of A is 3269. 
Input: A = 1234, B = 9879 
Output: -1 
 

 

Approach: The idea is to use next_permutation() and stol(). The following steps can be followed to compute the answer: 
 

  1. Take both the numbers as String input to make use of next_permutation().
  2. Use stol() to find the long value of B.
  3. Then find the lowest permutation of the number A.
  4. For each permutation of A, check whether the number is greater than B.
  5. If any permutation is greater than the number B then it is one of the possible answers. Select the minimum of all the possible answers.
  6. If no such number is present print -1.

Below is the implementation of the above approach:
 

CPP




// C++ program to find the greater permutation
 
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define inf 999999999999999999
 
// Function to find the greater permutation
ll solve(string a, string b)
{
    ll n, val, ans = inf;
 
    // Convert the string B to long
    val = stol(b);
    n = a.length();
 
    // To find the lowest permutation
    // of the number
    sort(a.begin(), a.end());
 
    // Find if the lowest permutation of A is
    // greater than the given number B
    if (stol(a) > val) {
        ans = min((ll)stol(a), ans);
    }
 
    // Find all the permutations of A
    while (next_permutation(a.begin(),
                            a.end())) {
        if (stol(a) > val) {
            ans = min((ll)stol(a), ans);
        }
    }
 
    // If ans is not the initial value
    // then return ans
    if (ans != inf) {
        return ans;
    }
    // Else return -1
    else {
        return -1;
    }
}
 
// Driver code
int main()
{
    string a, b;
    ll ans;
    a = "9236";
    b = "3145";
    ans = solve(a, b);
    cout << ans;
}

Output: 

3269

 

Time Complexity:O(n * log n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!