Open In App

Count all the permutation of an array

Last Updated : 08 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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
Python3
# 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>

Output
11

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)
    }
}
Python3
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);

Output
3
11

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads