Open In App

Total count of elements having frequency one in each Subarray

Last Updated : 03 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Output

8

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
?>


Output

8

Time Complexity: O(N)
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads