Find the minimum permutation of A greater than B

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


Input: A = 9236, B = 3125
Output: 3269
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:





// 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;


Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Recommended Posts:

Do your best to show the world what you are capable of

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :