Count all the permutation of an array
Last Updated :
12 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem