Difference of count of distinct elements present to left and right for each array element
Last Updated :
23 Jul, 2025
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++
// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;
// Function to find the difference of
// count of distinct 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 distinct 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 distinct 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 distinct 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 distinct 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>
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 distinct 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;
}
Java
// Java program for the above approach
import java.util.*;
class GFG {
// Function to find the difference of
// count of distinct elements to the
// left and right for each array elements
static void findDifferenceArray(int arr[], int N)
{
// Stores the frequency of array
// element to the left and the right
HashMap<Integer, Integer> leftMap = new HashMap<>();
HashMap<Integer, Integer> rightMap
= new HashMap<>();
// Stores the frequency of array
// element in the map rightMap
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);
}
// Stores the resultant differences
Vector<Integer> res = new Vector<>();
// 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.get(arr[i]) > 1) {
rightMap.put(arr[i],
rightMap.get(arr[i]) - 1);
}
else {
rightMap.remove(arr[i]);
}
// Find the count in the left
int countRight = rightMap.size();
// Insert the resultant difference
res.add(Math.abs(countRight - countLeft));
// Increment the frequency
if (leftMap.containsKey(arr[i]))
leftMap.put(arr[i],
leftMap.get(arr[i]) + 1);
else
leftMap.put(arr[i], 1);
}
// Print the result
for (int it : res) {
System.out.print(it + " ");
}
}
// 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 Rajput-Ji
Python
# Function to find the difference of
# count of distinct elements to the
# left and right for each array elements
def findDifferenceArray(arr, N):
# Stores the frequency of array
# element to the left and the right
leftMap = {}
rightMap = {}
# Stores the frequency of array
# element in the map rightMap
for i in range(N):
if arr[i] in rightMap:
rightMap[arr[i]] += 1
else:
rightMap[arr[i]] = 1
# Stores the resultant differences
res = []
# Traverse the array
for i in range(N):
# Find the count in the left
countLeft = len(leftMap)
# Decrement the frequency
if rightMap[arr[i]] > 1:
rightMap[arr[i]] -= 1
else:
del rightMap[arr[i]]
# Find the count in the left
countRight = len(rightMap)
# Insert the resultant difference
res.append(abs(countRight - countLeft))
# Increment the frequency
if arr[i] in leftMap:
leftMap[arr[i]] += 1
else:
leftMap[arr[i]] = 1
# Print the result
print(" ".join(str(x) for x in res))
# Driver code
if __name__ == '__main__':
arr = [7, 7, 3, 2, 3]
N = len(arr)
findDifferenceArray(arr, N)
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG {
// Function to find the difference of
// count of distinct elements to the
// left and right for each array elements
static void findDifferenceArray(int []arr, int N) {
// Stores the frequency of array
// element to the left and the right
Dictionary<int, int> leftMap = new Dictionary<int, int>();
Dictionary<int, int> rightMap = new Dictionary<int, int>();
// Stores the frequency of array
// element in the map rightMap
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);
}
// Stores the resultant differences
List<int> res = new List<int>();
// Traverse the array
for (int i = 0; i < N; i++) {
// Find the count in the left
int countLeft = leftMap.Count;
// Decrement the frequency
if (rightMap[arr[i]] > 1) {
rightMap[arr[i]] = rightMap[arr[i]] - 1;
} else {
rightMap.Remove(arr[i]);
}
// Find the count in the left
int countRight = rightMap.Count;
// Insert the resultant difference
res.Add(Math.Abs(countRight - countLeft));
// Increment the frequency
if (leftMap.ContainsKey(arr[i]))
leftMap[arr[i]]= leftMap[arr[i]] + 1;
else
leftMap.Add(arr[i], 1);
}
// Print the result
foreach (int it in res) {
Console.Write(it + " ");
}
}
// 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 Rajput-Ji
JavaScript
// JavaScript code for the above approach
function findDifferenceArray(arr, N) {
// Stores the frequency of array
// element to the left and the right
let leftMap = {};
let rightMap = {};
// Stores the frequency of array
// element in the map rightMap
for (let i = 0; i < N; i++) {
if (rightMap[arr[i]]) {
rightMap[arr[i]] += 1;
} else {
rightMap[arr[i]] = 1;
}
}
// Stores the resultant differences
let res = [];
// Traverse the array
for (let i = 0; i < N; i++) {
// Find the count in the left
let countLeft = Object.keys(leftMap).length;
// Decrement the frequency
if (rightMap[arr[i]] > 1) {
rightMap[arr[i]] -= 1;
} else {
delete rightMap[arr[i]];
}
// Find the count in the right
let countRight = Object.keys(rightMap).length;
// Insert the resultant difference
res.push(Math.abs(countRight - countLeft));
// Increment the frequency
if (leftMap[arr[i]]) {
leftMap[arr[i]] += 1;
} else {
leftMap[arr[i]] = 1;
}
}
// Print the result
console.log(res.join(" "));
}
// Driver code
let arr = [7, 7, 3, 2, 3];
let N = arr.length;
findDifferenceArray(arr, N);
// This code is contributed by phasing17.
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