Find total number of Permutations such that every element becomes an Extrema
Last Updated :
19 Sep, 2023
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 <bits/stdc++.h>
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<vector<int> > 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<Integer> 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<Integer> S)
{
Set<Vector<Integer> > distinctPermutations
= new HashSet<>();
Collections.sort(S);
do {
distinctPermutations.add(new Vector<>(S));
} while (nextPermutation(S));
int count = 0;
for (Vector<Integer> A : distinctPermutations)
if (isValid(A))
count++;
return count;
}
public static boolean nextPermutation(Vector<Integer> 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<Integer> S1
= new Vector<>(Arrays.asList(3, 6, 9));
System.out.println(countTotalValidPermutations(S1));
Vector<Integer> S2
= new Vector<>(Arrays.asList(7, 8));
System.out.println(countTotalValidPermutations(S2));
Vector<Integer> 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<List<int>> distinctPermutations = new HashSet<List<int>>(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
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<T> : IEqualityComparer<List<T>>
{
public bool Equals(List<T> x, List<T> y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(List<T> 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));
Time Complexity: O(N! * N)
Auxiliary Space: O(N!)
Related Articles:
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read