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;
// Function to find the total number of elements that have
// frequency 1 in a subarray of the given array
int findElementsWithFrequencyOne(int arr[], int N)
{
// variable to store the total number of elements with
// frequency 1
int count = 0;
// iterate through all possible subarrays of the given
// array
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
// unordered_map to store element frequencies
unordered_map<int, int> unmap;
// iterate through all elements in the current
// subarray and increment their frequencies in
// the unordered_map
for (int k = i; k <= j; k++) {
unmap[arr[k]]++;
}
// iterate through all elements in the
// unordered_map and check if their frequency is
// equal to 1
for (auto it : unmap) {
if (it.second == 1) {
count++;
}
}
}
}
return count;
}
// Driver Code
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)
{
// variable to store the total number of elements
// with frequency 1
int count = 0;
// iterate through all possible subarrays of the
// given array
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
// HashMap to store element frequencies
HashMap<Integer, Integer> hmap
= new HashMap<>();
// iterate through all elements in the
// current subarray and increment their
// frequencies in the 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);
}
}
// iterate through all elements in the
// HashMap and check if their frequency is
// equal to 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
# Function to find the total number of elements that have
# frequency 1 in a subarray of the given array
def findElementsWithFrequencyOne(arr, N):
# variable to store the total number of elements with
# frequency 1
count = 0;
# iterate through all possible subarrays of the given
# array
for i in range(0,N):
for j in range(i,N):
# unordered_map to store element frequencies
unmap={};
# iterate through all elements in the current
# subarray and increment their frequencies in
# the unordered_map
for k in range(i,j+1):
if (arr[k] not in unmap):
unmap[arr[k]] = 1;
else:
unmap[arr[k]] += 1;
# iterate through all elements in the
# unordered_map and check if their frequency is
# equal to 1
for it in unmap:
if (unmap[it] == 1):
count += 1;
return count;
# Driver Code
arr = [ 2, 4, 2 ];
N = len(arr);
print(findElementsWithFrequencyOne(arr, N));
# This code is contributed by ratiagarwal.
C#
// C# code for the above approach
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
// Function to find the total number of elements that have
// frequency 1 in a subarray of the given array
static int findElementsWithFrequencyOne(int[] arr, int N)
{
// variable to store the total number of elements with
// frequency 1
int count = 0;
// iterate through all possible subarrays of the given
// array
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
// unordered_map to store element frequencies
Dictionary<int, int> unmap=new Dictionary<int, int>();
// iterate through all elements in the current
// subarray and increment their frequencies in
// the unordered_map
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);
}
}
// iterate through all elements in the
// unordered_map and check if their frequency is
// equal to 1
foreach(KeyValuePair<int, int> entry in unmap){
if (entry.Value == 1) {
count++;
}
}
}
}
return count;
}
// Driver Code
static public void Main()
{
int[] arr = { 2, 4, 2 };
int N = arr.Length;
Console.Write(findElementsWithFrequencyOne(arr, N));
}
}
JavaScript
// Function to find the total number of elements that have
// frequency 1 in a subarray of the given array
function findElementsWithFrequencyOne(arr, N)
{
// variable to store the total number of elements with
// frequency 1
let count = 0;
// iterate through all possible subarrays of the given
// array
for (let i = 0; i < N; i++) {
for (let j = i; j < N; j++) {
// unordered_map to store element frequencies
let unmap=new Map();
// iterate through all elements in the current
// subarray and increment their frequencies in
// the unordered_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);
}
// iterate through all elements in the
// unordered_map and check if their frequency is
// equal to 1
for (let it of unmap) {
if (it[1] == 1) {
count++;
}
}
}
}
return count;
}
// Driver Code
let arr = [ 2, 4, 2 ];
let N = arr.length;
console.log(findElementsWithFrequencyOne(arr, N));
// This code is contributed by poojaagarwal2.
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++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the total number of elements
// having frequency 1 in a subarray
int calcBeauty(int n, vector<int> arr)
{
unordered_map<int, vector<int> > mp;
// Loop to store the occurrence of each element
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;
// Loop to find the contribution of each element
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 the answer
return ans;
}
// Driver code
int main()
{
vector<int> arr = { 2, 4, 2 };
int N = arr.size();
// Function call
cout << calcBeauty(N, arr);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
import java.util.*;
class GFG {
static int calcBeauty(int n, int[] arr)
{
HashMap<Integer, List<Integer> > mp
= new HashMap<>();
// Loop to store the occurrence of each element
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;
// Loop to find the contribution of each element
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 the answer
return ans;
}
public static void main(String[] args)
{
int[] arr = { 2, 4, 2 };
int N = arr.length;
// Function call
System.out.print(calcBeauty(N, arr));
}
}
// This code is contributed by lokeshmvs21.
Python3
# python3 code to implement the approach
# Function to calculate the total number of elements
# having frequency 1 in a subarray
def calcBeauty(n, arr):
mp = {}
# Loop to store the occurrence of each element
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
# Loop to find the contribution of each element
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 the answer
return ans
# Driver code
if __name__ == "__main__":
arr = [2, 4, 2]
N = len(arr)
# Function call
print(calcBeauty(N, arr))
# This code is contributed by rakeshsahni
JavaScript
<script>
// JavaScript code for the above approach
// Function to calculate the total number of elements
// having frequency 1 in a subarray
function calcBeauty(n, arr) {
let mp = new Map();
// Loop to store the occurrence of each element
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;
// Loop to find the contribution of each element
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 the answer
return ans;
}
// Driver code
let arr = [2, 4, 2];
let N = arr.length;
// Function call
document.write(calcBeauty(N, arr));
// This code is contributed by Potta Lokesh
</script>
C#
//C# implementation
using System;
using System.Collections.Generic;
public class GFG
{
// Function to calculate the total number of elements
// having frequency 1 in a subarray
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>());
}
// Loop to store the occurrence of each element
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;
// Loop to find the contribution of each element
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 the answer
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;
// Function call
Console.WriteLine(calcBeauty(N, arr));
}
}
//this code is contributed by ksam24000
PHP
<?php
// Function to calculate the total number of elements
// having frequency 1 in a subarray
function calcBeauty($n, $arr)
{
$mp = array();
// Loop to store the occurrence of each element
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;
// Loop to find the contribution of each element
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 the answer
return $ans;
}
// Driver code
$arr = array(2, 4, 2);
$N = count($arr);
// Function call
echo calcBeauty($N, $arr);
// This code is contributed by Kanishka Gupta
?>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Count of subarrays of size K with elements having even frequencies
Given an array arr[] and an integer K, the task is to count subarrays of size K in which every element appears an even number of times in the subarray. Examples: Input: arr[] = {1, 4, 2, 10, 2, 10, 0, 20}, K = 4 Output: 1 Explanation: Only subarray {2, 10, 2, 10} satisfies the required condition. In
9 min read
Largest subarray with frequency of all elements same
Given an array arr[] of N integers, the task is to find the size of the largest subarray with frequency of all elements the same. Examples: Input: arr[] = {1, 2, 2, 5, 6, 5, 6} Output: 6 Explanation: The subarray = {2, 2, 5, 6, 5, 6} has frequency of every element is 2. Input: arr[] = {1, 1, 1, 1, 1
15+ min read
Count the elements having frequency equals to its value
Given an array of integers arr[] of size N, the task is to count all the elements of the array which have a frequency equals to its value. Examples: Input: arr[] = {3, 2, 2, 3, 4, 3} Output: 2 Frequency of element 2 is 2 Frequency of element 3 is 3 Frequency of element 4 is 1 2 and 3 are elements wh
14 min read
Count subarrays made up of elements having exactly K set bits
Given an array arr[] consisting of N integers and an integer K, the task is to count the number of subarrays possible consisting of elements having exactly K set bits. Examples: Input: arr[] = {4, 2, 1, 5, 6}, K = 2Output: 3Explanation: The subarrays made up of elements having exactly 2 set bits are
7 min read
Count the elements having frequency equals to its value | Set 2
Given an array of integers arr[] of size N, the task is to count all the elements of the array which have a frequency equals to its value.Examples: Input: arr[] = {3, 2, 2, 3, 4, 3} Output: 2 Explanation : Frequency of element 2 is 2 Frequency of element 3 is 3 Frequency of element 4 is 1 2 and 3 ar
5 min read
Length of longest subarray having frequency of every element equal to K
Given an array arr[] consisting of N integers and an integer K, the task is to find the length of the longest subarray such that each element occurs K times. Examples: Input: arr[] = {3, 5, 2, 2, 4, 6, 4, 6, 5}, K = 2Output: 8Explanation: The subarray: {5, 2, 2, 4, 6, 4, 6, 5} of length 8 has freque
9 min read
Count subarrays having total distinct elements same as original array
Given an array of n integers. Count the total number of sub-arrays having total distinct elements, the same as that of the total distinct elements of the original array. Examples: Input : arr[] = {2, 1, 3, 2, 3} Output : 5 Total distinct elements in array is 3 Total sub-arrays that satisfy the condi
11 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 of subarrays with X as the most frequent element, for each value of X from 1 to N
Given an array arr[] of size N, (where 0<A[i]<=N, for all 0<=i<N), the task is to calculate for each number X from 1 to N, the number of subarrays in which X is the most frequent element. In subarrays, where more than one element has the maximum frequency, the smallest element should be
7 min read
Smallest subarray having an element with frequency greater than that of other elements
Given an array arr of positive integers, the task is to find the smallest length subarray of length more than 1 having an element occurring more times than any other element. Examples: Input: arr[] = {2, 3, 2, 4, 5} Output: 2 3 2 Explanation: The subarray {2, 3, 2} has an element 2 which occurs more
15+ min read