Related Articles

# Count of subarrays with X as the most frequent element, for each value of X from 1 to N

• Last Updated : 13 Jul, 2021

Given an array arr[] of size N, (where 0<A[i]<=N, for all 0<=i<N), the task is to calculate for each number X from 1 to N, the number of subarrays in which X is the most frequent element. In subarrays, where more than one element has the maximum frequency, the smallest element should be considered as the most frequent.

Examples:

Input: arr[]={2, 1, 2, 3}, N=4
Output:
4 5 1 0
Explanation:

1. For X=1, the subarrays where X is the most frequent element, are {2, 1}, {1}, {1, 2}, {1, 2, 3}
2. For X=2, the subarrays where X is the most frequent element, are {2}, {2, 1, 2}, {2, 1, 2, 3}, {2}, {2, 3}
3. For X=3, the subarray where X is the most frequent element, is {3}
4. For X=4, there are no subarrays containing 4.

Input: arr[]={3, 1, 5, 1, 3}, N=5
Output:
12 0 2 0 1

Approach: The approach is to keep track of the most frequent element in each subarray using two loops and keep them stored in a separate array. Follow the steps below to solve the problem:

1. Initialize an array ans of size N to 0, to store the final answers.
2. Iterate from 0 to N-1, and for each current index i, do the following:
1. Initialize a frequency array count of size N to 0, to store the current frequencies of each element from 1 to N.
2. Initialize a variable best to 0, to store the most frequent element in the current subarray.
3. Iterate from i to N-1, and for each current index j, do the following:
1. Increment the count of current element i.e count[arr[j]-1]=count[arr[j]-1]+1
2. Check if the frequency of the current element i.e arr[j] is greater than the frequency of best.
3. Check if the frequency of the current element i.e arr[j] is equal to the frequency of best and the current element is less than best.
4. If either of them is true, update best to the current element i.e best=arr[j]
5. Increment the best index of the ans array i.e ans[best-1]=ans[best-1]+1.
3. Print the array ans.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to calculate the number of subarrays where``// X(1<=X<=N) is the most frequent element``int` `mostFrequent(``int` `arr[], ``int` `N)``{``    ``// array to store the final answers``    ``int` `ans[N] = { 0 };` `    ``for` `(``int` `i = 0; i < N; i++) {` `        ``// Array to store current frequencies``        ``int` `count[N];` `        ``// Initialise count``        ``memset``(count, 0, ``sizeof``(count));` `        ``// Variable to store the``        ``// current most frequent element``        ``int` `best = 0;``        ``for` `(``int` `j = i; j < N; j++) {` `            ``// Update frequency array``            ``count[arr[j] - 1]++;``            ``if` `(count[arr[j] - 1] > count[best - 1]``                ``|| (count[arr[j] - 1] == count[best - 1]``                    ``&& arr[j] < best)) {``                ``best = arr[j];``            ``}` `            ``// Update answer``            ``ans[best - 1]++;``        ``}``    ``}` `    ``// Print answer``    ``for` `(``int` `i = 0; i < N; i++)``        ``cout << ans[i] << ``" "``;``}``// Driver code``int` `main()``{``    ``// Input``    ``int` `arr[] = { 2, 1, 2, 3 };``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);` `    ``// Function call``    ``mostFrequent(arr, N);``    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;` `class` `GFG {` `    ``// Function to calculate the number of subarrays where``    ``// X(1<=X<=N) is the most frequent element``    ``public` `static` `void` `mostFrequent(``int``[] arr, ``int` `N)``    ``{``        ``// array to store the final answers``        ``int``[] ans = ``new` `int``[N];` `        ``for` `(``int` `i = ``0``; i < N; i++) {` `            ``// Array to store current frequencies``            ``int``[] count = ``new` `int``[N];` `            ``// Variable to store the``            ``// current most frequent element``            ``int` `best = ``1``;``            ``for` `(``int` `j = i; j < N; j++) {` `                ``// Update frequency array``                ``count[arr[j] - ``1``]++;``                ``if` `(best > ``0``) {``                    ``if` `((count[arr[j] - ``1``]``                         ``> count[best - ``1``])``                        ``|| (count[arr[j] - ``1``]``                                ``== count[best - ``1``]``                            ``&& arr[j] < best)) {``                        ``best = arr[j];``                    ``}` `                    ``// Update answer``                    ``ans[best - ``1``]++;``                ``}``            ``}``        ``}` `        ``// Print answer``        ``for` `(``int` `i = ``0``; i < N; i++)``        ``System.out.print(ans[i] + ``" "``);``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``      ` `     ``// Input``        ``int``[] arr = { ``2``, ``1``, ``2``, ``3` `};``        ``int` `N = arr.length;` `        ``// Function call``        ``mostFrequent(arr, N);``    ``}``}` `// This code is contributed by sanjoy_62.`

