Count number of permutation of an Array having no SubArray of size two or more from original Array
Last Updated :
19 Sep, 2023
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: 3Â
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));
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)
Similar Reads
Count of permutations of an Array having maximum MEXs sum of prefix arrays
Given an array arr of size N, the task is to find the number of its permutations such that the sum of MEXs of its prefix arrays is maximum. Note: MEX of a set of integers is defined as the smallest non-negative integer that does not belong to this set. Example: Input: arr[] = {1, 0, 1}Output: 2Expla
10 min read
Generate an Array of length N having K subarrays as permutations of their own length
Given integers N and K, the task is to generate an array of length N which contains exactly K subarrays as a permutation of 1 to X where X is the subarray length. There may exist multiple answers you may print any one of them. If no array is possible to construct then print -1. Note: A Permutation o
7 min read
Change the array into a permutation of numbers from 1 to n
Given an array A of n elements. We need to change the array into a permutation of numbers from 1 to n using minimum replacements in the array. Examples: Input : A[] = {2, 2, 3, 3} Output : 2 1 3 4 Explanation: To make it a permutation of 1 to 4, 1 and 4 are missing from the array. So replace 2, 3 wi
5 min read
Count of Subarrays in an array containing numbers from 1 to the length of subarray
Given an array arr[] of length N containing all elements from 1 to N, the task is to find the number of sub-arrays that contain numbers from 1 to M, where M is the length of the sub-array. Examples: Input: arr[] = {4, 1, 3, 2, 5, 6} Output: 5 Explanation: Desired Sub-arrays = { {4, 1, 3, 2}, {1}, {1
7 min read
Check if an Array is a permutation of numbers from 1 to N : Set 2
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
4 min read
Count of subarrays which forms a permutation from given Array elements
Given an array A[] consisting of integers [1, N], the task is to count the total number of subarrays of all possible lengths x (1 ? x ? N), consisting of a permutation of integers [1, x] from the given array. Examples: Input: A[] = {3, 1, 2, 5, 4} Output: 4 Explanation: Subarrays forming a permutati
6 min read
Count of permutations of an Array having each element as a multiple or a factor of its index
Given an integer n, the task is to count the number of ways to generate an array, arr[] of consisting of n integers such that for every index i (1-based indexing), arr[i] is either a factor or a multiple of i, or both. Note: The arr[] must be the permutations of all the numbers from the range [1, n]
14 min read
Count subarrays of atleast size 3 forming a Geometric Progression (GP)
Given an array arr[] of N integers, the task is to find the count of all subarrays from the given array of at least size 3 forming a Geometric Progression. Examples: Input: arr[] = {1, 2, 4, 8}Output: 3Explanation: The required subarrays forming geometric progression are: {1, 2, 4}{2, 4, 8}{1, 2, 4,
6 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 of common subarrays in two different permutations of 1 to N
Given two arrays A and B of the same length N, filled with a permutation of natural numbers from 1 to N, the task is to count the number of common subarrays in A and B.Examples: Input: A = [1, 2, 3], B = [2, 3, 1] Output: 4 Explanation: The common subarrays are [1], [2], [3], [2, 3] Hence, total cou
8 min read