Open In App

Count number of permutation of an Array having no SubArray of size two or more from original Array

Last Updated : 19 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of distinct integer A, the task is to count the number of possible permutations of the given array A[] such that the permutations do not contain any subarray of size 2 or more from the original array.
Examples: 
 

Input: A = [ 1, 3, 9 ] 
Output:
All the permutation 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 sub-array [ 1, 3 ] from original list 
and [ 3, 9, 1 ] removed as it contains sub-array [3, 9] from original list so, 
Following are the 3 arrays that satisfy the condition : [1, 9, 3], [3, 1, 9], [9, 3, 1]
Input : A = [1, 3, 9, 12] 
Output :11 
 

 

Naive Approach: Iterate through list of all permutations and remove those arrays which contains any sub-array [ i, i+1 ] from A.
Below is the implementation of the above approach: 
 

C++




#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int indexOf(vector<int> arr, int target) {
    for (int i = 0; i < arr.size(); i++) {
        if (arr[i] == target) {
            return i;
        }
    }
    return -1;
}
void permute(int arr[], int l, int r, vector<vector<int>>& result) {
    if (l == r) {
        vector<int> v(arr, arr + r + 1);
        result.push_back(v);
    } else {
        for (int i = l; i <= r; i++) {
            swap(arr[l], arr[i]);
            permute(arr, l + 1, r, result);
            swap(arr[l], arr[i]);
        }
    }
}
// Function that returns count of all the permutation
// having no sub-array of [ i, i + 1 ]
int count(int arr[], int n) {
    vector<vector<int>> z;
    int perm[n];
    for (int i = 0; i < n; i++) {
        perm[i] = arr[i];
    }
    permute(perm, 0, n - 1, z);
      
    vector<vector<int>> q;
    for (int i = 0; i < n - 1; i++) {
        int x = arr[i];
        int y = arr[i + 1];
        for (int j = 0; j < z.size(); j++) {
            vector<int> curr = z[j];
            int idx = indexOf(curr, x);
            if (idx != n - 1 && curr[idx + 1] == y) {
                q.push_back(curr);
            }
        }
    }
      
    for (int i = 0; i < q.size(); i++) {
        z.erase(remove(z.begin(), z.end(), q[i]), z.end());
    }
    return z.size();
}
  
  
  
void swap(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}
  
  
// Driver code
int main() {
    int A[] = {1, 3, 9};
    int n = sizeof(A) / sizeof(A[0]);
    cout << count(A, n) << endl;
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
  
public class Main {
// Function that return count of all the permutation
// having no sub-array of [ i, i + 1 ]
public static int count(int[] arr) {
    List<int[]> z = new ArrayList<int[]>();
    int n = arr.length;
    int[] perm = new int[n];
    for (int i = 0; i < n; i++) {
        perm[i] = arr[i];
    }
    permute(perm, 0, n - 1, z);
      
    List<int[]> q = new ArrayList<int[]>();
    for (int i = 0; i < n - 1; i++) {
        int x = arr[i];
        int y = arr[i + 1];
        for (int j = 0; j < z.size(); j++) {
            int[] curr = z.get(j);
            int idx = indexOf(curr, x);
            if (idx != n - 1 && curr[idx + 1] == y) {
                q.add(curr);
            }
        }
    }
      
    z.removeAll(q);
    return z.size();
}
  
public static void permute(int[] arr, int l, int r, List<int[]> result) {
    if (l == r) {
        result.add(Arrays.copyOf(arr, arr.length));
    } else {
        for (int i = l; i <= r; i++) {
            swap(arr, l, i);
            permute(arr, l + 1, r, result);
            swap(arr, l, i);
        }
    }
}
  
public static void swap(int[] arr, int i, int j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
  
public static int indexOf(int[] arr, int target) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == target) {
            return i;
        }
    }
    return -1;
}
  
// Driver code
public static void main(String[] args) {
    int[] A = {1, 3, 9};
    System.out.println(count(A));
}
}


Python3




# Python implementation of the approach
  
# Importing the itertools 
from itertools import permutations
  
# Function that return count of all the permutation
# having no sub-array of [ i, i + 1 ]
def count(arr):
    z =[]
    perm = permutations(arr)
    for i in list(perm):
        z.append(list(i))
  
    q =[]
    for i in range(len(arr)-1):
        x, y = arr[i], arr[i + 1]
        for j in range(len(z)):
  
            # Finding the indexes where x is present
            if z[j].index(x)!= len(z[j])-1:
  
                # If y is present at position of x + 1
                # append into a temp list q
                if z[j][z[j].index(x)+1]== y:
                    q.append(z[j])
  
    # Removing all the lists that are present
    # in z ( list of all permutations )
    for i in range(len(q)):
         if q[i] in z:
             z.remove(q[i])
    return len(z)
  
# Driver Code
A =[1, 3, 9]
print(count(A))


C#




using System;
using System.Collections.Generic;
using System.Linq;
  
public class MainClass
{
  
  // Function that return count of all the permutation
  // having no sub-array of [ i, i + 1 ]
  public static int Count(int[] arr)
  {
    List<int[]> z = new List<int[]>();
    int n = arr.Length;
    int[] perm = new int[n];
    for (int i = 0; i < n; i++)
    {
      perm[i] = arr[i];
    }
    Permute(perm, 0, n - 1, z);
    List<int[]> q = new List<int[]>();
    for (int i = 0; i < n - 1; i++)
    {
      int x = arr[i];
      int y = arr[i + 1];
      for (int j = 0; j < z.Count(); j++)
      {
        int[] curr = z.ElementAt(j);
        int idx = IndexOf(curr, x);
        if (idx != n - 1 && curr[idx + 1] == y)
        {
          q.Add(curr);
        }
      }
    }
  
    z = z.Except(q).ToList();
    return z.Count();
  }
  
  public static void Permute(int[] arr, int l, int r, List<int[]> result)
  {
    if (l == r)
    {
      result.Add((int[])arr.Clone());
    }
    else
    {
      for (int i = l; i <= r; i++)
      {
        Swap(arr, l, i);
        Permute(arr, l + 1, r, result);
        Swap(arr, l, i);
      }
    }
  }
  
  public static void Swap(int[] arr, int i, int j)
  {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
  
  public static int IndexOf(int[] arr, int target)
  {
    for (int i = 0; i < arr.Length; i++)
    {
      if (arr[i] == target)
      {
        return i;
      }
    }
    return -1;
  }
  
  // Driver code
  public static void Main()
  {
    int[] A = { 1, 3, 9 };
    Console.WriteLine(Count(A));
  }
}


Javascript




// JavaScript implementation of the approach
  
// Function that return count of all the permutation
// having no sub-array of [ i, i + 1 ]
function count(arr) {
    let z = [];
    let perm = permutations(arr);
    for (let i of perm) {
        z.push(Array.from(i));
    }
  
    let q = [];
    for (let i = 0; i < arr.length - 1; i++) {
        let x = arr[i];
        let y = arr[i + 1];
        for (let j = 0; j < z.length; j++) {
  
            // Finding the indexes where x is present
            if (z[j].indexOf(x) !== z[j].length - 1) {
  
                // If y is present at position of x + 1
                // push into a temp array q
                if (z[j][z[j].indexOf(x) + 1] === y) {
                    q.push(z[j]);
                }
            }
        }
  
        // Removing all the arrays that are present
        // in z ( array of all permutations )
        for (let i = 0; i < q.length; i++) {
            if (z.includes(q[i])) {
                let index = z.indexOf(q[i]);
                z.splice(index, 1);
            }
        }
    }
    return z.length;
}
function permutations(inputArr) {
    let result = [];
  
    function permute(arr, m = []) {
        if (arr.length === 0) {
            result.push(m)
        } else {
            for (let i = 0; i < arr.length; i++) {
                let curr = arr.slice();
                let next = curr.splice(i, 1);
                permute(curr.slice(), m.concat(next))
             }
        }
    }
  
    permute(inputArr)
  
    return result;
}
  
// Driver Code
let A = [1, 3, 9];
console.log(count(A));


Output: 

3

 

Efficient Solution : After making the solution for smaller size of array, we can observe a pattern:
The following pattern generates a recurrence: 
Suppose the length of array A is n, then: 
 

count(0) = 1
count(1) = 1
count(n) = n * count(n-1) + (n-1) * count(n-2)

Below is the implementation of the approach: 
 

C++




// C++ implementation of the approach 
#include<bits/stdc++.h>
using namespace std;
  
// Recursive function that returns 
// the count of permutation-based 
// on the length of the array. 
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};
      
    // length of array
    int n = 4;
          
    // Output required answer
    cout << count(n - 1); 
          
    return 0;
}
  
// This code is contributed by Sanjit Prasad


Java




// Java implementation of the approach 
import java.util.*;
  
class GFG
{
  
// Recursive function that returns 
// the count of permutation-based 
// on the length of the array. 
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
public static void main(String[] args)
{
    int A[] = {1, 2, 3, 9};
      
    // length of array
    int n = 4;
          
    // Output required answer
    System.out.println(count(n - 1)); 
}
  
// This code is contributed by PrinciRaj1992


Python3




# Python implementation of the approach
  
# Recursive function that returns
# the count of permutation-based
# on the length of the 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 above approach
using System;
  
class GFG
{
  
// Recursive function that returns 
// the count of permutation-based 
// on the length of the array. 
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
public static void Main(String[] args)
{
    int []A = {1, 2, 3, 9};
      
    // length of array
    int n = 4;
          
    // Output required answer
    Console.WriteLine(count(n - 1)); 
}
}
  
// This code is contributed by PrinciRaj1992


Javascript




<script>
  
// JavaScript implementation of the approach
  
// Recursive function that returns
// the count of permutation-based
// on the length of the 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];
  
// length of array
let n = 4;
  
// Output required answer
document.write(count(n - 1));
  
  
// This code is contributed by _saurabh_jaiswal
  
</script>


Output: 

11

Time Complexity: O(2^n)
Auxiliary Space: O(2^n)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads