GeeksforGeeks App
Open App
Browser
Continue

# Find total number of Permutations such that every element becomes an Extrema

Given an array arr[] of size N  non-negative integers, the task is to find the total number of permutations of arr[] such that each element in the array is either strictly greater or smaller than all the elements before it i.e., arr[i] = min(arr[1], arr[2], …, arr[i – 1]) or arr[i] = max(arr[1], arr[2], …, arr[i – 1]).

Examples:

Input: arr[] = {3, 6, 9}, N = 3
Output: 4
Explanation: The array arr[] can be constructed in 4 ways: {3, 6, 9}, {6, 3, 9}, {6, 9, 3}, and {9, 6, 3} where each element is either smaller or greater from the left side.

Input: arr[] = {7, 8}, N = 2
Output: 2
Explanation: The array arr[] can be constructed in 4 ways: {7, 8}, {8, 7} where each element is either smaller or greater from the left side.

Approach: The problem can be solved based on the following idea:

Iterate over each element of all the arrays and check if that element is an extremum, by maintaining two variables that track the min and max encountered so far. Count the number of arrays where the condition is satisfied.

Follow the below steps to implement the idea:

• Find each permutation of the given array.
• For each permutation, Initialise mins and maxs with the greatest and smallest number respectively.
• Iterate over the array and update mins and maxs at each index.
• If the current element is not equal to mins and maxs return False. Otherwise, Return True.
• If True, Count it as a valid permutation.

This approach can be implemented as follows:

## C++

 `// C++ code for the above approach``#include ``using` `namespace` `std;` `// This function checks if a given``// permutation is valid``bool` `isValid(vector<``int``> A)``{``  ``// Initializing the min and max values``  ``int` `mins = *max_element(A.begin(), A.end()) + 1;``  ``int` `maxs = -1;``  ` `  ``// Iterating over the array``  ``for` `(``int` `i = 0; i < A.size(); i++)``  ``{``    ` `    ``// Updating the min and max``    ``mins = min(mins, A[i]);``    ``maxs = max(maxs, A[i]);` `    ``// If ith element is neither min``    ``// nor max, then the array is invalid``    ``if` `(A[i] != mins && A[i] != maxs)``      ``return` `false``;``  ``}``  ``return` `true``;``}` `// This function counts the total number``// of valid permutations``int` `countTotalValidPermutations(vector<``int``> S)``{``  ``set > distinctPermutations;``  ``sort(S.begin(), S.end());``  ``do` `{``    ``distinctPermutations.insert(S);``  ``} ``while` `(next_permutation(S.begin(), S.end()));`   `  ``int` `count = 0;``  ``for` `(vector<``int``> A : distinctPermutations)``    ``if` `(isValid(A))``      ``count++;` `  ``return` `count;``}` `int` `main()``{``  ``vector<``int``> S1 = { 3, 6, 9 };``  ``cout << countTotalValidPermutations(S1) << endl;` `  ``vector<``int``> S2 = { 7, 8 };``  ``cout << countTotalValidPermutations(S2) << endl;` `  ``vector<``int``> S3 = { 2, 1, 3, 1 };``  ``cout << countTotalValidPermutations(S3) << endl;` `  ``return` `0;``}`

