# Count subarrays having each distinct element occuring at least twice

Given an array arr[] of size N, the task is to count the number of subarrays from the given array, such that each distinct element in these subarray occurs at least twice.

Examples:

Input: arr[] = {1, 1, 2, 2, 2}
Output: 6
Explanation: Subarrays having each element occuring at least twice are :{{1, 1}, {1, 1, 2, 2}, {1, 1, 2, 2, 2}, {2, 2}, {2, 2, 2}, {2, 2}}.
Therefore, the required output is 6.

Input: arr[] = {1, 2, 1, 2, 3}
Output: 1

Naive Approach: The simplest approach to solve this problem is to traverse the array and generate all possible subarrays of the given array and for each subarray, check if all elements in the subarray occurs at least twice or not. If found to be true, then increment the count. Finally, print the count obtained.

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

Efficient Approach: To optimize the above approach the idea is to use Hashing. Follow the steps below to solve the problem:

• Initialize a variable, say cntSub to store the count of subarrays such that each element in the subarray occurs at least twice.
• Create a Map, say cntFreq, to store the frequency of elements of each subarray.
• Initialize a variable, say cntUnique, to store the count of elements in a subarray whose frequency is 1.
• Traverse the array and generate all possible subarrays. For each possible subarray, store the frequency of each element of the array and check if the value of cntUnique is 0 or not. If found to be true, then increment the value of cntSub.
• Finally, print the value of cntSub.

Below is the implementation of the above approach:

 `// C++ program to implement` `// the above approach`   `#include ` `using` `namespace` `std;`   `// Function to get the count` `// of subarrays having each` `// element occuring at least twice` `int` `cntSubarrays(``int` `arr[], ``int` `N)` `{` `    ``// Stores count of subarrays` `    ``// having each distinct element` `    ``// occuring at least twice` `    ``int` `cntSub = 0;`   `    ``// Stores count of unique` `    ``// elements in a subarray` `    ``int` `cntUnique = 0;`   `    ``// Store frequency of` `    ``// each element of a subarray` `    ``unordered_map<``int``, ``int``> cntFreq;`   `    ``// Traverse the given` `    ``// array` `    ``for` `(``int` `i = 0; i < N;` `         ``i++) {`   `        ``// Count frequency and` `        ``// check conditions for` `        ``// each subarray` `        ``for` `(``int` `j = i; j < N;` `             ``j++) {`   `            ``// Update frequency` `            ``cntFreq[arr[j]]++;`   `            ``// Check if frequency of` `            ``// arr[j] equal to 1` `            ``if` `(cntFreq[arr[j]]` `                ``== 1) {`   `                ``// Update Count of` `                ``// unique elements` `                ``cntUnique++;` `            ``}` `            ``else` `if` `(cntFreq[arr[j]]` `                     ``== 2) {`   `                ``// Update count of` `                ``// unique elements` `                ``cntUnique--;` `            ``}`   `            ``// If each element of subarray` `            ``// occurs at least twice` `            ``if` `(cntUnique == 0) {`   `                ``// Update cntSub` `                ``cntSub++;` `            ``}` `        ``}`   `        ``// Remove all elements` `        ``// from the subarray` `        ``cntFreq.clear();`   `        ``// Update cntUnique` `        ``cntUnique = 0;` `    ``}` `    ``return` `cntSub;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `arr[] = { 1, 1, 2, 2, 2 };` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``cout << cntSubarrays(arr, N);` `}`

 `// Java program to implement` `// the above approach` `import` `java.util.*;`   `class` `GFG{` `  `  `// Function to get the count` `// of subarrays having each` `// element occuring at least twice` `static` `int` `cntSubarrays(``int` `arr[], ``int` `N)` `{` `    `  `    ``// Stores count of subarrays` `    ``// having each distinct element` `    ``// occuring at least twice` `    ``int` `cntSub = ``0``;`   `    ``// Stores count of unique` `    ``// elements in a subarray` `    ``int` `cntUnique = ``0``;`   `    ``// Store frequency of` `    ``// each element of a subarray` `     ``Map cntFreq = ``new` `HashMap();` `                                        `  `    ``// Traverse the given` `    ``// array` `    ``for``(``int` `i = ``0``; i < N; i++) ` `    ``{` `        `  `        ``// Count frequency and` `        ``// check conditions for` `        ``// each subarray` `        ``for``(``int` `j = i; j < N; j++)` `        ``{` `            `  `            ``// Update frequency` `            ``cntFreq.put(arr[j], ` `                        ``cntFreq.getOrDefault(` `                        ``arr[j], ``0``) + ``1``); `   `            ``// Check if frequency of` `            ``// arr[j] equal to 1` `            ``if` `(cntFreq.get(arr[j]) == ``1``)` `            ``{` `                `  `                ``// Update Count of` `                ``// unique elements` `                ``cntUnique++;` `            ``}` `            ``else` `if` `(cntFreq.get(arr[j]) == ``2``) ` `            ``{` `                `  `                ``// Update count of` `                ``// unique elements` `                ``cntUnique--;` `            ``}`   `            ``// If each element of subarray` `            ``// occurs at least twice` `            ``if` `(cntUnique == ``0``)` `            ``{` `                `  `                ``// Update cntSub` `                ``cntSub++;` `            ``}` `        ``}`   `        ``// Remove all elements` `        ``// from the subarray` `        ``cntFreq.clear();`   `        ``// Update cntUnique` `        ``cntUnique = ``0``;` `    ``}` `    ``return` `cntSub;` `}`   `// Driver Code` `public` `static` `void` `main(String args[])` `{` `    ``int` `arr[] = { ``1``, ``1``, ``2``, ``2``, ``2` `};` `    ``int` `N = arr.length;` `    `  `    ``System.out.println(cntSubarrays(arr, N));` `}` `}`   `// This code is contributed by SURENDRA_GANGWAR`

 `# Python3 program to implement` `# the above appraoch` `from` `collections ``import` `defaultdict`   `# Function to get the count` `# of subarrays having each` `# element occuring at least twice ` `def` `cntSubarrays(arr, N):`   `    ``# Stores count of subarrays` `    ``# having each distinct element` `    ``# occuring at least twice` `    ``cntSub ``=` `0`   `    ``# Stores count of unique` `    ``# elements in a subarray` `    ``cntUnique ``=` `0`   `    ``# Store frequency of` `    ``# each element of a subarray` `    ``cntFreq ``=` `defaultdict(``lambda` `: ``0``)`   `    ``# Traverse the given` `    ``# array` `    ``for` `i ``in` `range``(N):` `        `  `        ``# Count frequency and` `        ``# check conditions for` `        ``# each subarray` `        ``for` `j ``in` `range``(i, N):` `            `  `            ``# Update frequency` `            ``cntFreq[arr[j]] ``+``=` `1`   `            ``# Check if frequency of` `            ``# arr[j] equal to 1` `            ``if` `(cntFreq[arr[j]] ``=``=` `1``):`   `                ``# Update Count of` `                ``# unique elements` `                ``cntUnique ``+``=` `1`   `            ``elif` `(cntFreq[arr[j]] ``=``=` `2``):` `                `  `                ``# Update count of` `                ``# unique elements` `                ``cntUnique ``-``=` `1`   `            ``# If each element of subarray` `            ``# occurs at least twice` `            ``if` `(cntUnique ``=``=` `0``):` `                `  `                ``# Update cntSub` `                ``cntSub ``+``=` `1`   `        ``# Remove all elements` `        ``# from the subarray` `        ``cntFreq.clear()`   `        ``# Update cntUnique` `        ``cntUnique ``=` `0`   `    ``return` `cntSub`   `# Driver code` `if` `__name__ ``=``=` `'__main__'``:`   `    ``arr ``=` `[ ``1``, ``1``, ``2``, ``2``, ``2` `]` `    ``N ``=` `len``(arr)` `    `  `    ``print``(cntSubarrays(arr, N))`   `# This code is contributed by Shivam Singh`

Output:
```6

```

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.

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.

Practice Tags :