GFG App
Open App
Browser
Continue

# Count subarrays with equal count of occurrences of given three numbers

Given an array arr[] and three integers X, Y, Z, the task is to find the number of subarrays from the array in which the number of occurrences of X, Y and Z are equal.

Examples:

Input: arr[] = {3, 6, 7, 8, 3, 6, 7}, X = 3, Y = 6, Z = 7
Output: 8
Explanationn: There are 8 such subarrays i.e. {3, 6, 7}, {6, 7, 8, 3}, {7, 8, 3, 6}, {8}, {3, 6, 7, 8}, {8, 3, 6, 7}, {3, 6, 7}, {3, 6, 7, 8, 3, 6, 7}, in which the count of occurrences of 3, 6 and 7 are equal.

Input: arr[] = {23, 45, 76, 45, 76, 87, 23}, X = 23, Y = 45, Z = 76
Output: 4
Explanation: There are 3 such subarrays i.e. {23, 45, 76}, {45, 76, 87, 23}, {87}, {23, 45, 76, 45, 76, 87, 23}, in which the count of occurrences of 23, 45 and 76 are equal.

Approach: Follow the steps below to solve the problem:

1. Initialize three variables, say fNum_count = 0, sNum_count = 0 and tNum_count = 0 and mini.
2. Initialize a Map , int>, int>.
3. Increment frequency of {0, 0, 0} once.
4. Traverse the array and if any of the given numbers is found, then increment its corresponding count and decrement minimum of the three from all of them.
5. After traversal, increment frequency of the set of values of these three variables.
6. Now Initialize a variable, say final_ans.
7. Traverse the map and add v*(v-1) / 2 of each frequency to final_ans.
8. Print final_ans as the required answer.

Below is the implementation of the above approach:

## C++

 // C++ program for the above approach   #include using namespace std;   typedef long long ll;   // Function to count subarrays void countSubarrays(int arr[], int N,                     int X, int Y, int Z) {       map, int>, int> m;     m[{ { 0, 0 }, 0 }]++;       int fNum_count = 0, sNum_count = 0,         tNum_count = 0;     int mini;       // Traverse the array     for (int i = 0; i < N; ++i) {           // Check is arr[i] is equal to X         if (arr[i] == X) {               // Increment fNum_count             fNum_count++;               mini = min(min(fNum_count,                            sNum_count),                        tNum_count);             fNum_count -= mini;             sNum_count -= mini;             tNum_count -= mini;         }           // Check is arr[i] is equal to Y         else if (arr[i] == Y) {               // Increment the count of sNum_count             sNum_count++;               mini = min(min(fNum_count,                            sNum_count),                        tNum_count);             fNum_count -= mini;             sNum_count -= mini;             tNum_count -= mini;         }           // Check is arr[i] is equal to Z         else if (arr[i] == Z) {               // Increment the count of             // tNum_count             tNum_count++;               mini = min(min(fNum_count,                            sNum_count),                        tNum_count);             fNum_count -= mini;             sNum_count -= mini;             tNum_count -= mini;         }         m[{ { fNum_count, sNum_count },             tNum_count }]++;     }       ll final_ans = 0;     map, int>,         int>::iterator it;       // Iterate over the map     for (it = m.begin(); it != m.end();          ++it) {         ll val = it->second;         final_ans += (val * (val - 1)) / 2;     }       // Print the  answer     cout << final_ans; }   // Driver Code int main() {     // Given array     int arr[] = { 3, 6, 7, 8, 3, 6, 7 };       // Size of the array     int N = sizeof(arr) / sizeof(arr[0]);       // Given value of X, Y & Z     int X = 3, Y = 6, Z = 7;       // Function Call     countSubarrays(arr, N, X, Y, Z);       return 0; }

