Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Difference of count of distinct elements present to left and right for each array element

  • Last Updated : 19 Nov, 2021

Given an array arr[] consisting of N integers, the task for each array element is to find the absolute difference between the count of distinct elements to the left and the right of it in the given array arr[].

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {7, 7, 3, 2, 3}
Output: 2 2 0 1 2
Explanation:
Count of distinct elements that occur to the left of every index is given by [0, 0, 1, 1, 2] and the number of distinct elements that occur to the right of every index is [2, 2, 1, 0, 0]. Taking absolute difference of both gives the above output.



Input: arr[] = {4, 3, 2, 3}
Output: 2 0 1 2

 

Naive Approach: The given problem can be solved using the Set Data Structure, the idea is to iterate over the range [0, i – 1] to find the count of distinct elements on the left of every element and similarly traverse the array over the range [i + 1, N – 1] to find the distinct elements on the right of every element. Follow the steps below to solve the given problem:

  • Initialize an array res[] that stores the resultant absolute difference of distinct elements for each array element.
  • Traverse the given array and for every element at index i perform the following operations:
    • Iterate over the range [0, i – 1] and insert all the elements in the set, say S1.
    • Iterate over the range [i  + 1, N – 1] and insert all the elements in the set, say S2.
    • Update the value of res[i] as the absolute difference of sizes of sets S1 and S2.
  • After completing the above steps, print the array res[] as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;
 
// Function to find the difference of
// count of distince elements to the
// left and right for each array elements
void findDifferenceArray(int arr[], int N)
{
 
    // Stores distinct array element
    // in the left and right
    set<int> S1;
    set<int> S2;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Insert all element to the left
        // in the set S1
        for (int j = 0; j < i; j++) {
            S1.insert(arr[j]);
        }
 
        // Insert all element to the right
        // in the set S2
        for (int j = i + 1; j < N; j++) {
            S2.insert(arr[j]);
        }
 
        // Print the difference
        cout << abs((int)S1.size()
                    - (int)S2.size())
             << ' ';
 
        S1.clear();
        S2.clear();
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 7, 7, 3, 2, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    findDifferenceArray(arr, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.HashSet;
class GFG{
 
// Function to find the difference of
// count of distince elements to the
// left and right for each array elements
public static void findDifferenceArray(int arr[], int N)
{
 
    // Stores distinct array element
    // in the left and right
    HashSet<Integer> S1 = new HashSet<Integer>();
    HashSet<Integer> S2 = new HashSet<Integer>();
     
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Insert all element to the left
        // in the set S1
        for (int j = 0; j < i; j++) {
            S1.add(arr[j]);
        }
 
        // Insert all element to the right
        // in the set S2
        for (int j = i + 1; j < N; j++) {
            S2.add(arr[j]);
        }
 
        // Print the difference
        System.out.print(Math.abs(S1.size() - S2.size()) + " ");
 
        S1.clear();
        S2.clear();
    }
}
 
// Driver Code
public static void main(String args[])
{
    int arr[] = { 7, 7, 3, 2, 3 };
    int N = arr.length;
    findDifferenceArray(arr, N);
}
}
 
// This code is contributed by gfgking.

Python3




# Python3 program for the above approach
 
# Function to find the difference of
# count of distince elements to the
# left and right for each array elements
def findDifferenceArray(arr, N) :
 
    # Stores distinct array element
    # in the left and right
    S1 = set();
    S2 = set();
 
    # Traverse the array
    for i in range(N) :
 
        # Insert all element to the left
        # in the set S1
        for j in range(i) :
            S1.add(arr[j]);
 
        # Insert all element to the right
        # in the set S2
        for j in range(i + 1, N) :
            S2.add(arr[j]);
     
        # Print the difference
        print(abs(len(S1) - len(S2)),end=' ');
 
        S1.clear();
        S2.clear();
 
# Driver Code
if __name__ == "__main__" :
     
    arr = [ 7, 7, 3, 2, 3 ];
    N = len(arr);
    findDifferenceArray(arr, N);
     
    # This code is contributed by AnkThon

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG
{
 
// Function to find the difference of
// count of distince elements to the
// left and right for each array elements
public static void findDifferenceArray(int[] arr, int N)
{
 
    // Stores distinct array element
    // in the left and right
    HashSet<int> S1 = new HashSet<int>();
    HashSet<int> S2 = new HashSet<int>();
     
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Insert all element to the left
        // in the set S1
        for (int j = 0; j < i; j++) {
            S1.Add(arr[j]);
        }
 
        // Insert all element to the right
        // in the set S2
        for (int j = i + 1; j < N; j++) {
            S2.Add(arr[j]);
        }
 
        // Print the difference
        Console.Write(Math.Abs(S1.Count - S2.Count) + " ");
 
        S1.Clear();
        S2.Clear();
    }
}
  
// Driver code
public static void Main(String[] args)
{
    int[] arr = { 7, 7, 3, 2, 3 };
    int N = arr.Length;
    findDifferenceArray(arr, N);
}
}
 