## Python3

 `# Python program for the above approach` `# Function to calculate the number of subarrays where``# X(1<=X<=N) is the most frequent element``def` `mostFrequent(arr, N):``    ``# array to store the final answers``    ``ans ``=` `[``0``]``*``N` `    ``for` `i ``in` `range``(N):``        ``# Array to store current frequencies``        ``count ``=` `[``0``]``*``N` `        ``# Initialise count``        ``# memset(count, 0, sizeof(count))` `        ``# Variable to store the``        ``# current most frequent element``        ``best ``=` `0``        ``for` `j ``in` `range``(i,N):``            ``# Update frequency array``            ``count[arr[j] ``-` `1``]``+``=``1``            ``if` `(count[arr[j] ``-` `1``] > count[best ``-` `1``]``                ``or` `(count[arr[j] ``-` `1``] ``=``=` `count[best ``-` `1``]``                    ``and` `arr[j] < best)):``                ``best ``=` `arr[j]` `            ``# Update answer``            ``ans[best ``-` `1``] ``+``=` `1` `    ``# Pranswer``    ``print``(``*``ans)``    ` `# Driver code``if` `__name__ ``=``=` `'__main__'``:``    ``# Input``    ``arr``=` `[``2``, ``1``, ``2``, ``3``]``    ``N ``=` `len``(arr)` `    ``# Function call``    ``mostFrequent(arr, N)` `# This code is contributed by mohit kumar 29.`

## C#

 `// C# program for the above approach``using` `System;``class` `GFG {` `    ``// Function to calculate the number of subarrays where``    ``// X(1<=X<=N) is the most frequent element``    ``public` `static` `void` `mostFrequent(``int``[] arr, ``int` `N)``    ``{``        ``// array to store the final answers``        ``int``[] ans = ``new` `int``[N];` `        ``for` `(``int` `i = 0; i < N; i++) {` `            ``// Array to store current frequencies``            ``int``[] count = ``new` `int``[N];` `            ``// Variable to store the``            ``// current most frequent element``            ``int` `best = 1;``            ``for` `(``int` `j = i; j < N; j++) {` `                ``// Update frequency array``                ``count[arr[j] - 1]++;``                ``if` `(best > 0) {``                    ``if` `((count[arr[j] - 1]``                         ``> count[best - 1])``                        ``|| (count[arr[j] - 1]``                                ``== count[best - 1]``                            ``&& arr[j] < best)) {``                        ``best = arr[j];``                    ``}` `                    ``// Update answer``                    ``ans[best - 1]++;``                ``}``            ``}``        ``}` `        ``// Print answer``        ``for` `(``int` `i = 0; i < N; i++)``            ``Console.Write(ans[i] + ``" "``);``    ``}``  ` `    ``// Driver code``    ``public` `static` `void` `Main()``    ``{``      ` `        ``// Input``        ``int``[] arr = { 2, 1, 2, 3 };``        ``int` `N = arr.Length;` `        ``// Function call``        ``mostFrequent(arr, N);``    ``}``}` `// This code is contributed by subham348.`

## Javascript

 ``

Output:
`4 5 1 0`

Time Complexity: O(N2)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up