## Java

 // Java program for the above approach import java.util.*;   public class SubarrayCount { // Function to count subarrays     static void countSubarrays(int arr[], int N, int X,                                int Y, int Z)     {           Map, Integer>,             Integer> m             = new HashMap<>();         m.put(Map.entry(Map.entry(0, 0), 0), 1);           int fNum_count = 0, sNum_count = 0, tNum_count = 0;         int mini;           // Traverse the array         for (int i = 0; i < N; ++i) {               // Check if arr[i] is equal to X             if (arr[i] == X) {                   // Increment fNum_count                 fNum_count++;                   mini = Math.min(                     Math.min(fNum_count, sNum_count),                     tNum_count);                 fNum_count -= mini;                 sNum_count -= mini;                 tNum_count -= mini;             }               // Check if arr[i] is equal to Y             else if (arr[i] == Y) {                   // Increment sNum_count                 sNum_count++;                   mini = Math.min(                     Math.min(fNum_count, sNum_count),                     tNum_count);                 fNum_count -= mini;                 sNum_count -= mini;                 tNum_count -= mini;             }               // Check if arr[i] is equal to Z             else if (arr[i] == Z) {                   // Increment tNum_count                 tNum_count++;                   mini = Math.min(                     Math.min(fNum_count, sNum_count),                     tNum_count);                 fNum_count -= mini;                 sNum_count -= mini;                 tNum_count -= mini;             }               m.put(                 Map.entry(Map.entry(fNum_count, sNum_count),                           tNum_count),                 m.getOrDefault(                     Map.entry(                         Map.entry(fNum_count, sNum_count),                         tNum_count),                     0)                     + 1);         }           long final_ans = 0;           // Iterate over the map         for (Map.Entry<                  Map.Entry,                            Integer>,                  Integer> entry : m.entrySet()) {             int val = entry.getValue();             final_ans += (val * (val - 1)) / 2;         }           // Print the answer         System.out.println(final_ans);     }       // Driver Code     public static void main(String[] args)     {           // Given array         int arr[] = { 3, 6, 7, 8, 3, 6, 7 };           // Size of the array         int N = arr.length;           // Given value of X, Y & Z         int X = 3, Y = 6, Z = 7;           // Function Call         countSubarrays(arr, N, X, Y, Z);     } }

## Python3

 # Python3 program for the above approach   # Function to count subarrays def countSubarrays(arr, N, X, Y, Z):     m = {}     m[(  ( 0, 0 ), 0 )] = 1     fNum_count, sNum_count = 0, 0     tNum_count = 0     mini = 0       # Traverse the array     for i in range(N):           # Check is arr[i] is equal to X         if (arr[i] == X):               # Increment fNum_count             fNum_count += 1               mini = min(min(fNum_count,sNum_count),tNum_count)             fNum_count -= mini             sNum_count -= mini             tNum_count -= mini           # Check is arr[i] is equal to Y         elif (arr[i] == Y):               # Increment the count of sNum_count             sNum_count+=1               mini = min(min(fNum_count,sNum_count), tNum_count)               fNum_count -= mini             sNum_count -= mini             tNum_count -= mini           # Check is arr[i] is equal to Z         elif (arr[i] == Z):               # Increment the count of             # tNum_count             tNum_count +=1               mini = min(min(fNum_count, sNum_count), tNum_count)               fNum_count -= mini             sNum_count -= mini             tNum_count -= mini           m[(( fNum_count, sNum_count ),tNum_count )] = m.get((( fNum_count, sNum_count ),tNum_count ),0)+1       final_ans = 0           # Iterate over the map     for it in m:         val = m[it]         final_ans += (val * (val - 1)) // 2       # Print the  answer     print (final_ans)   # Driver Code if __name__ == '__main__':         # Given array     arr = [3, 6, 7, 8, 3, 6, 7]       # Size of the array     N = len(arr)       # Given value of X, Y & Z     X, Y, Z = 3, 6, 7       # Function Call     countSubarrays(arr, N, X, Y, Z)       # This code is contributed by mohit kumar 29.

## C#

 // C# program for the above approach using System; using System.Collections.Generic; using System.Linq;   class MainClass {       // Function to count subarrays     public static void countSubarrays(int[] arr, int N,                                       int X, int Y, int Z)     {         var m = new Dictionary, int>,                                int>();         m.Add(new Tuple, int>(                   new Tuple(0, 0), 0),               1);         int fNum_count = 0, sNum_count = 0, tNum_count = 0;         int mini;             // Traverse the array         for (int i = 0; i < N; i++) {                       // Check is arr[i] is equal to X             if (arr[i] == X) {                               // Increment fNum_count                 fNum_count++;                   mini = Math.Min(                     Math.Min(fNum_count, sNum_count),                     tNum_count);                 fNum_count -= mini;                 sNum_count -= mini;                 tNum_count -= mini;             }                       // Check is arr[i] is equal to Y             else if (arr[i] == Y) {                               // Increment the count of sNum_count                 sNum_count++;                   mini = Math.Min(                     Math.Min(fNum_count, sNum_count),                     tNum_count);                 fNum_count -= mini;                 sNum_count -= mini;                 tNum_count -= mini;             }                       // Check is arr[i] is equal to Z             else if (arr[i] == Z) {                               // Increment the count of             // tNum_count                 tNum_count++;                   mini = Math.Min(                     Math.Min(fNum_count, sNum_count),                     tNum_count);                 fNum_count -= mini;                 sNum_count -= mini;                 tNum_count -= mini;             }               if (m.ContainsKey(                     new Tuple, int>(                         new Tuple(fNum_count,                                             sNum_count),                         tNum_count))) {                 m[new Tuple, int>(                     new Tuple(fNum_count,                                         sNum_count),                     tNum_count)]++;             }             else {                 m.Add(new Tuple, int>(                           new Tuple(fNum_count,                                               sNum_count),                           tNum_count),                       1);             }         }           long final_ans = 0;               // Iterate over the map         foreach(var item in m)         {             long val = item.Value;             final_ans += (val * (val - 1)) / 2;         }           Console.WriteLine(final_ans);     }       public static void Main(string[] args)     {         int[] arr = { 3, 6, 7, 8, 3, 6, 7 };         int N = arr.Length;         int X = 3, Y = 6, Z = 7;           countSubarrays(arr, N, X, Y, Z);     } }   // This code is contributed by aadityaburujwale.

## Javascript

 // JavaScript program for the above approach   // Function to count subarrays function countSubarrays(arr, N, X, Y, Z) {     let m = new Map();     m.set(JSON.stringify([0, 0, 0]), 1);       let fNum_count = 0, sNum_count = 0, tNum_count = 0;     let mini;       // Traverse the array     for (let i = 0; i < N; ++i) {           // Check is arr[i] is equal to X         if (arr[i] == X) {               // Increment fNum_count             fNum_count++;               mini = Math.min(Math.min(fNum_count,                            sNum_count),                        tNum_count);             fNum_count -= mini;             sNum_count -= mini;             tNum_count -= mini;         }           // Check is arr[i] is equal to Y         else if (arr[i] == Y) {               // Increment the count of sNum_count             sNum_count++;               mini = Math.min(Math.min(fNum_count,                            sNum_count),                        tNum_count);             fNum_count -= mini;             sNum_count -= mini;             tNum_count -= mini;         }           // Check is arr[i] is equal to Z         else if (arr[i] == Z) {               // Increment the count of             // tNum_count             tNum_count++;               mini = Math.min(Math.min(fNum_count,                            sNum_count),                        tNum_count);             fNum_count -= mini;             sNum_count -= mini;             tNum_count -= mini;         }         if (m.has(JSON.stringify([fNum_count, sNum_count, tNum_count]))) {             m.set(JSON.stringify([fNum_count, sNum_count, tNum_count]),             m.get(JSON.stringify([fNum_count, sNum_count, tNum_count])) + 1);         } else {             m.set(JSON.stringify([fNum_count, sNum_count, tNum_count]), 1);         }     }       let final_ans = 0;       // Iterate over the map     for (let [key, value] of m.entries()) {         let val = value;         final_ans += (val * (val - 1)) / 2;     }       // Print the  answer     console.log(final_ans); }   // Driver Code function main() {     // Given array     let arr = [3, 6, 7, 8, 3, 6, 7];       // Size of the array     let N = arr.length;       // Given value of X, Y & Z     let X = 3, Y = 6, Z = 7;       // Function Call     countSubarrays(arr, N, X, Y, Z); }   main(); // contributed by akashish__

Output:

8

Time Complexity: O(N * LogN)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up