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
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:Â
Â
- Take both the numbers as String input to make use of next_permutation().
- Use stol() to find the long value of B.
- Then find the lowest permutation of the number A.
- For each permutation of A, check whether the number is greater than B.
- 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.
- 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 permutationll 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 codeint main(){Â Â Â Â string a, b;Â Â Â Â ll ans;Â Â Â Â a = "9236";Â Â Â Â b = "3145";Â Â Â Â ans = solve(a, b);Â Â Â Â cout << ans;} |
Java
// Java program to find the greater permutationimport java.util.*;Â
class GFG {Â
    private static ArrayList<String> _permutations        = new ArrayList<String>();Â
    static long inf = 99999999;Â
    private static void GetPer(char[] list)    {        int x = list.length - 1;        GetPer(list, 0, x);    }Â
    private static void GetPer(char[] list, int k, int m)    {        if (k == m) {            _permutations.add(new String(list));        }        else            for (int i = k; i <= m; i++) {                char temp = list[k];                list[k] = list[i];                list[i] = temp;Â
                GetPer(list, k + 1, m);Â
                temp = list[k];                list[k] = list[i];                list[i] = temp;            }    }Â
    // Function to find the greater permutation    static long solve(String a, String b)    {        long n, val, ans = inf;Â
        // Convert the string B to long        val = Integer.valueOf(b);        n = a.length();Â
        // To find the lowest permutation        // of the number        char[] a1 = a.toCharArray();        Arrays.sort(a1);        a = new String(a1);Â
        // Find if the lowest permutation of A is        // greater than the given number B        if (Integer.valueOf(a) > val) {            ans = Math.min(Integer.valueOf(a), ans);        }Â
        GetPer(a.toCharArray());        // Find all the permutations of AÂ
        for (String permut : _permutations) {            if (Integer.valueOf(permut) > val) {                ans = Math.min(Integer.valueOf(permut),                               ans);            }        }Â
        // If ans is not the initial value        // then return ans        if (ans != inf) {            return ans;        }        // Else return -1        else {            return -1;        }    }Â
    // Driver code    public static void main(String[] args)    {        String a, b;        long ans;        a = "9236";        b = "3145";        ans = solve(a, b);        System.out.println(Long.valueOf(ans));    }}Â
// This code is contributed by phasing17 |
Python3
# Python program to find the greater permutationfrom itertools import *Â
inf = 9999999999999Â
# Function to find the greater permutationdef solve(a, b):Â Â Â Â a = list(a)Â Â Â Â ans = inf;Â
    # Convert the string B to long    val = int(b);    n = len(a);Â
    # To find the lowest permutation    # of the number    a.sort()Â
    # Find if the lowest permutation of A is    # greater than the given number B    if (int("".join(a)) > val) :        ans = min(int(a), ans);     Â
    # Find all the permutations of A    flag = False;    permuts = list(permutations(a))    for permut in permuts:        curr = int("".join(permut))                 if (curr > val) :            ans = min(curr, ans);Â
    # If ans is not the initial value    # then return ans    if (ans != inf):        return ans;         # Else return -1    else:        return -1;     # Driver codea = "9236";b = "3145";ans = solve(a, b);print(ans)Â
# This code is contributed by phasing17 |
C#
// C# program to find the greater permutationÂ
using System;using System.Collections.Generic;Â
class GFG {    private static List<string> _permutations        = new List<string>();Â
    static long inf = 99999999999999;Â
    private static void Swap(ref char a, ref char b)    {        if (a == b)            return;Â
        a ^= b;        b ^= a;        a ^= b;    }Â
    private static void GetPer(char[] list)    {        int x = list.Length - 1;        GetPer(list, 0, x);    }Â
    private static void GetPer(char[] list, int k, int m)    {        if (k == m) {            _permutations.Add(new string(list));        }        else            for (int i = k; i <= m; i++) {                Swap(ref list[k], ref list[i]);                GetPer(list, k + 1, m);                Swap(ref list[k], ref list[i]);            }    }Â
    // Function to find the greater permutation    static long solve(string a, string b)    {        long n, val, ans = inf;Â
        // Convert the string B to long        val = Convert.ToInt64(b);        n = a.Length;Â
        // To find the lowest permutation        // of the number        char[] a1 = a.ToCharArray();        Array.Sort(a1);        a = new string(a1);Â
        // Find if the lowest permutation of A is        // greater than the given number B        if (Convert.ToInt64(a) > val) {            ans = Math.Min(Convert.ToInt64(a), ans);        }Â
        GetPer(a.ToCharArray());        // Find all the permutations of AÂ
        foreach(string permut in _permutations)        {            if (Convert.ToInt64(permut) > val) {                ans = Math.Min(Convert.ToInt64(permut),                               ans);            }        }Â
        // If ans is not the initial value        // then return ans        if (ans != inf) {            return ans;        }        // Else return -1        else {            return -1;        }    }Â
    // Driver code    public static void Main(string[] args)    {        string a, b;        long ans;        a = "9236";        b = "3145";        ans = solve(a, b);        Console.WriteLine(ans);    }}Â
// This code is contributed by phasing17 |
Javascript
// JS program to find the greater permutationÂ
let inf = 9999999999999Â
var nextPermutation = function(N) {Â Â Â Â const swap = (i, j) =>Â Â Â Â Â Â Â Â [N[i],N[j]] = [N[j],N[i]]Â
    let len = N.length - 1, i    for (i = len - 1; N[i] >= N[i+1];) i--    let j = i + 1, k = len    while (j < k) swap(j++,k--)    if (i >= 0) {        for (j = i + 1; N[i] >= N[j];) j++        swap(i,j)    }};Â
// Function to find the greater permutationfunction solve(a, b){Â Â Â Â a = a.split("")Â
    let n, val, ans = inf;Â
    // Convert the string B to long    val = parseInt(b);    n = a.length;Â
    // To find the lowest permutation    // of the number    a.sort()Â
    // Find if the lowest permutation of A is    // greater than the given number B    if (parseInt(a) > val) {        ans = Math.min(parseInt(a), ans);    }Â
    // Find all the permutations of A    a = a.map(function(item) {    return parseInt(item);});Â
    x = [...a];    x.reverse();         let flag = false;    while (true)    {        nextPermutation(a);                 let curr = parseInt(a.join(""))                 if (curr > val) {            ans = Math.min(curr, ans);        }                          if (flag)            break;                     if (a.join("") == x.join(""))            flag = true;    }Â
    // If ans is not the initial value    // then return ans    if (ans != inf) {        return ans;    }    // Else return -1    else {        return -1;    }}Â
// Driver codelet a, b;let ans;a = "9236";b = "3145";ans = solve(a, b);console.log(ans)Â
// This code is contributed by phasing17 |
Output:Â
3269
Â
Time Complexity:O(n * log n)
Space Complexity: O(1) as no extra space has been taken.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



