Total count of elements having frequency one in each Subarray
Last Updated :
23 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem