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 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)