## Java

 `// Java code for the above approach``import` `java.util.Arrays;``import` `java.util.Collections;``import` `java.util.HashSet;``import` `java.util.Set;``import` `java.util.Vector;` `// This function checks if a given``// permutation is valid` `public` `class` `Main {``    ``public` `static` `boolean` `isValid(Vector A)``    ``{``        ``// Initializing the min and max values``        ``int` `mins = Collections.max(A) + ``1``;``        ``;``        ``int` `maxs = -``1``;``        ``// Iterating over the array``        ``for` `(``int` `i = ``0``; i < A.size(); i++) {``            ``// Updating the min and max``            ``mins = Math.min(mins, A.get(i));``            ``maxs = Math.max(maxs, A.get(i));` `            ``// If ith element is neither min``            ``// nor max, then the array is invalid``            ``if` `(A.get(i) != mins && A.get(i) != maxs)``                ``return` `false``;``        ``}``        ``return` `true``;``    ``}` `    ``// This function counts the total number``    ``// of valid permutations` `    ``public` `static` `int``    ``countTotalValidPermutations(Vector S)``    ``{``        ``Set > distinctPermutations``            ``= ``new` `HashSet<>();``        ``Collections.sort(S);``        ``do` `{``            ``distinctPermutations.add(``new` `Vector<>(S));``        ``} ``while` `(nextPermutation(S));` `        ``int` `count = ``0``;``        ``for` `(Vector A : distinctPermutations)``            ``if` `(isValid(A))``                ``count++;` `        ``return` `count;``    ``}` `    ``public` `static` `boolean` `nextPermutation(Vector S)``    ``{``        ``int` `i = S.size() - ``2``;``        ``while` `(i >= ``0` `&& S.get(i) >= S.get(i + ``1``))``            ``i--;``        ``if` `(i == -``1``)``            ``return` `false``;` `        ``int` `j = S.size() - ``1``;``        ``while` `(S.get(j) <= S.get(i))``            ``j--;` `        ``int` `temp = S.get(i);``        ``S.set(i, S.get(j));``        ``S.set(j, temp);` `        ``int` `left = i + ``1``;``        ``int` `right = S.size() - ``1``;``        ``while` `(left < right) {``            ``temp = S.get(left);``            ``S.set(left, S.get(right));``            ``S.set(right, temp);``            ``left++;``            ``right--;``        ``}``        ``return` `true``;``    ``}` `    ``public` `static` `void` `main(String[] args)``    ``{``        ``Vector S1``            ``= ``new` `Vector<>(Arrays.asList(``3``, ``6``, ``9``));``        ``System.out.println(countTotalValidPermutations(S1));` `        ``Vector S2``            ``= ``new` `Vector<>(Arrays.asList(``7``, ``8``));``        ``System.out.println(countTotalValidPermutations(S2));` `        ``Vector S3``            ``= ``new` `Vector<>(Arrays.asList(``2``, ``1``, ``3``, ``1``));``        ``System.out.println(countTotalValidPermutations(S3));``    ``}``}` `// This code is contributed by rutikbhosale`

## Python3

 `# Python code for the above approach``from` `itertools ``import` `permutations` `# This function checks if a given``# permutation is valid`  `def` `is_valid(A):` `    ``# Initializing the min and max values``    ``mins ``=` `max``(A) ``+` `1``    ``maxs ``=` `-``1` `    ``# Iterating over the array``    ``for` `i ``in` `range``(``len``(A)):` `        ``# Updating the min and max``        ``mins ``=` `min``(mins, A[i])``        ``maxs ``=` `max``(maxs, A[i])` `        ``# If ith element is neither min``        ``# nor max, then the array is invalid``        ``if` `A[i] !``=` `mins ``and` `A[i] !``=` `maxs:``            ``return` `False``    ``return` `True` `# This function counts the total number``# of valid permutations`  `def` `count_total_valid_permutations(S):` `    ``# Getting the total number of``    ``# distinct permutations``    ``distinct_permutations ``=` `set``(permutations(S))` `    ``# Counting the number of distinct``    ``# permutations that are valid``    ``return` `len``([A ``for` `A ``in` `distinct_permutations ``if` `is_valid(A)])`  `# Driver Code` `# Input 1``S1 ``=` `[``3``, ``6``, ``9``]` `# Function call``print``(count_total_valid_permutations(S1))` `# Input 2``S2 ``=` `[``7``, ``8``]` `# Function call``print``(count_total_valid_permutations(S2))` `# Input 3``S3 ``=` `[``2``, ``1``, ``3``, ``1``]` `# Function call``print``(count_total_valid_permutations(S3))`

