Given three integers N, A and B, the task is to find a permutation of pairwise distinct numbers from 1 to N that has exactly ‘A’ local minima’s and ‘B’ local maxima’s.
- A local minima is defined as the element which is less than both its neighbours.
- A local maxima is defined as the element which is greater than both its neighbours.
- The first and last element of the entire permutation can never be local minima or maxima.
If no such permutations exist print -1.
Example :
Input: N = 6 , A = 2 , B = 2
Output: 1, 3, 2, 5, 4, 6
Explanation :
2 local minima’s: 2 and 5
2 local maxima’s: 3 and 5Input: N = 5 , A = 2 , B = 2
Output: -1
Naive Approach (Brute Force): In this approach, generate all permutations of 1 to N numbers and check each one individually. Follow the below steps, to solve this problem:
- Generate all the permutations of numbers from 1 to N and store them in an array.
- Traverse through each permutation, if the following permutation has exactly A local minima’s and B local maxima’s, print the permutation.
- If no such permutation exists, then print -1.
Below is the implementation of the above approach :
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to generate next permutation void nextPermutation(vector< int >& nums) { int n = nums.size(), k, l; for (k = n - 2; k >= 0; k--) { if (nums[k] < nums[k + 1]) { break ; } } if (k < 0) { reverse(nums.begin(), nums.end()); } else { for (l = n - 1; l > k; l--) { if (nums[l] > nums[k]) { break ; } } swap(nums[k], nums[l]); reverse(nums.begin() + k + 1, nums.end()); } } // Factorial function int factorial( int n) { return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; } // Function to returns all the permutations of a given array // or vector vector<vector< int > > permute(vector< int >& nums) { vector<vector< int > > permuted; int n = nums.size(); int factn = factorial(n); for ( int i = 0; i < factn; i++) { permuted.push_back(nums); nextPermutation(nums); } return permuted; } // Function to find the permutation of 1 to N numbers // having A minimas and B maximas void findPermutation( int n, int a, int b) { // Generate the array containing one permutation vector< int > nums(n); for ( int i = 0; i < n; i++) { nums[i] = i + 1; } // Generate all the permutations vector<vector< int > > allpermutations = permute(nums); int total = allpermutations.size(); int ansindex = -1; for ( int i = 0; i < total; i++) { // Count local minima and local maximas for each // permutation int minc = 0, maxc = 0; for ( int j = 1; j < n - 1; j++) { if (allpermutations[i][j] > allpermutations[i][j - 1] && allpermutations[i][j] > allpermutations[i][j + 1]) { maxc++; } if (allpermutations[i][j] < allpermutations[i][j - 1] && allpermutations[i][j] < allpermutations[i][j + 1]) { minc++; } } if (minc == a && maxc == b) { // Store the index of a perfect permutation ansindex = i; break ; } } // Print -1 if no such permutation exists if (ansindex == -1) { cout << -1; } else { // Print the perfect permutation if exists for ( int i = 0; i < n; i++) { cout << allpermutations[ansindex][i] << " " ; } } } int main() { int N = 6, A = 2, B = 2; findPermutation(N, A, B); return 0; } |
Java
// Java program for the above approach import java.io.*; import java.util.*; class GFG { // Function to generate next permutation public static void nextPermutation(List<Integer> nums) { int n = nums.size(); int k, l; for (k = n - 2 ; k >= 0 ; k--) { if (nums.get(k) < nums.get(k + 1 )) { break ; } } if (k < 0 ) { Collections.reverse(nums); } else { for (l = n - 1 ; l > k; l--) { if (nums.get(l) > nums.get(k)) { break ; } } Collections.swap(nums, k, l); List<Integer> subList = nums.subList(k + 1 , n); Collections.reverse(subList); } } // Factorial function public static int factorial( int n) { return (n == 1 || n == 0 ) ? 1 : factorial(n - 1 ) * n; } // Function to returns all the permutations of a given // array // or vector public static List<List<Integer> > permute(List<Integer> nums) { List<List<Integer> > permuted = new ArrayList<>(); int n = nums.size(); int factn = factorial(n); for ( int i = 0 ; i < factn; i++) { permuted.add( new ArrayList<>(nums)); nextPermutation(nums); } return permuted; } // Function to find the permutation of 1 to N numbers // having A minimas and B maximas public static void findPermutation( int n, int a, int b) { // Generate the array containing one permutation List<Integer> nums = new ArrayList<>(n); for ( int i = 0 ; i < n; i++) { nums.add(i + 1 ); } // Generate all the permutations List<List<Integer> > allpermutations = permute(nums); int total = allpermutations.size(); int ansindex = - 1 ; for ( int i = 0 ; i < total; i++) { // Count local minima and local maximas for each // permutation int minc = 0 , maxc = 0 ; for ( int j = 1 ; j < n - 1 ; j++) { if (allpermutations.get(i).get(j) > allpermutations.get(i).get(j - 1 ) && allpermutations.get(i).get(j) > allpermutations.get(i).get( j + 1 )) { maxc++; } if (allpermutations.get(i).get(j) < allpermutations.get(i).get(j - 1 ) && allpermutations.get(i).get(j) < allpermutations.get(i).get( j + 1 )) { minc++; } } if (minc == a && maxc == b) { // Store the index of a perfect permutation ansindex = i; break ; } } // Print -1 if no such permutation exists if (ansindex == - 1 ) { System.out.println(- 1 ); } else { // Print the perfect permutation if exists for ( int i = 0 ; i < n; i++) { System.out.print( allpermutations.get(ansindex).get(i) + " " ); } } } public static void main(String[] args) { int N = 6 , A = 2 , B = 2 ; findPermutation(N, A, B); } } // This code is contributed by lokeshmvs21. |
C#
using System; using System.Collections.Generic; class GFG { // Function to generate next permutation static void NextPermutation(List< int > nums) { int n = nums.Count, k, l; for (k = n - 2; k >= 0; k--) { if (nums[k] < nums[k + 1]) { break ; } } if (k < 0) { nums.Reverse(); } else { for (l = n - 1; l > k; l--) { if (nums[l] > nums[k]) { break ; } } int temp = nums[k]; nums[k] = nums[l]; nums[l] = temp; nums.Reverse(k + 1, n - k - 1); } } // Factorial function static int Factorial( int n) { return (n == 1 || n == 0) ? 1 : Factorial(n - 1) * n; } // Function to returns all the permutations of a given // array or list static List<List< int > > Permute(List< int > nums) { List<List< int > > permuted = new List<List< int > >(); int n = nums.Count; int factn = Factorial(n); for ( int i = 0; i < factn; i++) { permuted.Add( new List< int >(nums)); NextPermutation(nums); } return permuted; } // Function to find the permutation of 1 to N numbers // having A minimas and B maximas static void FindPermutation( int n, int a, int b) { // Generate the array containing one permutation List< int > nums = new List< int >(n); for ( int i = 0; i < n; i++) { nums.Add(i + 1); } // Generate all the permutations List<List< int > > allpermutations = Permute(nums); int total = allpermutations.Count; int ansindex = -1; for ( int i = 0; i < total; i++) { // Count local minima and local maximas for each // permutation int minc = 0, maxc = 0; for ( int j = 1; j < n - 1; j++) { if (allpermutations[i][j] > allpermutations[i][j - 1] && allpermutations[i][j] > allpermutations[i][j + 1]) { maxc++; } if (allpermutations[i][j] < allpermutations[i][j - 1] && allpermutations[i][j] < allpermutations[i][j + 1]) { minc++; } } if (minc == a && maxc == b) { // Store the index of a perfect permutation ansindex = i; break ; } } // Print -1 if no such permutation exists if (ansindex == -1) { Console.WriteLine( "-1" ); } else { // Print the perfect permutation if exists for ( int i = 0; i < n; i++) { Console.Write(allpermutations[ansindex][i]); Console.Write( " " ); } } } static public void Main() { int N = 6, A = 2, B = 2; FindPermutation(N, A, B); } } // This code is contributed by akashish__ |
Javascript
// Function to generate next permutation function nextPermutation(nums) { let n = nums.length, k, l; for (k = n - 2; k >= 0; k--) { if (nums[k] < nums[k + 1]) { break ; } } if (k < 0) { nums.reverse(); } else { for (l = n - 1; l > k; l--) { if (nums[l] > nums[k]) { break ; } } let temp = nums[k]; nums[k] = nums[l]; nums[l] = temp; nums.splice(k + 1, n - k - 1, ...nums.slice(k + 1, n).reverse()); } } // Factorial function function factorial(n) { return (n === 1 || n === 0) ? 1 : factorial(n - 1) * n; } // Function to returns all the permutations of a given array function permute(nums) { let permuted = []; let n = nums.length; let factn = factorial(n); for (let i = 0; i < factn; i++) { permuted.push([...nums]); nextPermutation(nums); } return permuted; } // Function to find the permutation of 1 to N numbers // having A minimas and B maximas function findPermutation(n, a, b) { // Generate the array containing one permutation let nums = []; for (let i = 0; i < n; i++) { nums.push(i + 1); } // Generate all the permutations let allpermutations = permute(nums); let total = allpermutations.length; let ansindex = -1; for (let i = 0; i < total; i++) { // Count local minima and local maximas for each // permutation let minc = 0, maxc = 0; for (let j = 1; j < n - 1; j++) { if (allpermutations[i][j] > allpermutations[i][j - 1] && allpermutations[i][j] > allpermutations[i][j + 1]) { maxc++; } if (allpermutations[i][j] < allpermutations[i][j - 1] && allpermutations[i][j] < allpermutations[i][j + 1]) { minc++; } } if (minc == a && maxc == b) { // Store the index of a perfect permutation ansindex = i; break ; } } // Print -1 if no such permutation exists if (ansindex === -1) { console.log(-1); } else { // Print the perfect permutation if exists console.log(allpermutations[ansindex]); } } let N = 6, A = 2, B = 2; findPermutation(N, A, B); // This code is contributed by akashish__ |
Python3
# Python program for the above approach from typing import List , Tuple # Function to generate next permutation def nextPermutation(nums: List [ int ]) - > None : n = len (nums) k, l = n - 2 , n - 1 while k > = 0 : if nums[k] < nums[k + 1 ]: break k - = 1 if k < 0 : nums.reverse() else : while l > k: if nums[l] > nums[k]: break l - = 1 nums[k], nums[l] = nums[l], nums[k] nums[k + 1 :] = reversed (nums[k + 1 :]) # Factorial function def factorial(n: int ) - > int : return 1 if n = = 1 or n = = 0 else factorial(n - 1 ) * n # Function to returns all the permutations of a given array or vector def permute(nums: List [ int ]) - > List [ List [ int ]]: permuted = [] factn = factorial( len (nums)) for i in range (factn): permuted.append(nums.copy()) nextPermutation(nums) return permuted # Function to find the permutation of 1 to N numbers having A minimas and B maximas def findPermutation(n: int , a: int , b: int ) - > Tuple [ int , List [ int ]]: # Generate the array containing one permutation nums = [i + 1 for i in range (n)] # Generate all the permutations allpermutations = permute(nums) ansindex = - 1 for i in range ( len (allpermutations)): # Count local minima and local maximas for each permutation minc, maxc = 0 , 0 for j in range ( 1 , n - 1 ): if allpermutations[i][j] > allpermutations[i][j - 1 ] and allpermutations[i][j] > allpermutations[i][j + 1 ]: maxc + = 1 if allpermutations[i][j] < allpermutations[i][j - 1 ] and allpermutations[i][j] < allpermutations[i][j + 1 ]: minc + = 1 if minc = = a and maxc = = b: # Store the index of a perfect permutation ansindex = i break # Print -1 if no such permutation exists if ansindex = = - 1 : return - 1 ; else : # Print the perfect permutation if exists return allpermutations[ansindex] N, A, B = 6 , 2 , 2 print (findPermutation(N, A, B)) |
1 3 2 5 4 6
Time Complexity: O(N!)
Auxiliary Space: O(N!)
Efficient Approach (Greedy Method):
The above brute force method can be optimized using the Greedy Algorithm. Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. So, break the problem into different usable pieces according to the values of N, A, B. Follow the below steps to solve this problem:
- As the first and the last element of an entire permutation cannot be maxima or minima so the total number of maxima’s and minima’s must be less than or equal to N-2. So if (A + B > N -2), print -1.
- Also, there cannot be two consecutive minima’s or maxima’s. There must be a minima in between two consecutive maxima’s and there must be a maxima in between two consecutive minima’s. So the absolute difference between the total number of minima’s and maxima’s must be less than or equal to 1. So if the absolute difference between A and B exceeds 1 then print -1. We can easily visualize that from the image below.
- After the two corner cases are done, create two variables, minValue to store the minimum value of the permutation, and maxValue to store the maxValue. Now divide the problem into three different cases that are (A > B), (A < B) and (A=B). Now solve each case individually:
- If (A > B): Initialize the minValue as 1 and fill the array with the minValue starting from index 2 for A times. After each insertion increase the minValue by 1 as the values should be distinct. While filling, make sure to leave one index empty after each insertion as it is not possible for two minima’s to reside consecutively. After creating A minima’s fill the rest of the array in increasing order so that no new minima is created.
- If (B > A): Initialize the maxValue as N and fill the array with the maxValue starting from index 2 for B times. After each insertion decrease the maxValue by 1 as the values should be distinct. While filling, make sure to leave one index empty after each insertion as it is not possible for two maxima’s to reside consecutively. After creating B maxima’s fill the rest of the array in decreasing order so that no new maxima is created.
- If (A = B): then initialize two values minValue as 1 and maxValue as N. Fill the first element of the array with minValue and increase the minValue by 1. Then fill the even indices with maxValue and decrease maxValue by 1 and fill the odd indices with minValue and increase the minValue by 1 for A times. Now, fill the rest of the positions in increasing order.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find the permutation of 1 to N numbers // having A minimas and B maximas void findPermutation( int N, int A, int B) { // Create the result array vector< int > arr(N); for ( int i = 0; i < N; i++) { arr[i] = -1; } // If the absolute difference between A and B is // greater 1 or A+B is greater than N-2, then return -1 if ( abs (A - B) > 1 || A + B > N - 2) { cout << -1; } else { if (A > B) { // Initialize maxValue with N int maxValue = N; // Create a maxima's for ( int i = 1; i < N - 1 && A > 0; i += 2) { arr[i] = maxValue; maxValue--; A--; } // Fill other elements in decreasing order for ( int i = 0; i < N; i++) { if (arr[i] == -1) { arr[i] = maxValue; maxValue--; } } } else if (A < B) { // Initialize minValue with 1 int minValue = 1; // Create B minima's for ( int i = 1; i < N - 1 && B > 0; i += 2) { arr[i] = minValue; minValue++; B--; } // Fill other elements in increasing order for ( int i = 0; i < N; i++) { if (arr[i] == -1) { arr[i] = minValue; minValue++; } } } else if (A == B) { // Initialize maxValue with n and minValue with // 1 int minValue = 1, maxValue = N; arr[0] = minValue; minValue++; // Initialize fill equal number of minima and // maximas for ( int i = 1; i < N - 1 && A > 0; i += 2) { arr[i] = maxValue; arr[i + 1] = minValue; A--; maxValue--; minValue++; } // Fill the rest in increasing order for ( int i = 0; i < N; i++) { if (arr[i] == -1) { arr[i] = minValue; minValue++; } } } // Print the output for ( int i = 0; i < N; i++) { cout << arr[i] << " " ; } } cout << endl; } // Driver Code int main() { int N = 6, A = 2, B = 1; findPermutation(N, A, B); return 0; } |
Java
// Java program for the above approach class GFG{ // Function to find the permutation of 1 to N numbers // having A minimas and B maximas static void findPermutation( int N, int A, int B) { // Create the result array int []arr = new int [N]; for ( int i = 0 ; i < N; i++) { arr[i] = - 1 ; } // If the absolute difference between A and B is // greater 1 or A+B is greater than N-2, then return -1 if (Math.abs(A - B) > 1 || A + B > N - 2 ) { System.out.print(- 1 ); } else { if (A > B) { // Initialize maxValue with N int maxValue = N; // Create a maxima's for ( int i = 1 ; i < N - 1 && A > 0 ; i += 2 ) { arr[i] = maxValue; maxValue--; A--; } // Fill other elements in decreasing order for ( int i = 0 ; i < N; i++) { if (arr[i] == - 1 ) { arr[i] = maxValue; maxValue--; } } } else if (A < B) { // Initialize minValue with 1 int minValue = 1 ; // Create B minima's for ( int i = 1 ; i < N - 1 && B > 0 ; i += 2 ) { arr[i] = minValue; minValue++; B--; } // Fill other elements in increasing order for ( int i = 0 ; i < N; i++) { if (arr[i] == - 1 ) { arr[i] = minValue; minValue++; } } } else if (A == B) { // Initialize maxValue with n and minValue with // 1 int minValue = 1 , maxValue = N; arr[ 0 ] = minValue; minValue++; // Initialize fill equal number of minima and // maximas for ( int i = 1 ; i < N - 1 && A > 0 ; i += 2 ) { arr[i] = maxValue; arr[i + 1 ] = minValue; A--; maxValue--; minValue++; } // Fill the rest in increasing order for ( int i = 0 ; i < N; i++) { if (arr[i] == - 1 ) { arr[i] = minValue; minValue++; } } } // Print the output for ( int i = 0 ; i < N; i++) { System.out.print(arr[i]+ " " ); } } System.out.println(); } // Driver Code public static void main(String[] args) { int N = 6 , A = 2 , B = 1 ; findPermutation(N, A, B); } } // This code is contributed by 29AjayKumar |
Python3
# Python 3 program for the above approach # Function to find the permutation of 1 to N numbers # having A minimas and B maximas def findPermutation(N, A, B): # Create the result array arr = [ 0 ] * (N) for i in range (N): arr[i] = - 1 # If the absolute difference between A and B is # greater 1 or A+B is greater than N-2, then return -1 if ( abs (A - B) > 1 or A + B > N - 2 ): print ( - 1 ) else : if (A > B): # Initialize maxValue with N maxValue = N # Create a maxima's i = 1 while i < N - 1 and A > 0 : arr[i] = maxValue maxValue - = 1 A - = 1 i + = 2 # Fill other elements in decreasing order for i in range (N): if (arr[i] = = - 1 ): arr[i] = maxValue maxValue - = 1 elif (A < B): # Initialize minValue with 1 minValue = 1 # Create B minima's i = 1 while i < N - 1 and B > 0 : arr[i] = minValue minValue + = 1 B - = 1 i + = 2 # Fill other elements in increasing order for i in range (N): if (arr[i] = = - 1 ): arr[i] = minValue minValue + = 1 elif (A = = B): # Initialize maxValue with n and minValue with # 1 minValue = 1 maxValue = N arr[ 0 ] = minValue minValue + = 1 # Initialize fill equal number of minima and # maximas i = 1 while i < N - 1 and A > 0 : arr[i] = maxValue arr[i + 1 ] = minValue A - = 1 maxValue - = 1 minValue + = 1 i + = 2 # Fill the rest in increasing order for i in range (N): if (arr[i] = = - 1 ): arr[i] = minValue minValue + = 1 # Print the output for i in range (N): print (arr[i], end = " " ) print () # Driver Code if __name__ = = "__main__" : N = 6 A = 2 B = 1 findPermutation(N, A, B) # This code is contributed by ukasp. |
C#
// C# program for the above approach using System; class GFG{ // Function to find the permutation of 1 to N numbers // having A minimas and B maximas static void findPermutation( int N, int A, int B) { // Create the result array int []arr = new int [N]; for ( int i = 0; i < N; i++) { arr[i] = -1; } // If the absolute difference between A and B is // greater 1 or A+B is greater than N-2, then return -1 if (Math.Abs(A - B) > 1 || A + B > N - 2) { Console.Write(-1); } else { if (A > B) { // Initialize maxValue with N int maxValue = N; // Create a maxima's for ( int i = 1; i < N - 1 && A > 0; i += 2) { arr[i] = maxValue; maxValue--; A--; } // Fill other elements in decreasing order for ( int i = 0; i < N; i++) { if (arr[i] == -1) { arr[i] = maxValue; maxValue--; } } } else if (A < B) { // Initialize minValue with 1 int minValue = 1; // Create B minima's for ( int i = 1; i < N - 1 && B > 0; i += 2) { arr[i] = minValue; minValue++; B--; } // Fill other elements in increasing order for ( int i = 0; i < N; i++) { if (arr[i] == -1) { arr[i] = minValue; minValue++; } } } else if (A == B) { // Initialize maxValue with n and minValue with // 1 int minValue = 1, maxValue = N; arr[0] = minValue; minValue++; // Initialize fill equal number of minima and // maximas for ( int i = 1; i < N - 1 && A > 0; i += 2) { arr[i] = maxValue; arr[i + 1] = minValue; A--; maxValue--; minValue++; } // Fill the rest in increasing order for ( int i = 0; i < N; i++) { if (arr[i] == -1) { arr[i] = minValue; minValue++; } } } // Print the output for ( int i = 0; i < N; i++) { Console.Write(arr[i]+ " " ); } } Console.Write( "\n" ); } // Driver Code public static void Main() { int N = 6, A = 2, B = 1; findPermutation(N, A, B); } } // This code is contributed by Samim Hossain Mondal. |
Javascript
<script> // JavaScript code for the above approach // Function to find the permutation of 1 to N numbers // having A minimas and B maximas function findPermutation(N, A, B) { // Create the result array let arr = new Array(N); for (let i = 0; i < N; i++) { arr[i] = -1; } // If the absolute difference between A and B is // greater 1 or A+B is greater than N-2, then return -1 if (Math.abs(A - B) > 1 || A + B > N - 2) { document.write(-1); } else { if (A > B) { // Initialize maxValue with N let maxValue = N; // Create a maxima's for (let i = 1; i < N - 1 && A > 0; i += 2) { arr[i] = maxValue; maxValue--; A--; } // Fill other elements in decreasing order for (let i = 0; i < N; i++) { if (arr[i] == -1) { arr[i] = maxValue; maxValue--; } } } else if (A < B) { // Initialize minValue with 1 let minValue = 1; // Create B minima's for (let i = 1; i < N - 1 && B > 0; i += 2) { arr[i] = minValue; minValue++; B--; } // Fill other elements in increasing order for (let i = 0; i < N; i++) { if (arr[i] == -1) { arr[i] = minValue; minValue++; } } } else if (A == B) { // Initialize maxValue with n and minValue with // 1 let minValue = 1, maxValue = N; arr[0] = minValue; minValue++; // Initialize fill equal number of minima and // maximas for (let i = 1; i < N - 1 && A > 0; i += 2) { arr[i] = maxValue; arr[i + 1] = minValue; A--; maxValue--; minValue++; } // Fill the rest in increasing order for (let i = 0; i < N; i++) { if (arr[i] == -1) { arr[i] = minValue; minValue++; } } } // Print the output for (let i = 0; i < N; i++) { document.write(arr[i] + " " ); } } document.write( '<br>' ) } // Driver Code let N = 6, A = 2, B = 1; findPermutation(N, A, B); // This code is contributed by Potta Lokesh </script> |
4 6 3 5 2 1
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!