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.
Input: A = [ 1, 3, 9 ]
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]
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:
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:
Note: For the above recurrence you can check oeis.org.
- Count subarrays having total distinct elements same as original array
- Find original array from encrypted array (An array of sums of other elements)
- Find a subarray whose sum is divisible by size of the array
- Smallest subarray whose sum is multiple of array size
- Minimum number of operations to convert array A to array B by adding an integer into a subarray
- Generate original array from an array that store the counts of greater elements on right
- Count Inversions of size three in a given array
- Count of Subarrays in an array containing numbers from 1 to the length of subarray
- Count the number of primes in the prefix sum array of the given array
- Number of triplets in array having subarray xor equal
- Check in binary array the number represented by a subarray is odd or even
- Permutation of an array that has smaller values from another array
- Find permutation array from the cumulative sum array
- Maximum subarray sum in array formed by repeating the given array k times
- Sort an array where a subarray of a sorted array is in reverse order
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.