Open In App

Find the difference of count of equal elements on the right and the left for each element

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N. The task is to find X – Y for each of the element where X is the count of j such that arr[i] = arr[j] and j > i. Y is the count of j such that arr[i] = arr[j] and j < i.
Examples: 
 

Input: arr[] = {1, 2, 3, 2, 1} 
Output: 1 1 0 -1 -1 
For index 0, X – Y = 1 – 0 = 1 
For index 1, X – Y = 1 – 0 = 1 
For index 2, X – Y = 0 – 0 = 0 
For index 3, X – Y = 0 – 1 = -1 
For index 4, X – Y = 0 – 1 = -1
Input: arr[] = {1, 1, 1, 1, 1} 
Output: 4 2 0 -2 -4 
 

 

Brute Force Approach:

Brute force approach to solve this problem would be to use nested loops to count the number of elements to the right and left of each element that are equal to it. For each element, we can initialize two counters, one for counting the number of equal elements to the right and the other for counting the number of equal elements to the left. Then we can use nested loops to traverse the array and count the number of equal elements to the right and left of each element. Finally, we can subtract the two counts to get the required result.

  • Iterate over the array using a for loop starting from index 0 to index n-1.
  • For each element at index i, initialize the variables ‘right_count’ and ‘left_count’ to 0.
  • Use another for loop to iterate over the elements from i+1 to n-1 to count the number of elements to the right of i that are equal to a[i]. Increment ‘right_count’ for each such element.
  • Use another for loop to iterate over the elements from i-1 to 0 to count the number of elements to the left of i that are equal to a[i]. Increment ‘left_count’ for each such element.
  • Calculate the difference between ‘right_count’ and ‘left_count’ for each i.

Below is the implementation of the above approach:

C++




// C++ implementation of the brute force approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the count of equal
// elements to the right - count of equal
// elements to the left for each of the element
void right_left(int a[], int n)
{
    for(int i=0; i<n; i++) {
        int right_count = 0, left_count = 0;
        for(int j=i+1; j<n; j++) {
            if(a[i] == a[j]) {
                right_count++;
            }
        }
        for(int j=i-1; j>=0; j--) {
            if(a[i] == a[j]) {
                left_count++;
            }
        }
        cout << right_count - left_count << " ";
    }
}
 
// Driver code
int main()
{
    int a[] = { 1, 2, 3, 2, 1 };
    int n = sizeof(a) / sizeof(a[0]);
 
    right_left(a, n);
 
    return 0;
}


Java




import java.util.*;
 
public class GFG {
    // Function to find the count of equal elements to the right
    // minus the count of equal elements to the left for each element
    static void rightLeft(int[] a, int n) {
        for (int i = 0; i < n; i++) {
            int rightCount = 0, leftCount = 0;
             
            // Count equal elements to the right
            for (int j = i + 1; j < n; j++) {
                if (a[i] == a[j]) {
                    rightCount++;
                }
            }
             
            // Count equal elements to the left
            for (int j = i - 1; j >= 0; j--) {
                if (a[i] == a[j]) {
                    leftCount++;
                }
            }
            System.out.print(rightCount - leftCount + " ");
        }
    }
 
    public static void main(String[] args) {
        int[] a = { 1, 2, 3, 2, 1 };
        int n = a.length;
 
        rightLeft(a, n);
    }
}


Python




# Function to find the count of equal elements to the right
# minus the count of equal elements to the left for each element
 
 
def right_left_counts(arr):
    n = len(arr)
    result = []
 
    for i in range(n):
        right_count = 0
        left_count = 0
 
        # Count equal elements to the right
        for j in range(i + 1, n):
            if arr[i] == arr[j]:
                right_count += 1
 
        # Count equal elements to the left
        for j in range(i - 1, -1, -1):
            if arr[i] == arr[j]:
                left_count += 1
 
        result.append(right_count - left_count)
 
    return result
 
 
# Driver code
if __name__ == "__main__":
    arr = [1, 2, 3, 2, 1]
    result = right_left_counts(arr)
    print(result)


C#




using System;
 
public class GFG {
    // Function to find the count of equal elements to the
    // right minus the count of equal elements to the left
    // for each element
    static void RightLeft(int[] a, int n)
    {
        for (int i = 0; i < n; i++) {
            int rightCount = 0, leftCount = 0;
 
            // Count equal elements to the right
            for (int j = i + 1; j < n; j++) {
                if (a[i] == a[j]) {
                    rightCount++;
                }
            }
 
            // Count equal elements to the left
            for (int j = i - 1; j >= 0; j--) {
                if (a[i] == a[j]) {
                    leftCount++;
                }
            }
            Console.Write(rightCount - leftCount + " ");
        }
    }
 
    public static void Main(string[] args)
    {
        int[] a = { 1, 2, 3, 2, 1 };
        int n = a.Length;
 
        RightLeft(a, n);
    }
}


Javascript




// Function to find the count of equal
// elements to the right - count of equal
// elements to the left for each of the element
function rightLeft(arr) {
    const n = arr.length;
    for (let i = 0; i < n; i++) {
        let rightCount = 0, leftCount = 0;
         
        // Count equal elements to the right
        for (let j = i + 1; j < n; j++) {
            if (arr[i] === arr[j]) {
                rightCount++;
            }
        }
         
        // Count equal elements to the left
        for (let j = i - 1; j >= 0; j--) {
            if (arr[i] === arr[j]) {
                leftCount++;
            }
        }
 
        // Print the result
        console.log(rightCount - leftCount);
    }
}
 
// Driver code
const arr = [1, 2, 3, 2, 1];
rightLeft(arr);


Output

1 1 0 -1 -1 





Time Complexity: O(n^2) because it uses two nested loops to count the equal elements to the right and left of each element.
Space Complexity: O(1), as we are not using extra space.

Approach: An efficient approach is to use a map. One map is to store the count of each element in the array and another map to count the number of same elements left to each element.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the count of equal
// elements to the right - count of equal
// elements to the left for each of the element
void right_left(int a[], int n)
{
 
    // Maps to store the frequency and same
    // elements to the left of an element
    unordered_map<int, int> total, left;
 
    // Count the frequency of each element
    for (int i = 0; i < n; i++)
        total[a[i]]++;
 
    for (int i = 0; i < n; i++) {
 
        // Print the answer for each element
        cout << (total[a[i]] - 1 - (2 * left[a[i]])) << " ";
 
        // Increment it's left frequency
        left[a[i]]++;
    }
}
 
// Driver code
int main()
{
    int a[] = { 1, 2, 3, 2, 1 };
    int n = sizeof(a) / sizeof(a[0]);
 
    right_left(a, n);
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function to find the count of equal
// elements to the right - count of equal
// elements to the left for each of the element
static void right_left(int a[], int n)
{
 
    // Maps to store the frequency and same
    // elements to the left of an element
    Map<Integer, Integer> total = new HashMap<>();
    Map<Integer, Integer> left = new HashMap<>();
 
    // Count the frequency of each element
    for (int i = 0; i < n; i++)
        total.put(a[i],
        total.get(a[i]) == null ? 1 :
        total.get(a[i]) + 1);
 
    for (int i = 0; i < n; i++)
    {
 
        // Print the answer for each element
        System.out.print((total.get(a[i]) - 1 -
                         (2 * (left.containsKey(a[i]) == true ?
                               left.get(a[i]) : 0))) + " ");
 
        // Increment it's left frequency
        left.put(a[i],
        left.get(a[i]) == null ? 1 :
        left.get(a[i]) + 1);
    }
}
 
// Driver code
public static void main(String[] args)
{
    int a[] = { 1, 2, 3, 2, 1 };
    int n = a.length;
 
    right_left(a, n);
}
}
 
// This code is contributed by Princi Singh


Python3




# Python3 implementation of the approach
 
# Function to find the count of equal
# elements to the right - count of equal
# elements to the left for each of the element
def right_left(a, n) :
 
    # Maps to store the frequency and same
    # elements to the left of an element
    total = dict.fromkeys(a, 0);
    left = dict.fromkeys(a, 0);
 
    # Count the frequency of each element
    for i in range(n) :
        if a[i] not in total :
            total[a[i]] = 1
        total[a[i]] += 1;
 
    for i in range(n) :
 
        # Print the answer for each element
        print(total[a[i]] - 1 - (2 * left[a[i]]),
                                      end = " ");
 
        # Increment it's left frequency
        left[a[i]] += 1;
 
# Driver code
if __name__ == "__main__" :
 
    a = [ 1, 2, 3, 2, 1 ];
    n = len(a);
 
    right_left(a, n);
 
# This code is contributed by AnkitRai01


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
     
class GFG
{
 
// Function to find the count of equal
// elements to the right - count of equal
// elements to the left for each of the element
static void right_left(int []a, int n)
{
 
    // Maps to store the frequency and same
    // elements to the left of an element
    Dictionary<int, int> total = new Dictionary<int, int>();
    Dictionary<int, int> left = new Dictionary<int, int>();
 
    // Count the frequency of each element
    for (int i = 0; i < n; i++)
    {
        if(total.ContainsKey(a[i]))
        {
            total[a[i]] = total[a[i]] + 1;
        }
        else{
            total.Add(a[i], 1);
        }
    }
 
    for (int i = 0; i < n; i++)
    {
 
        // Print the answer for each element
        Console.Write((total[a[i]] - 1 -
                      (2 * (left.ContainsKey(a[i]) == true ?
                                   left[a[i]] : 0))) + " ");
 
        // Increment it's left frequency
        if(left.ContainsKey(a[i]))
        {
            left[a[i]] = left[a[i]] + 1;
        }
        else
        {
            left.Add(a[i], 1);
        }
    }
}
 
// Driver code
public static void Main(String[] args)
{
    int []a = { 1, 2, 3, 2, 1 };
    int n = a.Length;
 
    right_left(a, n);
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
    // Javascript implementation of the approach
 
// Function to find the count of equal
// elements to the right - count of equal
// elements to the left for each of the element
function right_left(a, n)
{
   
    // Maps to store the frequency and same
    // elements to the left of an element
   let total = new Map();
    let left = new Map();
   
    // Count the frequency of each element
    for (let i = 0; i < n; i++)
        total.set(a[i],
        total.get(a[i]) == null ? 1 :
        total.get(a[i]) + 1);
   
    for (let i = 0; i < n; i++)
    {
   
        // Print the answer for each element
        document.write((total.get(a[i]) - 1 -
                         (2 * (left.has(a[i]) == true ?
                               left.get(a[i]) : 0))) + " ");
   
        // Increment it's left frequency
        left.set(a[i],
        left.get(a[i]) == null ? 1 :
        left.get(a[i]) + 1);
    }
}
     
    // Driver code
     
        let a = [ 1, 2, 3, 2, 1 ];
    let n = a.length;
   
    right_left(a, n);
     
    // This code is contributed by susmitakundugoaldanga.
</script>


Output

1 1 0 -1 -1





Time complexity: O(N), where N is the size of the given array.
Auxiliary space: O(N), as two hashmaps are required to store the frequency of the elements.



Last Updated : 27 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads