Count subarrays with equal number of occurrences of two given elements
Last Updated :
05 Jan, 2023
Given an array and two integers say, x and y, find the number of subarrays in which the number of occurrences of x is equal to the number of occurrences of y.
Examples:
Input : arr[] = {1, 2, 1},
x = 1, y = 2
Output : 2
The possible sub-arrays have same equal number
of occurrences of x and y are:
1) {1, 2}, x and y have same occurrence(1).
2) {2, 1}, x and y have same occurrence(1).
Input : arr[] = {1, 2, 1},
x = 4, y = 6
Output : 6
The possible sub-arrays have same equal number of
occurrences of x and y are:
1) {1}, x and y have same occurrence(0).
2) {2}, x and y have same occurrence(0).
3) {1}, x and y have same occurrence(0).
1) {1, 2}, x and y have same occurrence(0).
2) {2, 1}, x and y have same occurrence(0).
3) {1, 2, 1}, x and y have same occurrence(0).
Input : arr[] = {1, 2, 1},
x = 1, y = 1
Output : 6
The possible sub-arrays have same equal number
of occurrences of x and y are:
1) {1}, x and y have same occurrence(1).
2) {2}, x and y have same occurrence(0).
3) {1}, x and y have same occurrence(1).
1) {1, 2}, x and y have same occurrence(1).
2) {2, 1}, x and y have same occurrence(1).
3) {1, 2, 1}, x and y have same occurrences (2).
We can simply generate all the possible sub-arrays and check for each subarray whether the number of occurrences of x is equal to that of y in that particular subarray.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int sameOccurrence( int arr[], int n, int x, int y)
{
int result = 0;
for ( int i = 0; i <= n - 1; i++) {
int ctX = 0, ctY = 0;
for ( int j = i; j <= n - 1; j++) {
if (arr[j] == x)
ctX += 1;
else if (arr[j] == y)
ctY += 1;
if (ctX == ctY)
result += 1;
}
}
return (result);
}
int main()
{
int arr[] = { 1, 2, 2, 3, 4, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
int x = 2, y = 3;
cout << sameOccurrence(arr, n, x, y);
return (0);
}
|
Java
import java.util.*;
class solution
{
static int sameOccurrence( int arr[], int n, int x, int y)
{
int result = 0 ;
for ( int i = 0 ; i <= n - 1 ; i++) {
int ctX = 0 , ctY = 0 ;
for ( int j = i; j <= n - 1 ; j++) {
if (arr[j] == x)
ctX += 1 ;
else if (arr[j] == y)
ctY += 1 ;
if (ctX == ctY)
result += 1 ;
}
}
return (result);
}
public static void main(String args[])
{
int arr[] = { 1 , 2 , 2 , 3 , 4 , 1 };
int n = arr.length;
int x = 2 , y = 3 ;
System.out.println(sameOccurrence(arr, n, x, y));
}
}
|
Python3
def sameOccurrence(arr, n, x, y):
result = 0
for i in range (n):
ctX = 0
ctY = 0
for j in range (i, n, 1 ):
if (arr[j] = = x):
ctX + = 1 ;
elif (arr[j] = = y):
ctY + = 1
if (ctX = = ctY):
result + = 1
return (result)
if __name__ = = '__main__' :
arr = [ 1 , 2 , 2 , 3 , 4 , 1 ]
n = len (arr)
x = 2
y = 3
print (sameOccurrence(arr, n, x, y))
|
C#
using System;
class GFG
{
static int sameOccurrence( int [] arr, int n,
int x, int y)
{
int result = 0;
for ( int i = 0; i <= n - 1; i++)
{
int ctX = 0, ctY = 0;
for ( int j = i; j <= n - 1; j++)
{
if (arr[j] == x)
ctX += 1;
else if (arr[j] == y)
ctY += 1;
if (ctX == ctY)
result += 1;
}
}
return (result);
}
public static void Main()
{
int [] arr = { 1, 2, 2, 3, 4, 1 };
int n = arr.Length;
int x = 2, y = 3;
Console.Write(sameOccurrence(arr, n, x, y));
}
}
|
PHP
<?php
function sameOccurrence( $arr , $n , $x , $y )
{
$result = 0;
for ( $i = 0; $i <= $n - 1; $i ++)
{
$ctX = 0; $ctY = 0;
for ( $j = $i ; $j <= $n - 1; $j ++)
{
if ( $arr [ $j ] == $x )
$ctX += 1;
else if ( $arr [ $j ] == $y )
$ctY += 1;
if ( $ctX == $ctY )
$result += 1;
}
}
return ( $result );
}
$arr = array ( 1, 2, 2, 3, 4, 1 );
$n = count ( $arr );
$x = 2; $y = 3;
echo sameOccurrence( $arr , $n , $x , $y );
?>
|
Javascript
<script>
function sameOccurrence(arr, n, x, y)
{
let result = 0;
for (let i = 0; i <= n - 1; i++)
{
let ctX = 0, ctY = 0;
for (let j = i; j <= n - 1; j++)
{
if (arr[j] == x)
ctX += 1;
else if (arr[j] == y)
ctY += 1;
if (ctX == ctY)
result += 1;
}
}
return (result);
}
let arr = [ 1, 2, 2, 3, 4, 1 ];
let n = arr.length;
let x = 2, y = 3;
document.write(sameOccurrence(arr, n, x, y));
</script>
|
Time Complexity – O(N^2)
Auxiliary Space – O(1)
Efficient Approach (O(N) Time Complexity) :
In this solution, auxiliary space is O(N) and the time complexity is also O(N). We create two arrays say, countX[] and countY[], which denotes the number of occurrences of x and y, respectively, till that point in the array. Then, we evaluate another array, say diff which stores (countX[i]-countY[i]), i be the index of the array. Now, store the count of each element of array diff in a map, say m. Initialize result as m[0] since the occurrence of 0 in diff array gives us subarray count where the required condition is followed.
Now, iterate through the map and using handshake formula, update the result, since two same values in diff array indicate that the subarray contains the same number of occurrences of x and y.
Explanation:
arr[] = {1, 2, 2, 3, 4, 1};
x = 2, y = 3;
Two arrays countX[] and countY[] are be evaluated as-
countX[] = {0, 1, 2, 2, 2, 2};
countY[] = {0, 0, 0, 1, 1, 1};
Hence, diff[] = {0, 1, 2, 1, 1, 1};
(diff[i] = countX[i]-countY[i], i be the index of array)
Now, create a map and store the count of each element of diff in it,
so, finally, we get-
m[0] = 1, m[1] = 4, m[2] = 1;
Initialize result as m[0]
i.e result = m[0] = 1
Further, using handshake formula, updating the
result as follows-
result = result + (1*(1-1))/2 = 1 + 0 = 1
result = result + (4*(4-1))/2 = 1 + 6 = 7
result = result + (1*(1-1))/2 = 7 + 0 = 7
so, the final result will be 7, required subarrays having
same number of occurrences of x and y.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int sameOccurrence( int arr[], int n, int x, int y)
{
int countX[n], countY[n];
map< int , int > m;
for ( int i = 0; i < n; i++) {
if (arr[i] == x) {
if (i != 0)
countX[i] = countX[i - 1] + 1;
else
countX[i] = 1;
} else {
if (i != 0)
countX[i] = countX[i - 1];
else
countX[i] = 0;
}
if (arr[i] == y) {
if (i != 0)
countY[i] = countY[i - 1] + 1;
else
countY[i] = 1;
} else {
if (i != 0)
countY[i] = countY[i - 1];
else
countY[i] = 0;
}
m[countX[i] - countY[i]]++;
}
int result = m[0];
for ( auto it = m.begin(); it != m.end(); it++)
result = result + ((it->second) * ((it->second) - 1)) / 2;
return (result);
}
int main()
{
int arr[] = { 1, 2, 2, 3, 4, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
int x = 2, y = 3;
cout << sameOccurrence(arr, n, x, y);
return (0);
}
|
Java
import java.util.*;
class GFG
{
static int sameOccurrence( int arr[], int n, int x, int y)
{
int []countX = new int [n];
int []countY = new int [n];
Map<Integer,Integer> m = new HashMap<>();
for ( int i = 0 ; i < n; i++)
{
if (arr[i] == x)
{
if (i != 0 )
countX[i] = countX[i - 1 ] + 1 ;
else
countX[i] = 1 ;
}
else
{
if (i != 0 )
countX[i] = countX[i - 1 ];
else
countX[i] = 0 ;
}
if (arr[i] == y)
{
if (i != 0 )
countY[i] = countY[i - 1 ] + 1 ;
else
countY[i] = 1 ;
}
else
{
if (i != 0 )
countY[i] = countY[i - 1 ];
else
countY[i] = 0 ;
}
if (m.containsKey(countX[i] - countY[i]))
{
m.put(countX[i] - countY[i], m.get(countX[i] - countY[i])+ 1 );
}
else
{
m.put(countX[i] - countY[i], 1 );
}
}
int result = m.get( 0 );
for (Map.Entry<Integer,Integer> it : m.entrySet())
result = result + ((it.getValue()) * ((it.getValue()) - 1 )) / 2 ;
return (result);
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 2 , 3 , 4 , 1 };
int n = arr.length;
int x = 2 , y = 3 ;
System.out.println(sameOccurrence(arr, n, x, y));
}
}
|
Python3
def sameOccurrence( arr, n, x, y):
countX = [ 0 for i in range (n)]
countY = [ 0 for i in range (n)]
m = dict ()
for i in range (n):
if (arr[i] = = x):
if (i ! = 0 ):
countX[i] = countX[i - 1 ] + 1
else :
countX[i] = 1
else :
if (i ! = 0 ):
countX[i] = countX[i - 1 ]
else :
countX[i] = 0
if (arr[i] = = y):
if (i ! = 0 ):
countY[i] = countY[i - 1 ] + 1
else :
countY[i] = 1
else :
if (i ! = 0 ):
countY[i] = countY[i - 1 ]
else :
countY[i] = 0
m[countX[i] - countY[i]] = m.get(countX[i] -
countY[i], 0 ) + 1
result = m[ 0 ]
for j in m:
result + = (m[j] * (m[j] - 1 )) / / 2
return result
arr = [ 1 , 2 , 2 , 3 , 4 , 1 ]
n = len (arr)
x, y = 2 , 3
print (sameOccurrence(arr, n, x, y))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int sameOccurrence( int []arr, int n, int x, int y)
{
int []countX = new int [n];
int []countY = new int [n];
Dictionary< int , int > m = new Dictionary< int , int >();
for ( int i = 0; i < n; i++)
{
if (arr[i] == x)
{
if (i != 0)
countX[i] = countX[i - 1] + 1;
else
countX[i] = 1;
}
else
{
if (i != 0)
countX[i] = countX[i - 1];
else
countX[i] = 0;
}
if (arr[i] == y)
{
if (i != 0)
countY[i] = countY[i - 1] + 1;
else
countY[i] = 1;
}
else
{
if (i != 0)
countY[i] = countY[i - 1];
else
countY[i] = 0;
}
if (m.ContainsKey(countX[i] - countY[i]))
{
var v = m[countX[i] - countY[i]]+1;
m.Remove(countX[i] - countY[i]);
m.Add(countX[i] - countY[i], v);
}
else
{
m.Add(countX[i] - countY[i], 1);
}
}
int result = m[0];
foreach (KeyValuePair< int , int > it in m)
result = result + ((it.Value) * ((it.Value) - 1)) / 2;
return (result);
}
public static void Main(String[] args)
{
int []arr = { 1, 2, 2, 3, 4, 1 };
int n = arr.Length;
int x = 2, y = 3;
Console.WriteLine(sameOccurrence(arr, n, x, y));
}
}
|
Javascript
<script>
function sameOccurrence(arr,n,x,y)
{
let countX = new Array(n);
let countY = new Array(n);
let m = new Map();
for (let i = 0; i < n; i++)
{
if (arr[i] == x)
{
if (i != 0)
countX[i] = countX[i - 1] + 1;
else
countX[i] = 1;
}
else
{
if (i != 0)
countX[i] = countX[i - 1];
else
countX[i] = 0;
}
if (arr[i] == y)
{
if (i != 0)
countY[i] = countY[i - 1] + 1;
else
countY[i] = 1;
}
else
{
if (i != 0)
countY[i] = countY[i - 1];
else
countY[i] = 0;
}
if (m.has(countX[i] - countY[i]))
{
m.set(countX[i] - countY[i], m.get(countX[i] - countY[i])+1);
}
else
{
m.set(countX[i] - countY[i], 1);
}
}
let result = m.get(0);
for (let [key, value] of m.entries())
result = result + (value) * ((value) - 1) / 2;
return (result);
}
let arr=[1, 2, 2, 3, 4, 1];
let n = arr.length;
let x = 2, y = 3;
document.write(sameOccurrence(arr, n, x, y));
</script>
|
Time Complexity – O(N)
Auxiliary Space – O(N)
Similar Reads
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 = 7Output: 8Explanationn: There are 8 such subarrays i.e. {3, 6, 7},
9 min read
Count occurrences of the average of array elements with a given number
Given an array of [Tex]N [/Tex]integers and an integer [Tex]x [/Tex]. For every integer of the array a[i], the task is to calculate the count of numbers in the array with value equals to the average of element a[i] and x. That is, the number of occurrences of the (average of element a[i] and x) in t
7 min read
Count subarrays having exactly K elements occurring at least twice
Given an array arr[] consisting of N integers and a positive integer K, the task is to count the number of subarrays having exactly K elements occurring at least twice. Examples: Input: arr[] = {1, 1, 1, 2, 2}, K = 1Output: 7Explanation: The subarrays having exactly 1 element occurring at least twic
11 min read
Count non-overlapping Subarrays of size K with equal alternate elements
Given an array arr[] of length N, the task is to find the count of non-overlapping subarrays of size K such that the alternate elements are equal. Examples: Input: arr[] = {2, 4, 2, 7}, K = 3Output: 1Explanation: Given subarray {2, 4, 2} is a valid array because the elements in even position(index n
7 min read
Count of subarrays which contains a given number exactly K times
Given an array A[] of N elements consisting of values from 1 to N with duplicates, the task is to find the total number of subarrays that contain a given number num exactly K times. Examples: Input: A[] = {1, 2, 1, 5, 1}, num = 1, K = 2 Output: 2 Explanation: Subarrays {1, 2, 1, 5}, {1, 2, 1}, {2, 1
8 min read
Count subarrays with equal number of 1's and 0's
Given an array arr[] of size n containing 0 and 1 only. The problem is to count the subarrays having an equal number of 0's and 1's. Examples: Input: arr[] = {1, 0, 0, 1, 0, 1, 1}Output: 8Explanation: The index range for the 8 sub-arrays are: (0, 1), (2, 3), (0, 3), (3, 4), (4, 5)(2, 5), (0, 5), (1,
14 min read
Count subarrays having sum of elements at even and odd positions equal
Given an array arr[] of integers, the task is to find the total count of subarrays such that the sum of elements at even position and sum of elements at the odd positions are equal. Examples: Input: arr[] = {1, 2, 3, 4, 1}Output: 1Explanation: {3, 4, 1} is the only subarray in which sum of elements
7 min read
Count of index pairs with equal elements in an array | Set 2
Given an array arr[] of N elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i != j Examples: Input: arr[]={1, 2, 1, 1}Output: 3 Explanation:In the array arr[0]=arr[2]=arr[3]Valid Pairs are (0, 2), (0, 3) and (2, 3) Input: arr[]={2, 2, 3, 2, 3}Output: 4Ex
8 min read
Count number of occurrences (or frequency) in a sorted array
Given a sorted array arr[] and an integer target, the task is to find the number of occurrences of target in given array. Examples: Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 2Output: 4Explanation: 2 occurs 4 times in the given array. Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 4Output: 0Expl
9 min read
Count sub-arrays which have elements less than or equal to X
Given an array of n elements and an integer X. Count the number of sub-arrays of this array which have all elements less than or equal to X. Examples: Input : arr[] = {1, 5, 7, 8, 2, 3, 9} X = 6 Output : 6 Explanation : Sub-arrays are {1}, {5}, {2}, {3}, {1, 5}, {2, 3} Input : arr[] = {1, 10, 12, 4,
15 min read