## C#

 `// C# code for the above approach` `using` `System;``using` `System.Collections.Generic;``using` `System.Linq;` `class` `GFG{``    ``// This function checks if a given permutation is valid``    ``static` `bool` `IsValid(List<``int``> A)``    ``{``        ``// Initializing the min and max values``        ``int` `mins = A.Max() + 1;``        ``int` `maxs = -1;` `        ``// Iterating over the array``        ``for` `(``int` `i = 0; i < A.Count; i++)``        ``{``            ``// Updating the min and max``            ``mins = Math.Min(mins, A[i]);``            ``maxs = Math.Max(maxs, A[i]);` `            ``// If ith element is neither min``            ``// nor max, then the array is invalid``            ``if` `(A[i] != mins && A[i] != maxs)``                ``return` `false``;``        ``}``        ``return` `true``;``    ``}` `    ``// This function counts the total number``    ``// of valid permutations``    ``static` `int` `CountTotalValidPermutations(List<``int``> S)``    ``{``        ``HashSet> distinctPermutations = ``new` `HashSet>(``new` `ListComparer<``int``>());``        ``S.Sort();``        ``do``        ``{``            ``distinctPermutations.Add(``new` `List<``int``>(S));``        ``} ``while` `(NextPermutation(S));` `        ``int` `count = 0;``        ``foreach` `(List<``int``> A ``in` `distinctPermutations)``        ``{``            ``if` `(IsValid(A))``                ``count++;``        ``}``        ``return` `count;``    ``}` `    ``// Function to generate the next permutation``    ``// Reference: https://stackoverflow.com/a/1120871``    ``static` `bool` `NextPermutation(List<``int``> list)``    ``{``        ``int` `i = list.Count - 2;``        ``while` `(i >= 0 && list[i] >= list[i + 1])``            ``i--;``        ``if` `(i < 0)``            ``return` `false``;``        ``int` `j = list.Count - 1;``        ``while` `(list[j] <= list[i])``            ``j--;``        ``int` `temp = list[i];``        ``list[i] = list[j];``        ``list[j] = temp;``        ``j = list.Count - 1;``        ``i++;``        ``while` `(i < j)``        ``{``            ``temp = list[i];``            ``list[i] = list[j];``            ``list[j] = temp;``            ``i++;``            ``j--;``        ``}``        ``return` `true``;``    ``}` `    ``// Custom comparer for lists``    ``class` `ListComparer : IEqualityComparer>``    ``{``        ``public` `bool` `Equals(List x, List y)``        ``{``            ``return` `x.SequenceEqual(y);``        ``}` `        ``public` `int` `GetHashCode(List obj)``        ``{``            ``return` `obj.Sum(item => item.GetHashCode());``        ``}``    ``}` `    ``// Driver code``    ``static` `void` `Main()``    ``{``        ``List<``int``> S1 = ``new` `List<``int``> { 3, 6, 9 };``        ``Console.WriteLine(CountTotalValidPermutations(S1));` `        ``List<``int``> S2 = ``new` `List<``int``> { 7, 8 };``        ``Console.WriteLine(CountTotalValidPermutations(S2));` `        ``List<``int``> S3 = ``new` `List<``int``> { 2, 1, 3, 1 };``        ``Console.WriteLine(CountTotalValidPermutations(S3));``    ``}``}`

## Javascript

 `// JavaScript code for the above approach` `function` `isValid(A) {``  ``// Initializing the min and max values``  ``let mins = Math.max(...A) + 1;``  ``let maxs = -1;` `  ``// Iterating over the array``  ``for` `(let i = 0; i < A.length; i++) {` `    ``// Updating the min and max``    ``mins = Math.min(mins, A[i]);``    ``maxs = Math.max(maxs, A[i]);` `    ``// If ith element is neither min``    ``// nor max, then the array is invalid``    ``if` `(A[i] !== mins && A[i] !== maxs) {``      ``return` `false``;``    ``}``  ``}``  ``return` `true``;``}` `function` `countTotalValidPermutations(S) {``  ``let distinctPermutations = ``new` `Set();``  ``S.sort();` `  ``do` `{``    ``distinctPermutations.add([...S]);``  ``} ``while` `(nextPermutation(S));` `  ``let count = 0;``  ``for` `(let A of distinctPermutations) {``    ``if` `(isValid(A)) {``      ``count++;``    ``}``  ``}``  ``return` `count;``}` `function` `nextPermutation(arr) {``  ``let i = arr.length - 2;``  ``while` `(i >= 0 && arr[i] >= arr[i + 1]) {``    ``i--;``  ``}``  ``if` `(i < 0) {``    ``return` `false``;``  ``}``  ``let j = arr.length - 1;``  ``while` `(arr[j] <= arr[i]) {``    ``j--;``  ``}``  ``[arr[i], arr[j]] = [arr[j], arr[i]];``  ``reverse(arr, i + 1);``  ``return` `true``;``}` `function` `reverse(arr, start) {``  ``let i = start;``  ``let j = arr.length - 1;``  ``while` `(i < j) {``    ``[arr[i], arr[j]] = [arr[j], arr[i]];``    ``i++;``    ``j--;``  ``}``}` `let S1 = [3, 6, 9];``console.log(countTotalValidPermutations(S1));` `let S2 = [7, 8];``console.log(countTotalValidPermutations(S2));` `let S3 = [2, 1, 3, 1];``console.log(countTotalValidPermutations(S3));`

Output

```4
2
7```

Time Complexity: O(N! * N)
Auxiliary Space: O(N!)

Related Articles:

My Personal Notes arrow_drop_up