Difference of count of distinct elements present to left and right for each array element
Last Updated :
15 Feb, 2023
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:
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++
#include "bits/stdc++.h"
using namespace std;
void findDifferenceArray( int arr[], int N)
{
set< int > S1;
set< int > S2;
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < i; j++) {
S1.insert(arr[j]);
}
for ( int j = i + 1; j < N; j++) {
S2.insert(arr[j]);
}
cout << abs (( int )S1.size()
- ( int )S2.size())
<< ' ' ;
S1.clear();
S2.clear();
}
}
int main()
{
int arr[] = { 7, 7, 3, 2, 3 };
int N = sizeof (arr) / sizeof (arr[0]);
findDifferenceArray(arr, N);
return 0;
}
|
Java
import java.util.HashSet;
class GFG{
public static void findDifferenceArray( int arr[], int N)
{
HashSet<Integer> S1 = new HashSet<Integer>();
HashSet<Integer> S2 = new HashSet<Integer>();
for ( int i = 0 ; i < N; i++) {
for ( int j = 0 ; j < i; j++) {
S1.add(arr[j]);
}
for ( int j = i + 1 ; j < N; j++) {
S2.add(arr[j]);
}
System.out.print(Math.abs(S1.size() - S2.size()) + " " );
S1.clear();
S2.clear();
}
}
public static void main(String args[])
{
int arr[] = { 7 , 7 , 3 , 2 , 3 };
int N = arr.length;
findDifferenceArray(arr, N);
}
}
|
Python3
def findDifferenceArray(arr, N) :
S1 = set ();
S2 = set ();
for i in range (N) :
for j in range (i) :
S1.add(arr[j]);
for j in range (i + 1 , N) :
S2.add(arr[j]);
print ( abs ( len (S1) - len (S2)),end = ' ' );
S1.clear();
S2.clear();
if __name__ = = "__main__" :
arr = [ 7 , 7 , 3 , 2 , 3 ];
N = len (arr);
findDifferenceArray(arr, N);
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
public static void findDifferenceArray( int [] arr, int N)
{
HashSet< int > S1 = new HashSet< int >();
HashSet< int > S2 = new HashSet< int >();
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < i; j++) {
S1.Add(arr[j]);
}
for ( int j = i + 1; j < N; j++) {
S2.Add(arr[j]);
}
Console.Write(Math.Abs(S1.Count - S2.Count) + " " );
S1.Clear();
S2.Clear();
}
}
public static void Main(String[] args)
{
int [] arr = { 7, 7, 3, 2, 3 };
int N = arr.Length;
findDifferenceArray(arr, N);
}
}
|
Javascript
<script>
function findDifferenceArray(arr, N) {
let S1 = new Set();
let S2 = new Set();
for (let i = 0; i < N; i++) {
for (let j = 0; j < i; j++) {
S1.add(arr[j]);
}
for (let j = i + 1; j < N; j++) {
S2.add(arr[j]);
}
document.write(Math.abs(S1.size
- S2.size)
+ ' ' );
S1.clear();
S2.clear();
}
}
let arr = [7, 7, 3, 2, 3];
let N = arr.length;
findDifferenceArray(arr, N);
</script>
|
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++
#include "bits/stdc++.h"
using namespace std;
void findDifferenceArray( int arr[], int N)
{
unordered_map< int , int > leftMap, rightMap;
for ( int i = 0; i < N; i++) {
rightMap[arr[i]]++;
}
vector< int > res;
for ( int i = 0; i < N; i++) {
int countLeft = leftMap.size();
if (rightMap[arr[i]] > 1) {
rightMap[arr[i]]--;
}
else {
rightMap.erase(arr[i]);
}
int countRight = rightMap.size();
res.push_back( abs (countRight - countLeft));
leftMap[arr[i]]++;
}
for ( auto & it : res) {
cout << it << ' ' ;
}
}
int main()
{
int arr[] = { 7, 7, 3, 2, 3 };
int N = sizeof (arr) / sizeof (arr[0]);
findDifferenceArray(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void findDifferenceArray( int arr[], int N)
{
HashMap<Integer, Integer> leftMap = new HashMap<>();
HashMap<Integer, Integer> rightMap
= new HashMap<>();
for ( int i = 0 ; i < N; i++) {
if (rightMap.containsKey(arr[i]))
rightMap.put(arr[i],
rightMap.get(arr[i]) + 1 );
else
rightMap.put(arr[i], 1 );
}
Vector<Integer> res = new Vector<>();
for ( int i = 0 ; i < N; i++) {
int countLeft = leftMap.size();
if (rightMap.get(arr[i]) > 1 ) {
rightMap.put(arr[i],
rightMap.get(arr[i]) - 1 );
}
else {
rightMap.remove(arr[i]);
}
int countRight = rightMap.size();
res.add(Math.abs(countRight - countLeft));
if (leftMap.containsKey(arr[i]))
leftMap.put(arr[i],
leftMap.get(arr[i]) + 1 );
else
leftMap.put(arr[i], 1 );
}
for ( int it : res) {
System.out.print(it + " " );
}
}
public static void main(String[] args)
{
int arr[] = { 7 , 7 , 3 , 2 , 3 };
int N = arr.length;
findDifferenceArray(arr, N);
}
}
|
Python
def findDifferenceArray(arr, N):
leftMap = {}
rightMap = {}
for i in range (N):
if arr[i] in rightMap:
rightMap[arr[i]] + = 1
else :
rightMap[arr[i]] = 1
res = []
for i in range (N):
countLeft = len (leftMap)
if rightMap[arr[i]] > 1 :
rightMap[arr[i]] - = 1
else :
del rightMap[arr[i]]
countRight = len (rightMap)
res.append( abs (countRight - countLeft))
if arr[i] in leftMap:
leftMap[arr[i]] + = 1
else :
leftMap[arr[i]] = 1
print ( " " .join( str (x) for x in res))
if __name__ = = '__main__' :
arr = [ 7 , 7 , 3 , 2 , 3 ]
N = len (arr)
findDifferenceArray(arr, N)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static void findDifferenceArray( int []arr, int N) {
Dictionary< int , int > leftMap = new Dictionary< int , int >();
Dictionary< int , int > rightMap = new Dictionary< int , int >();
for ( int i = 0; i < N; i++) {
if (rightMap.ContainsKey(arr[i]))
rightMap[arr[i]] = rightMap[arr[i]] + 1;
else
rightMap.Add(arr[i], 1);
}
List< int > res = new List< int >();
for ( int i = 0; i < N; i++) {
int countLeft = leftMap.Count;
if (rightMap[arr[i]] > 1) {
rightMap[arr[i]] = rightMap[arr[i]] - 1;
} else {
rightMap.Remove(arr[i]);
}
int countRight = rightMap.Count;
res.Add(Math.Abs(countRight - countLeft));
if (leftMap.ContainsKey(arr[i]))
leftMap[arr[i]]= leftMap[arr[i]] + 1;
else
leftMap.Add(arr[i], 1);
}
foreach ( int it in res) {
Console.Write(it + " " );
}
}
public static void Main(String[] args) {
int []arr = { 7, 7, 3, 2, 3 };
int N = arr.Length;
findDifferenceArray(arr, N);
}
}
|
Javascript
function findDifferenceArray(arr, N) {
let leftMap = {};
let rightMap = {};
for (let i = 0; i < N; i++) {
if (rightMap[arr[i]]) {
rightMap[arr[i]] += 1;
} else {
rightMap[arr[i]] = 1;
}
}
let res = [];
for (let i = 0; i < N; i++) {
let countLeft = Object.keys(leftMap).length;
if (rightMap[arr[i]] > 1) {
rightMap[arr[i]] -= 1;
} else {
delete rightMap[arr[i]];
}
let countRight = Object.keys(rightMap).length;
res.push(Math.abs(countRight - countLeft));
if (leftMap[arr[i]]) {
leftMap[arr[i]] += 1;
} else {
leftMap[arr[i]] = 1;
}
}
console.log(res.join( " " ));
}
let arr = [7, 7, 3, 2, 3];
let N = arr.length;
findDifferenceArray(arr, N);
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...