Total count of elements having frequency one in each Subarray
Last Updated :
03 Feb, 2023
Given an array arr[] of length N, the task is to find the total number of elements that has frequency 1 in a subarray of the given array.
Examples:
Input: N = 3, arr[ ] = {2, 4, 2}
Output: 8
Explanation: All possible subarrays are
{2}: elements with frequency one = 1.
{4}: elements with frequency one = 1.
{2}: elements with frequency one = 1.
{2, 4}: elements with frequency one = 2.
{4, 2}: elements with frequency one = 2.
{2, 4, 2}: elements with frequency one = 1 (i.e., only for 4).
Total count of elements = 1 + 1 + 1 + 2 + 2 + 1 = 8.
Input: N = 2, arr[ ] = {1, 1}
Output: 2
Explanation: All possible subarrays are
{1}: elements with frequency one = 1.
{1, 1}: elements with frequency one = 0.
{1}: elements with frequency one = 1.
Total count of elements = 1 + 0 + 1 = 2.
Naive Approach: The simple idea is to calculate all the possible subarrays and for each subarray count the number of elements that are present only once in that subarray and add that count to the final answer.
- Initialize a variable count to 0. This variable will be used to store the total number of elements that have frequency 1 in a subarray of the given array.
- Iterate through all possible subarrays of the given array. For each subarray, do the following:
- Create an unordered_map to store the frequency of each element in the subarray.
- Iterate through all elements in the subarray. For each element, increment its frequency in the unordered_map.
- Iterate through all elements in the unordered_map and check if their frequency is equal to 1. If so, increment the count variable by 1.
- Return the value of count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findElementsWithFrequencyOne( int arr[], int N)
{
int count = 0;
for ( int i = 0; i < N; i++) {
for ( int j = i; j < N; j++) {
unordered_map< int , int > unmap;
for ( int k = i; k <= j; k++) {
unmap[arr[k]]++;
}
for ( auto it : unmap) {
if (it.second == 1) {
count++;
}
}
}
}
return count;
}
int main()
{
int arr[] = { 2, 4, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << findElementsWithFrequencyOne(arr, N);
return 0;
}
|
Java
import java.util.HashMap;
public class Gfg {
public static int
findElementsWithFrequencyOne( int [] arr, int N)
{
int count = 0 ;
for ( int i = 0 ; i < N; i++) {
for ( int j = i; j < N; j++) {
HashMap<Integer, Integer> hmap
= new HashMap<>();
for ( int k = i; k <= j; k++) {
if (hmap.containsKey(arr[k])) {
hmap.put(arr[k],
hmap.get(arr[k]) + 1 );
}
else {
hmap.put(arr[k], 1 );
}
}
for ( int key : hmap.keySet()) {
if (hmap.get(key) == 1 ) {
count++;
}
}
}
}
return count;
}
public static void main(String[] args)
{
int [] arr = { 2 , 4 , 2 };
int N = arr.length;
System.out.println(
findElementsWithFrequencyOne(arr, N));
}
}
|
Python3
def findElementsWithFrequencyOne(arr, N):
count = 0 ;
for i in range ( 0 ,N):
for j in range (i,N):
unmap = {};
for k in range (i,j + 1 ):
if (arr[k] not in unmap):
unmap[arr[k]] = 1 ;
else :
unmap[arr[k]] + = 1 ;
for it in unmap:
if (unmap[it] = = 1 ):
count + = 1 ;
return count;
arr = [ 2 , 4 , 2 ];
N = len (arr);
print (findElementsWithFrequencyOne(arr, N));
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
static int findElementsWithFrequencyOne( int [] arr, int N)
{
int count = 0;
for ( int i = 0; i < N; i++) {
for ( int j = i; j < N; j++) {
Dictionary< int , int > unmap= new Dictionary< int , int >();
for ( int k = i; k <= j; k++)
{
if (unmap.ContainsKey(arr[k]))
{
var val = unmap[arr[k]];
unmap.Remove(arr[k]);
unmap.Add(arr[k], val + 1);
}
else
{
unmap.Add(arr[k], 1);
}
}
foreach (KeyValuePair< int , int > entry in unmap){
if (entry.Value == 1) {
count++;
}
}
}
}
return count;
}
static public void Main()
{
int [] arr = { 2, 4, 2 };
int N = arr.Length;
Console.Write(findElementsWithFrequencyOne(arr, N));
}
}
|
Javascript
function findElementsWithFrequencyOne(arr, N)
{
let count = 0;
for (let i = 0; i < N; i++) {
for (let j = i; j < N; j++) {
let unmap= new Map();
for (let k = i; k <= j; k++) {
if (unmap.has(arr[k]))
unmap.set(arr[k], unmap.get(arr[k])+1);
else
unmap.set(arr[k], 1);
}
for (let it of unmap) {
if (it[1] == 1) {
count++;
}
}
}
}
return count;
}
let arr = [ 2, 4, 2 ];
let N = arr.length;
console.log(findElementsWithFrequencyOne(arr, N));
|
Time Complexity: O(N3)
Auxiliary Space: O(N)
Efficient Approach: For the above approach, we will run out of time if the size of the array is very large. Therefore we have to optimize it. We can efficiently calculate the answer using Hashing based on the below idea:
Here we will evaluate the contribution done by each element to the final count.
Say an element at index i has two other occurrences at jth and kth index (j < i < k). In this case, the element at ith index has (i – j) * (k – i) number of choices to form a subarray where it is present only once.
Proof:
The ith element can have (i – j) elements from its left [including itself] in any of the subarray where arr[i] has frequency 1.
Similarly, it can have (k – i) elements from its right [including itself] in any of the subarray satisfying the above condition.
So, from the basic principle of counting, we can see the total number of possible subarrays where arr[i] has frequency 1 is (i – j) * (k – i).
Follow the steps mentioned below to implement the idea:
- Initialize a map (say mp) to store the indices of occurrences of any element.
- Iterate through the array from i = 0 to N-1:
- If arr[i] is arriving for the first time then insert -1 first. (because -1 will denote the first occurrence for ease of calculation)
- Insert i in mp[arr[i]].
- Again for ease of calculation insert N at the end of each entry of the map.
- Now traverse through each element of the map and use the above formula to calculate the contribution of the element present in each index.
- Return the final count as the required answer.
Below is the implementation of the above idea.
C++
#include <bits/stdc++.h>
using namespace std;
int calcBeauty( int n, vector< int > arr)
{
unordered_map< int , vector< int > > mp;
for ( int i = 0; i < n; i++) {
if (mp.count(arr[i]) == 0)
mp[arr[i]].push_back(-1);
mp[arr[i]].push_back(i);
}
for ( auto it : mp)
mp[it.first].push_back(n);
int ans = 0;
for ( auto it : mp) {
vector< int > ls = it.second;
for ( int i = 1; i < ls.size() - 1; i++) {
int left = ls[i] - ls[i - 1];
int right = ls[i + 1] - ls[i];
ans = ans + (left * right);
}
}
return ans;
}
int main()
{
vector< int > arr = { 2, 4, 2 };
int N = arr.size();
cout << calcBeauty(N, arr);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int calcBeauty( int n, int [] arr)
{
HashMap<Integer, List<Integer> > mp
= new HashMap<>();
for ( int i = 0 ; i < n; i++) {
List<Integer> temp = new ArrayList<>();
if (!mp.containsKey(arr[i])) {
temp.add(- 1 );
mp.put(arr[i], temp);
}
temp = mp.get(arr[i]);
temp.add(i);
mp.put(arr[i], temp);
}
for (Map.Entry<Integer, List<Integer> > it :
mp.entrySet()) {
List<Integer> temp = it.getValue();
temp.add(n);
}
int ans = 0 ;
for (Map.Entry<Integer, List<Integer> > it :
mp.entrySet()) {
List<Integer> ls = it.getValue();
for ( int i = 1 ; i < ls.size() - 1 ; i++) {
int left = ls.get(i) - ls.get(i - 1 );
int right = ls.get(i + 1 ) - ls.get(i);
ans = ans + (left * right);
}
}
return ans;
}
public static void main(String[] args)
{
int [] arr = { 2 , 4 , 2 };
int N = arr.length;
System.out.print(calcBeauty(N, arr));
}
}
|
Python3
def calcBeauty(n, arr):
mp = {}
for i in range ( 0 , n):
if (arr[i] not in mp):
mp[arr[i]] = [ - 1 ]
mp[arr[i]].append(i)
for it in mp:
mp[it].append(n)
ans = 0
for it in mp:
ls = mp[it]
for i in range ( 1 , len (ls) - 1 ):
left = ls[i] - ls[i - 1 ]
right = ls[i + 1 ] - ls[i]
ans = ans + (left * right)
return ans
if __name__ = = "__main__" :
arr = [ 2 , 4 , 2 ]
N = len (arr)
print (calcBeauty(N, arr))
|
Javascript
<script>
function calcBeauty(n, arr) {
let mp = new Map();
for (let i = 0; i < n; i++) {
if (mp.has(arr[i]) == 0)
mp.set(arr[i], [-1]);
mp.get(arr[i]).push(i);
}
for (let [key, val] of mp)
mp.get(key).push(n);
let ans = 0;
for (let [key, val] of mp) {
let ls = val;
for (let i = 1; i < ls.length - 1; i++) {
let left = ls[i] - ls[i - 1];
let right = ls[i + 1] - ls[i];
ans = ans + (left * right);
}
}
return ans;
}
let arr = [2, 4, 2];
let N = arr.length;
document.write(calcBeauty(N, arr));
</script>
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
public static int calcBeauty( int n, List< int > arr)
{
Dictionary< int ,List< int >> mp = new Dictionary< int ,List< int >>();
for ( int i=0;i<100;i++)
{
mp.Add(i, new List< int >());
}
for ( int i = 0; i < n; i++) {
if (mp[arr[i]].Count == 0)
mp[arr[i]].Add(-1);
mp[arr[i]].Add(i);
}
foreach (KeyValuePair< int , List< int >> ele in mp)
{
ele.Value.Add(n);
}
int ans = 0;
foreach (KeyValuePair< int , List< int >> ele in mp)
{
List< int > ls = new List< int >();
ls = ele.Value;
for ( int i = 1; i < ls.Count - 1; i++) {
int left = ls[i] - ls[i - 1];
int right = ls[i + 1] - ls[i];
ans = ans + (left * right);
}
}
return ans;
}
public static void Main( string [] args)
{
List< int > arr = new List< int >();
arr.Add(2);
arr.Add(4);
arr.Add(2);
int N = arr.Count;
Console.WriteLine(calcBeauty(N, arr));
}
}
|
PHP
<?php
function calcBeauty( $n , $arr )
{
$mp = array ();
for ( $i = 0; $i < $n ; $i ++) {
if (! array_key_exists ( $arr [ $i ], $mp ))
$mp [ $arr [ $i ]] = array (-1);
array_push ( $mp [ $arr [ $i ]], $i );
}
foreach ( $mp as $key => $value )
array_push ( $mp [ $key ], $n );
$ans = 0;
foreach ( $mp as $key => $value ) {
$ls = $value ;
for ( $i = 1; $i < count ( $ls ) - 1; $i ++) {
$left = $ls [ $i ] - $ls [ $i - 1];
$right = $ls [ $i + 1] - $ls [ $i ];
$ans = $ans + ( $left * $right );
}
}
return $ans ;
}
$arr = array (2, 4, 2);
$N = count ( $arr );
echo calcBeauty( $N , $arr );
?>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...