// This code is contributed by sanjoy_62.

Javascript




<script>
        // JavaScript Program to implement
        // the above approach
 
        // Function to find the difference of
        // count of distince elements to the
        // left and right for each array elements
        function findDifferenceArray(arr, N) {
 
            // Stores distinct array element
            // in the left and right
            let S1 = new Set();
            let S2 = new Set();
 
            // Traverse the array
            for (let i = 0; i < N; i++) {
 
                // Insert all element to the left
                // in the set S1
                for (let j = 0; j < i; j++) {
                    S1.add(arr[j]);
                }
 
                // Insert all element to the right
                // in the set S2
                for (let j = i + 1; j < N; j++) {
                    S2.add(arr[j]);
                }
 
                // Print the difference
                document.write(Math.abs(S1.size
                    - S2.size)
                    + ' ');
 
                S1.clear();
                S2.clear();
            }
        }
 
        // Driver Code
 
        let arr = [7, 7, 3, 2, 3];
        let N = arr.length;
        findDifferenceArray(arr, N);
 
// This code is contributed by Potta Lokesh
    </script>

 
 

Output: 
3 1 1 1 3

 

 

Time Complexity: O((N2)*log N)
Auxiliary Space: O(N)

 

Efficient Approach: The above approach can also be optimized by storing the frequency of distinct elements on the left and the right for each array element and then find the resultant difference for each array element. Follow the steps below to solve the given problem:



 

  • Initialize two unordered_map leftMap and rightMap to store the distinct elements on the left and right of every index respectively.
  • Traverse the given array and insert all the array elements in the rightMap.
  • Traverse the given array using the variable i and perform the following steps:
    • Count distinct elements to the left of the current element(say countLeft) as the size of the map leftMap.
    • Decrement the frequency of the current element from the map rightMap by 1.
    • Count distinct elements to the right of the current element(say countRight) as the size of the map rightMap.
    • Increment the frequency of the current element in the map leftMap by 1.
    • Insert the value of the absolute difference of sizes of maps leftMap and rightMap.
  • After completing the above steps, print the array res[] as the result.

 

Below is the implementation of the above approach:

 

C++




// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;
 
// Function to find the difference of
// count of distince elements to the
// left and right for each array elements
void findDifferenceArray(int arr[], int N)
{
 
    // Stores the frequency of array
    // element to the left and the right
    unordered_map<int, int> leftMap, rightMap;
 
    // Stores the frequency of array
    // element in the map rightMap
    for (int i = 0; i < N; i++) {
        rightMap[arr[i]]++;
    }
 
    // Stores the resultant differences
    vector<int> res;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Find the count in the left
        int countLeft = leftMap.size();
 
        // Decrement the frequency
        if (rightMap[arr[i]] > 1) {
            rightMap[arr[i]]--;
        }
        else {
            rightMap.erase(arr[i]);
        }
 
        // Find the count in the left
        int countRight = rightMap.size();
 
        // Insert the resultant difference
        res.push_back(abs(countRight - countLeft));
 
        // Increment the frequency
        leftMap[arr[i]]++;
    }
 
    // Print the result
    for (auto& it : res) {
        cout << it << ' ';
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 7, 7, 3, 2, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    findDifferenceArray(arr, N);
 
    return 0;
}

 
 

Output: 
3 1 1 1 3

 

 

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

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!