Count subarrays having each distinct element occurring at least twice
Last Updated :
04 Oct, 2021
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 occurring 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++
#include <bits/stdc++.h>
using namespace std;
int cntSubarrays( int arr[], int N)
{
int cntSub = 0;
int cntUnique = 0;
unordered_map< int , int > cntFreq;
for ( int i = 0; i < N;
i++) {
for ( int j = i; j < N;
j++) {
cntFreq[arr[j]]++;
if (cntFreq[arr[j]]
== 1) {
cntUnique++;
}
else if (cntFreq[arr[j]]
== 2) {
cntUnique--;
}
if (cntUnique == 0) {
cntSub++;
}
}
cntFreq.clear();
cntUnique = 0;
}
return cntSub;
}
int main()
{
int arr[] = { 1, 1, 2, 2, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << cntSubarrays(arr, N);
}
|
Java
import java.util.*;
class GFG{
static int cntSubarrays( int arr[], int N)
{
int cntSub = 0 ;
int cntUnique = 0 ;
Map<Integer,
Integer> cntFreq = new HashMap<Integer,
Integer>();
for ( int i = 0 ; i < N; i++)
{
for ( int j = i; j < N; j++)
{
cntFreq.put(arr[j],
cntFreq.getOrDefault(
arr[j], 0 ) + 1 );
if (cntFreq.get(arr[j]) == 1 )
{
cntUnique++;
}
else if (cntFreq.get(arr[j]) == 2 )
{
cntUnique--;
}
if (cntUnique == 0 )
{
cntSub++;
}
}
cntFreq.clear();
cntUnique = 0 ;
}
return cntSub;
}
public static void main(String args[])
{
int arr[] = { 1 , 1 , 2 , 2 , 2 };
int N = arr.length;
System.out.println(cntSubarrays(arr, N));
}
}
|
Python3
from collections import defaultdict
def cntSubarrays(arr, N):
cntSub = 0
cntUnique = 0
cntFreq = defaultdict( lambda : 0 )
for i in range (N):
for j in range (i, N):
cntFreq[arr[j]] + = 1
if (cntFreq[arr[j]] = = 1 ):
cntUnique + = 1
elif (cntFreq[arr[j]] = = 2 ):
cntUnique - = 1
if (cntUnique = = 0 ):
cntSub + = 1
cntFreq.clear()
cntUnique = 0
return cntSub
if __name__ = = '__main__' :
arr = [ 1 , 1 , 2 , 2 , 2 ]
N = len (arr)
print (cntSubarrays(arr, N))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int cntSubarrays( int [] arr, int N)
{
int cntSub = 0;
int cntUnique = 0;
Dictionary< int ,
int > cntFreq = new Dictionary< int ,
int >();
for ( int i = 0; i < N; i++)
{
for ( int j = i; j < N; j++)
{
if (cntFreq.ContainsKey(arr[j]))
{
var val = cntFreq[arr[j]];
cntFreq.Remove(arr[j]);
cntFreq.Add(arr[j], val + 1);
}
else
{
cntFreq.Add(arr[j], 1);
}
if (cntFreq[arr[j]] == 1)
{
cntUnique++;
}
else if (cntFreq[arr[j]] == 2)
{
cntUnique--;
}
if (cntUnique == 0)
{
cntSub++;
}
}
cntFreq.Clear();
cntUnique = 0;
}
return cntSub;
}
public static void Main()
{
int [] arr = { 1, 1, 2, 2, 2 };
int N = arr.Length;
Console.Write(cntSubarrays(arr, N));
}
}
|
Javascript
<script>
function cntSubarrays(arr, N)
{
var cntSub = 0;
var cntUnique = 0;
var cntFreq = new Map();
for ( var i = 0; i < N;
i++) {
for ( var j = i; j < N;
j++) {
if (cntFreq.has(arr[j]))
cntFreq.set(arr[j], cntFreq.get(arr[j])+1)
else
cntFreq.set(arr[j], 1);
if (cntFreq.get(arr[j])
== 1) {
cntUnique++;
}
else if (cntFreq.get(arr[j])
== 2) {
cntUnique--;
}
if (cntUnique == 0) {
cntSub++;
}
}
cntFreq = new Map();
cntUnique = 0;
}
return cntSub;
}
var arr = [1, 1, 2, 2, 2];
var N = arr.length;
document.write( cntSubarrays(arr, N));
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...