Count all the permutation of an array
Last Updated :
30 Jul, 2024
Given an array of integer A[] with no duplicate elements, write a function that returns the count of all the permutations of an array having no subarray of [i, i+1] for every i in A[].
Examples:
Input: 1 3 9
Output: 3
Explanation: All the permutations of 1 3 9 are : [1, 3, 9], [1, 9, 3], [3, 9, 1], [3, 1, 9], [9, 1, 3], [9, 3, 1] Here [1, 3, 9], [9, 1, 3] are removed as they contain subarray [1, 3] from the original list and [3, 9, 1] removed as it contains subarray [3, 9] from the original list so, Following are the 3 arrays that satisfy the condition : [1, 9, 3], [3, 1, 9], [9, 3, 1]
Input: 1 3 9 12
Output: 11
Naive Solution: Generate all the permutations of an array and count all such permutations.
Efficient Solution : Following is a recursive solution based on fact that length of the array decides the number of all permutations having no subarray [i, i+1] for every i in A[ ]
Suppose the length of A[ ] is n, then
n = n-1
count(0) = 1
count(1) = 1
count(n) = n * count(n-1) + (n-1) * count(n-2)
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
// Recursive function that return count of
// permutation based on the length of array.
#include <bits/stdc++.h>
using namespace std;
int count(int n)
{
if(n == 0)
return 1;
if(n == 1)
return 1;
else
return (n * count(n - 1)) +
((n - 1) * count(n - 2));
}
// Driver code
int main()
{
int A[] = {1, 2, 3, 9};
int len = sizeof(A) / sizeof(A[0]);
cout << count(len - 1);
}
// This code is contributed by 29AjayKumar
Java
// Java implementation of the approach
// Recursive function that return count of
// permutation based on the length of array.
import java.util.*;
class GFG
{
static int count(int n)
{
if(n == 0)
return 1;
if(n == 1)
return 1;
else
return (n * count(n - 1)) +
((n - 1) * count(n - 2));
}
// Driver Code
static public void main(String[] arg)
{
int []A = {1, 2, 3, 9};
System.out.print(count(A.length - 1));
}
}
// This code is contributed by PrinciRaj1992
Python
# Python implementation of the approach
# Recursive function that return count of
# permutation based on the length of array.
def count(n):
if n == 0:
return 1
if n == 1:
return 1
else:
return (n * count(n-1)) + ((n-1) * count(n-2))
# Driver Code
A = [1, 2, 3, 9]
print(count(len(A)-1))
C#
// C# implementation of the approach
// Recursive function that return count of
// permutation based on the length of array.
using System;
class GFG
{
static int count(int n)
{
if(n == 0)
return 1;
if(n == 1)
return 1;
else
return (n * count(n - 1)) +
((n - 1) * count(n - 2));
}
// Driver Code
static public void Main(String[] arg)
{
int []A = {1, 2, 3, 9};
Console.Write(count(A.Length - 1));
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
// Javascript implementation of the approach
// Recursive function that return count of
// permutation based on the length of array.
function count(n) {
if(n == 0)
return 1;
if(n == 1)
return 1;
else
return (n * count(n - 1)) +
((n - 1) * count(n - 2));
}
// Driver code
let A = [1, 2, 3, 9];
let len = A.length;
document.write(count(len - 1));
// This code is contributed by Samim Hossain Mondal.
</script>
Time Complexity: O(n!), Finding pair for every element in the array of size n.
Auxiliary Space: O(n)
Brute Force Method :
Approach:
Our approach is very simple ,First we generate all the permutations of the given array and check if each permutation satisfies the given condition or not. We can do this by transversing through each element of the permutation and checking if it is adjacent to the next element in the original array or not.
Algorithms:
1.We can generate all the permutations of the given array A[].
2. For each permutation, we check if it contains any subarray of [i, i+1] for every i in A[].
If it does not contain any such subarray, we count it as a valid permutation.
To check if a permutation contains any subarray of [i, i+1], we can simply iterate through the permutation and check if any adjacent pair forms such subarray.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool is_Valid_Permutation(vector<int>& permutation, vector<int>& arr) {
for (int i = 0; i < permutation.size() - 1; i++) {
int x = permutation[i], y = permutation[i + 1];
if (abs(x - y) == 1 && arr[x] < arr[y]) {
return false;
}
}
return true;
}
int count_Permutations(vector<int>& arr) {
int n = arr.size();
vector<int> permutation(n);
for (int i = 0; i < n; i++) {
permutation[i] = i;
}
int count = 0;
do {
if (is_Valid_Permutation(permutation, arr)) {
count++;
}
} while (next_permutation(permutation.begin(), permutation.end()));
return count;
}
int main() {
vector<int> arr = {1, 2, 3};
cout << count_Permutations(arr) << endl;
arr = {1, 2, 3, 9};
cout << count_Permutations(arr) << endl;
return 0;
}
Java
import java.util.ArrayList;
import java.util.Collections;
public class PermutationCount {
// Function to check if a given permutation is valid
static boolean
isValidPermutation(ArrayList<Integer> permutation,
ArrayList<Integer> arr)
{
for (int i = 0; i < permutation.size() - 1; i++) {
int x = permutation.get(i);
int y = permutation.get(i + 1);
// Check if the adjacent elements in the
// permutation are consecutive and form an
// increasing subsequence in the original array.
if (Math.abs(x - y) == 1
&& arr.get(x) < arr.get(y)) {
return false; // If the condition is not
// met, the permutation is not
// valid.
}
}
return true; // If all adjacent elements satisfy the
// condition, the permutation is valid.
}
// Function to count valid permutations
static int countPermutations(ArrayList<Integer> arr)
{
int n = arr.size();
ArrayList<Integer> permutation = new ArrayList<>();
for (int i = 0; i < n; i++) {
permutation.add(
i); // Create an initial permutation (0, 1,
// 2, ..., n-1).
}
int count = 0; // Initialize the count of valid
// permutations to 0.
do {
if (isValidPermutation(permutation, arr)) {
count++; // If the current permutation is
// valid, increment the count.
}
} while (nextPermutation(
permutation)); // Generate all permutations
// using lexicographic order.
return count; // Return the total count of valid
// permutations.
}
// Function to find the next permutation
static boolean
nextPermutation(ArrayList<Integer> permutation)
{
int i = permutation.size() - 2;
// Find the longest suffix of the permutation that
// is in non-increasing order.
while (i >= 0
&& permutation.get(i)
>= permutation.get(i + 1)) {
i--;
}
if (i < 0) {
return false; // If the entire permutation is in
// non-increasing order, there is
// no next permutation.
}
int j = permutation.size() - 1;
// Find the rightmost element in the suffix that is
// greater than the current element
// (permutation[i]).
while (permutation.get(j) <= permutation.get(i)) {
j--;
}
// Swap the current element with the next greater
// element in the suffix.
swap(permutation, i, j);
// Reverse the suffix to get the next permutation in
// lexicographic order.
reverse(permutation, i + 1, permutation.size() - 1);
return true; // Successfully generated the next
// permutation.
}
// Function to swap two elements in an ArrayList
static void swap(ArrayList<Integer> arr, int i, int j)
{
int temp = arr.get(i);
arr.set(i, arr.get(j));
arr.set(j, temp);
}
// Function to reverse a portion of the ArrayList
static void reverse(ArrayList<Integer> arr, int i,
int j)
{
while (i < j) {
swap(arr, i, j);
i++;
j--;
}
}
public static void main(String[] args)
{
ArrayList<Integer> arr1 = new ArrayList<>();
arr1.add(1);
arr1.add(2);
arr1.add(3);
System.out.println(countPermutations(
arr1)); // Output: 2 (Valid permutations: (1, 3,
// 2) and (2, 1, 3))
ArrayList<Integer> arr2 = new ArrayList<>();
arr2.add(1);
arr2.add(2);
arr2.add(3);
arr2.add(9);
System.out.println(countPermutations(
arr2)); // Output: 0 (No valid permutation, as
// (1, 3, 2, 9) breaks the increasing
// subsequence condition)
}
}
Python
import itertools
def is_valid_permutation(permutation, arr):
for i in range(len(permutation) - 1):
x, y = permutation[i], permutation[i + 1]
if abs(x - y) == 1 and arr[x] < arr[y]:
return False
return True
def count_permutations(arr):
n = len(arr)
permutation = list(range(n))
count = 0
for perm in itertools.permutations(permutation):
if is_valid_permutation(perm, arr):
count += 1
return count
def main():
arr = [1, 2, 3]
print(count_permutations(arr)) # Output: 3
arr = [1, 2, 3, 9]
print(count_permutations(arr)) # Output: 6
if __name__ == "__main__":
main()
C#
using System;
using System.Collections.Generic;
using System.Linq;
class MainClass {
// Function to check if a given permutation is valid
static bool IsValidPermutation(List<int> permutation,
List<int> arr)
{
for (int i = 0; i < permutation.Count - 1; i++) {
int x = permutation[i], y = permutation[i + 1];
if (Math.Abs(x - y) == 1 && arr[x] < arr[y]) {
return false;
}
}
return true;
}
// Function to count valid permutations of given array
static int CountPermutations(List<int> arr)
{
int n = arr.Count;
List<int> permutation
= Enumerable.Range(0, n)
.ToList(); // Generate initial permutation
int count = 0;
do {
if (IsValidPermutation(permutation, arr)) {
count++;
}
} while (NextPermutation(permutation));
return count;
}
// Function to generate the next permutation
static bool NextPermutation(List<int> permutation)
{
int i = permutation.Count - 2;
while (i >= 0
&& permutation[i] >= permutation[i + 1]) {
i--;
}
if (i < 0)
return false; // Last permutation reached
int j = permutation.Count - 1;
while (permutation[j] <= permutation[i]) {
j--;
}
Swap(permutation, i, j);
Reverse(permutation, i + 1);
return true;
}
// Function to swap two elements in a list
static void Swap(List<int> list, int i, int j)
{
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
// Function to reverse elements in a list from start
// index
static void Reverse(List<int> list, int start)
{
int i = start, j = list.Count - 1;
while (i < j) {
Swap(list, i, j);
i++;
j--;
}
}
// Main method
public static void Main(string[] args)
{
List<int> arr = new List<int>{ 1, 2, 3 };
Console.WriteLine(
CountPermutations(arr)); // Output: 2
arr = new List<int>{ 1, 2, 3, 9 };
Console.WriteLine(
CountPermutations(arr)); // Output: 6
}
}
JavaScript
// Function to generate all permutations of an array
function permute(nums) {
const result = [];
// Recursive function to generate permutations
function backtrack(current, remaining) {
if (remaining.length === 0) {
result.push([...current]);
return;
}
for (let i = 0; i < remaining.length; i++) {
current.push(remaining[i]);
const rest = remaining.slice(0, i).concat(remaining.slice(i + 1));
backtrack(current, rest);
current.pop();
}
}
backtrack([], nums);
return result;
}
// Function to check if a permutation is valid
function isValid(permutation, arr) {
for (let i = 0; i < permutation.length - 1; i++) {
const index1 = arr.indexOf(permutation[i]);
const index2 = arr.indexOf(permutation[i + 1]);
if (Math.abs(index1 - index2) === 1) {
return false;
}
}
return true;
}
// Main function to find valid permutations
function findValidPermutations(arr) {
const permutations = permute(arr);
const validPermutations = [];
// Check each permutation for validity
for (const permutation of permutations) {
if (isValid(permutation, arr)) {
validPermutations.push(permutation);
}
}
return validPermutations;
}
// Example usage
const array = [1, 2, 3, 11];
const validPermutations = findValidPermutations(array);
// Filter the valid permutations to remove any with the first element as 11
const filteredPermutations = validPermutations.filter(permutation => permutation[0] !== 11);
console.log("Valid Permutations:", filteredPermutations);
Time Complexity: O(n*n!)
Auxiliary Space: O(n)
Similar Reads
All Permutations of an Array
Given an array arr[] the task is to print all the possible permutations of the given array. Examples: Input: arr[] = {1, 2, 3}Output: {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 2, 1}, {3, 1, 2}Explanation: There are 6 possible permutations Input: arr[] = {1, 3}Output: {1, 3}, {3, 1}Explanation:
6 min read
Print All Distinct Permutations of an Array
Given an array arr[], Print all distinct permutations of the given array. Examples: Input: arr[] = [1, 3, 3]Output: [[1, 3, 3], [3, 1, 3], [3, 3, 1]]Explanation: Above are all distinct permutations of given array. Input: arr[] = [2, 2] Output: [[2, 2]]Explanation: Above are all distinct permutations
6 min read
Generate all permutation of a set in Python
Permutation is an arrangement of objects in a specific order. Order of arrangement of object is very important. The number of permutations on a set of n elements is given by n!. For example, there are 2! = 2*1 = 2 permutations of {1, 2}, namely {1, 2} and {2, 1}, and 3! = 3*2*1 = 6 permutations of {
2 min read
What is a Permutation Array in DSA?
A permutation array, often called a permutation or permuted array, is an arrangement of elements from a source array in a specific order different from their original placement. The critical characteristic of a permutation array is that it contains all the elements from the source array but in a dif
7 min read
Find permutation array from the cumulative sum array
Given an array arr[] of N elements where each arr[i] is the cumulative sum of the subarray P[0...i] of another array P[] where P is the permutation of the integers from 1 to N. The task is to find the array P[], if no such P exists then print -1.Examples: Input: arr[] = {2, 3, 6} Output: 2 1 3Input:
5 min read
Iterative approach to print all permutations of an Array
Given an array arr[] of size N, the task is to generate and print all permutations of the given array. Examples: Input: arr[] = {1, 2} Output: 1 2 2 1 Input: {0, 1, 2} Output: 0 1 2 1 0 2 0 2 1 2 0 1 1 2 0 2 1 0 Approach: The recursive methods to solve the above problems are discussed here and here.
14 min read
Check if an Array is a permutation of numbers from 1 to N
Given an array arr containing N positive integers, the task is to check if the given array arr represents a permutation or not. A sequence of N integers is called a permutation if it contains all integers from 1 to N exactly once. Examples: Input: arr[] = {1, 2, 5, 3, 2} Output: No Explanation: The
15+ min read
Count Inversions of an Array
Given an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j. Note: Inversion Count for an array indicates that how far (or close) the array is from being sorted. If the array is already sorte
15+ min read
Count Permutations in a Sequence
Given an array A consisting of N positive integers, find the total number of subsequences of the given array such that the chosen subsequence represents a permutation. Note: Sequence A is a subsequence of B if A can be obtained from B by deleting some(possibly, zero) elements without changing its or
5 min read
Different Ways to Generate Permutations of an Array
Permutations are like the magic wand of combinatorics, allowing us to explore the countless ways elements can be rearranged within an array. Whether you're a coder, a math enthusiast, or someone on a quest to solve a complex problem, understanding how to generate all permutations of an array is a va
6 min read