Count Permutations in a Sequence
Last Updated :
28 Nov, 2023
Given an array A consisting of N positive integers, find the total number of subsequences of the given array such that the chosen subsequence represents a permutation.
Note:
- Sequence A is a subsequence of B if A can be obtained from B by deleting some(possibly, zero) elements without changing its order. For example, [3,1] is a subsequence of [3,2,1] and [4,3,1], but not a subsequence of [1,3,3,7] and [3,10,4].
- Two permutations are different if they are of different lengths or if there is any element in the two permutations such that its index in the original array is different.
- A permutation of length N is an array of length N in which every element from 1 to N occurs exactly once.
Examples:
Input: N = 5, A[] = {1, 2, 3, 2, 4}
Output: 7
Explanation: We can get 7 permutations: {1}, {1, 2}, {1, 2}, {1, 2, 3}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 3, 4}.
Input: N = 4, A[] = {2, 1, 1, 2}
Output: 6
Explanation: We can get 6 permutations: {1}, {1}, {2, 1}, {2, 1}, {1, 2}, {1, 2}
Approach: This can be solved with the following idea:
We can use a map to store the frequency of all the elements in the array A[]. Now, run a loop starting from 1 till we get an element whose frequency is 0. The main idea is to calculate the number of permutations which can be formed using first (i-1) elements, then for each of these permutations we can append every i to form a new permutation.
Below are the steps involved:
- Store the frequency of each element in a map, say freq_arr.
- Maintain a variable prev = 1, to store the number of permutations which can be formed using elements from 1 to (i-1)
- Now, start a loop from 1 till we reach a number whose frequency in the original array is 0.
- Maintain a variable ans = 0, to store the final answer.
- For each iteration i,
- Check if freq[i] > 0. If not, break
- Else, Update prev with prev * freq[i] and add prev to ans
- Return ans
Below is the implementation of the code:
C++
// C++ Implementation for the above approach:
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
// Function to count permutation
int solve(int N, vector<int>& A)
{
// Frequency array to store frequency of
// all the elements
map<int, int> freq_arr;
long long prev = 1;
for (auto ele : A)
freq_arr[ele]++;
long long ans = 0;
for (int i = 1; freq_arr[i]; i++) {
prev = prev * freq_arr[i];
ans += prev;
}
return ans;
}
// Driver code
int main()
{
int N = 4;
vector<int> A = { 2, 1, 1, 2 };
// Function call
cout << solve(N, A);
return 0;
}
Java
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
public class PermutationCount {
// Function to count permutations
static long solve(int N, ArrayList<Integer> A) {
// Frequency map to store the frequency of all the elements
Map<Integer, Integer> freqMap = new HashMap<>();
long prev = 1;
for (int ele : A) {
freqMap.put(ele, freqMap.getOrDefault(ele, 0) + 1);
}
long ans = 0;
for (int i = 1; freqMap.containsKey(i); i++) {
prev *= freqMap.get(i);
ans += prev;
}
return ans;
}
//Driver code
public static void main(String[] args) {
int N = 4;
ArrayList<Integer> A = new ArrayList<>();
A.add(2);
A.add(1);
A.add(1);
A.add(2);
// Function call
System.out.println(solve(N, A));
}
}
Python3
# Python Implementation for the above approach:
def solve(N, A):
# Frequency dictionary to store the frequency of all the elements
freq_dict = {}
prev = 1
for ele in A:
freq_dict[ele] = freq_dict.get(ele, 0) + 1
ans = 0
for i in range(1, N + 1):
if i in freq_dict:
prev = prev * freq_dict[i]
ans += prev
else:
break
return ans
# Driver code
if __name__ == "__main__":
N = 4
A = [2, 1, 1, 2]
# Function call
print(solve(N, A))
C#
using System;
using System.Collections.Generic;
class GFG {
// Function to count permutation
static long Solve(int N, List<int> A) {
// Frequency dictionary to store frequency of all the elements
Dictionary<int, int> freqDict = new Dictionary<int, int>();
long prev = 1;
foreach (var ele in A) {
if (freqDict.ContainsKey(ele))
freqDict[ele]++;
else
freqDict[ele] = 1;
}
long ans = 0;
for (int i = 1; freqDict.ContainsKey(i); i++) {
prev = prev * freqDict[i];
ans += prev;
}
return ans;
}
// Driver code
public static void Main(string[] args) {
int N = 4;
List<int> A = new List<int> { 2, 1, 1, 2 };
// Function call
Console.WriteLine(Solve(N, A));
}
}
JavaScript
// Function to count permutations
function GFG(N, A) {
// Frequency map to the store the frequency of all the elements
const freqMap = new Map();
let prev = 1;
for (const ele of A) {
if (freqMap.has(ele)) {
freqMap.set(ele, freqMap.get(ele) + 1);
} else {
freqMap.set(ele, 1);
}
}
let ans = 0;
for (let i = 1; freqMap.has(i); i++) {
prev *= freqMap.get(i);
ans += prev;
}
return ans;
}
// Driver Code
const N = 4;
const A = [2, 1, 1, 2];
// Function call
console.log(GFG(N, A));
Time Complexity: O(N), where N is the size of input array A[]
Auxiliary Space: O(N)
Similar Reads
Count all increasing subsequences Given an array arr[] of integers (values lie in range from 0 to 9). The task is to count the number of strictly increasing subsequences that can be formed from this array. Note: A strictly increasing subsequence is a sequence where each element is greater than the previous one, and the elements are
10 min read
Count the number of special permutations Given two positive integers n and k, the task is to count the number of special permutations. A special permutation P is defined as a permutation of first n natural numbers in which there exists at least (n - k) indices such that Pi = i. Prerequisite: Derangements Examples: Input: n = 4, k = 2 Outpu
15+ min read
Permutation and Combination in Python Python provides built-in methods to work with permutations and combinations using the itertools module. These are helpful in problems involving arrangement (order matters) and selection (order doesnât matter) of elements.Let's explore them one by one:PermutationA permutation is an arrangement of ele
2 min read
Count Distinct Subsequences Given a string str of length n, your task is to find the count of distinct subsequences of it.Examples: Input: str = "gfg"Output: 7Explanation: The seven distinct subsequences are "", "g", "f", "gf", "fg", "gg" and "gfg" Input: str = "ggg"Output: 4Explanation: The four distinct subsequences are "",
13 min read
Count all the permutation of an array 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: 3Explanation: All the permutations of 1 3 9 are : [1, 3, 9], [1, 9, 3], [3, 9, 1], [
10 min read
Count permutations that produce positive result Given an array of digits of length n > 1, digits lies within range 0 to 9. We perform sequence of below three operations until we are done with all digits Select starting two digits and add ( + )Then next digit is subtracted ( - ) from result of above step. The result of above step is multiplied
11 min read