Count-based Absolute difference for Array element
Last Updated :
15 Sep, 2023
Given an array of integers, A[] of size N. For each ith element in the array, calculate the absolute difference between the count of numbers that are to the left of i and are strictly greater than the ith element, and the count of numbers that are to the right of i and are strictly lesser than the ith element.
Examples:
Input: N = 5, A[] = {5, 4, 3, 2, 1}
Output: 4 2 0 2 4
Explanation: We can see that the required number for the 1st element is |0-4| = 4
Input: N = 5, A[] = {1, 2, 3, 4, 5}
Output: 0 0 0 0 0
Explanation: There is no greater element on the left for any element and no lesser element on the right.
Approach: To solve the problem follow the below idea:
The solution to finding the absolute difference between the number of elements greater than and lesser than each element in a given array, involves using a Binary Index Tree. The approach involves sorting the array and mapping each element to its corresponding index in the sorted array, constructing two Binary Index Trees for counting the number of elements less than each element from the right side and greater than each element from the left side, respectively, and computing the absolute difference between the counts for each element.
Steps that were to follow the above approach:
- Create a Binary Index Tree object with an array of size n+1 initialized with 0.
- Sort the given input array and create a map of the sorted array elements with their corresponding indices.
- Create an array of indices of the input array elements using the map created in the previous step.
- Create another Binary Index Tree object with an array of size n+1 initialized with 0.
- Traverse the array of indices from right to left and for each index,
- find the number of elements smaller than the current element to its right using the Binary Index Tree created in the previous step, update the Binary Index Tree with the current index, and store the result in a separate array.
- Reverse the array of indices and repeat the traversal, but this time find the number of elements greater than the current element to its left.
- For each element in the two arrays created in the two traversals, calculate their absolute difference and store the result in a third array.
- Return the third array as the final result.
Below is the code to implement the above steps:
C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
// Binary Indexed Tree class.
class BinaryIndexTree {
private:
vector<int> arr;
public:
BinaryIndexTree(int size) {
arr.resize(size + 1, 0);
}
void update(int x, int val) {
if (x == 0)
return;
for (; x < arr.size(); x += x & -x)
arr[x] += val;
}
int query(int index) {
if (index == 0)
return 0;
int sum = 0;
for (; index > 0; index -= index & -index)
sum += arr[index];
return sum;
}
};
// Function to return the resultant array.
vector<int> retResult(vector<int>& arr, int n) {
vector<int> arrSorted = arr;
sort(arrSorted.begin(), arrSorted.end());
unordered_map<int, int> map;
for (int i = 0; i < arrSorted.size(); i++) {
map[arrSorted[i]] = i + 1;
}
vector<int> arrIndexes(arr.size());
int idx = 0;
for (int key : arr) {
arrIndexes[idx++] = map[key];
}
BinaryIndexTree bitRightLesser(arr.size() + 1);
vector<int> right(n);
for (int i = n - 1; i >= 0; i--) {
right[i] = bitRightLesser.query(arrIndexes[i] - 1);
bitRightLesser.update(arrIndexes[i], 1);
}
for (int i = 0; i < n; i++) {
arrIndexes[i] = n + 1 - arrIndexes[i];
}
BinaryIndexTree bitLeftGreater(arr.size() + 1);
vector<int> left(n);
for (int i = 0; i < n; i++) {
left[i] = bitLeftGreater.query(arrIndexes[i] - 1);
bitLeftGreater.update(arrIndexes[i], 1);
}
vector<int> ret(n);
for (int i = 0; i < n; i++) {
ret[i] = abs(right[i] - left[i]);
}
return ret;
}
// Driver's code
int main() {
vector<int> arr = { 5, 4, 3, 2, 1 };
int n = arr.size();
// Function call
vector<int> ret = retResult(arr, n);
cout << "[";
for (int i = 0; i < ret.size(); i++) {
cout << ret[i];
if (i != ret.size() - 1)
cout << ", ";
}
cout << "]" << endl;
return 0;
}
// This code is contributed by Prajwal Kandekar
Java
// Java code for the above approach.
import java.util.*;
public class Main {
// Binary Indexed Tree class.
static class BinaryIndexTree {
private int[] arr;
public BinaryIndexTree(int size)
{
arr = new int[size + 1];
Arrays.fill(arr, 0);
}
public void update(int x, int val)
{
if (x == 0)
return;
for (; x < arr.length; x += x & -x)
arr[x] += val;
}
public int query(int index)
{
if (index == 0)
return 0;
int sum = 0;
for (; index > 0; index -= index & -index)
sum += arr[index];
return sum;
}
}
// Function to return the
// resultant array.
static int[] retResult(int[] arr, int n)
{
int[] arrSorted = Arrays.copyOf(arr, arr.length);
Arrays.sort(arrSorted);
Map<Integer, Integer> map
= new HashMap<Integer, Integer>();
for (int i = 0; i < arrSorted.length; i++) {
map.put(arrSorted[i], i + 1);
}
int[] arrIndexes = new int[arr.length];
int idx = 0;
for (int key : arr) {
arrIndexes[idx++] = map.get(key);
}
BinaryIndexTree bitRightLesser
= new BinaryIndexTree(arr.length + 1);
int[] right = new int[n];
for (int i = n - 1; i >= 0; i--) {
right[i]
= bitRightLesser.query(arrIndexes[i] - 1);
bitRightLesser.update(arrIndexes[i], 1);
}
for (int i = 0; i < n; i++) {
arrIndexes[i] = n + 1 - arrIndexes[i];
}
BinaryIndexTree bitLeftGreater
= new BinaryIndexTree(arr.length + 1);
int[] left = new int[n];
for (int i = 0; i < n; i++) {
left[i]
= bitLeftGreater.query(arrIndexes[i] - 1);
bitLeftGreater.update(arrIndexes[i], 1);
}
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = Math.abs(right[i] - left[i]);
}
return ret;
}
// Driver's code
public static void main(String[] args)
{
int[] arr = { 5, 4, 3, 2, 1 };
int n = arr.length;
// Function call
int[] ret = retResult(arr, n);
System.out.println(Arrays.toString(ret));
}
}
Python3
#Python code for the above approach.
class BinaryIndexTree:
def __init__(self, size):
# Binary Indexed Tree (Fenwick Tree) initialization.
self.arr = [0] * (size + 1)
def update(self, x, val):
# Update the Binary Indexed Tree by adding 'val' to the element at index 'x'.
if x == 0:
return
while x < len(self.arr):
self.arr[x] += val
x += x & -x
def query(self, index):
# Compute the prefix sum of elements from index 1 to 'index'.
if index == 0:
return 0
sum = 0
while index > 0:
sum += self.arr[index]
index -= index & -index
return sum
def ret_result(arr, n):
# Sort the input array and create a mapping of elements to their sorted order.
arr_sorted = sorted(arr)
mapping = {}
for i, num in enumerate(arr_sorted):
mapping[num] = i + 1
# Convert the input array to an array of indexes based on their sorted order.
arr_indexes = [mapping[num] for num in arr]
# Use Binary Indexed Tree to calculate the number of elements greater than the current element on its right.
bit_right_lesser = BinaryIndexTree(len(arr) + 1)
right = [0] * n
for i in range(n - 1, -1, -1):
right[i] = bit_right_lesser.query(arr_indexes[i] - 1)
bit_right_lesser.update(arr_indexes[i], 1)
# Update the array of indexes to calculate the number of elements greater than the current element on its left.
arr_indexes = [n + 1 - num for num in arr_indexes]
# Use Binary Indexed Tree to calculate the number of elements smaller than the current element on its left.
bit_left_greater = BinaryIndexTree(len(arr) + 1)
left = [0] * n
for i in range(n):
left[i] = bit_left_greater.query(arr_indexes[i] - 1)
bit_left_greater.update(arr_indexes[i], 1)
# Calculate the absolute difference between the number of elements greater and smaller on both sides for each element.
ret = [abs(right[i] - left[i]) for i in range(n)]
return ret
# Driver's code
if __name__ == "__main__":
arr = [5, 4, 3, 2, 1]
n = len(arr)
# Function call to get the resultant array.
ret = ret_result(arr, n)
# Print the resultant array in the specified format.
print("[", end="")
for i in range(len(ret)):
print(ret[i], end="")
if i != len(ret) - 1:
print(", ", end="")
print("]")
# This code is contributed by uttamdp_10
C#
// C# code for the above approach.
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
// Binary Indexed Tree class.
class BinaryIndexTree {
private int[] arr;
public BinaryIndexTree(int size)
{
arr = new int[size + 1];
Array.Fill(arr, 0);
}
public void update(int x, int val)
{
if (x == 0)
return;
for (; x < arr.Length; x += x & -x)
arr[x] += val;
}
public int query(int index)
{
if (index == 0)
return 0;
int sum = 0;
for (; index > 0; index -= index & -index)
sum += arr[index];
return sum;
}
}
// Function to return the
// resultant array.
static int[] retResult(int[] arr, int n)
{
int[] arrSorted = arr.ToArray();
Array.Sort(arrSorted);
Dictionary<int, int> map
= new Dictionary<int, int>();
for (int i = 0; i < arrSorted.Length; i++) {
map.Add(arrSorted[i], i + 1);
}
int[] arrIndexes = new int[arr.Length];
int idx = 0;
foreach(int key in arr)
{
arrIndexes[idx++] = map[key];
}
BinaryIndexTree bitRightLesser
= new BinaryIndexTree(arr.Length + 1);
int[] right = new int[n];
for (int i = n - 1; i >= 0; i--) {
right[i]
= bitRightLesser.query(arrIndexes[i] - 1);
bitRightLesser.update(arrIndexes[i], 1);
}
for (int i = 0; i < n; i++) {
arrIndexes[i] = n + 1 - arrIndexes[i];
}
BinaryIndexTree bitLeftGreater
= new BinaryIndexTree(arr.Length + 1);
int[] left = new int[n];
for (int i = 0; i < n; i++) {
left[i]
= bitLeftGreater.query(arrIndexes[i] - 1);
bitLeftGreater.update(arrIndexes[i], 1);
}
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = Math.Abs(right[i] - left[i]);
}
return ret;
}
// Driver's code
static void Main(string[] args)
{
int[] arr = { 5, 4, 3, 2, 1 };
int n = arr.Length;
// Function call
int[] ret = retResult(arr, n);
Console.Write("[");
Console.Write(string.Join(", ", ret));
Console.WriteLine("]");
}
}
// This code is contributed by Tapesh(tapeshdua420)
JavaScript
// Javascript code for the above approach.
class BinaryIndexTree {
constructor(size) {
this.arr = new Array(size + 1).fill(0);
}
update(x, val) {
if (x === 0) return;
for (; x < this.arr.length; x += x & -x)
this.arr[x] += val;
}
query(index) {
if (index === 0) return 0;
let sum = 0;
for (; index > 0; index -= index & -index)
sum += this.arr[index];
return sum;
}
}
function retResult(arr) {
const n = arr.length;
const arrSorted = [...arr].sort((a, b) => a - b);
const map = new Map();
arrSorted.forEach((value, index) => {
map.set(value, index + 1);
});
const arrIndexes = arr.map(value => map.get(value));
const bitRightLesser = new BinaryIndexTree(n + 1);
const right = new Array(n);
for (let i = n - 1; i >= 0; i--) {
right[i] = bitRightLesser.query(arrIndexes[i] - 1);
bitRightLesser.update(arrIndexes[i], 1);
}
arrIndexes.forEach((value, index, arr) => {
arr[index] = n + 1 - value;
});
const bitLeftGreater = new BinaryIndexTree(n + 1);
const left = new Array(n);
for (let i = 0; i < n; i++) {
left[i] = bitLeftGreater.query(arrIndexes[i] - 1);
bitLeftGreater.update(arrIndexes[i], 1);
}
const ret = new Array(n);
for (let i = 0; i < n; i++) {
ret[i] = Math.abs(right[i] - left[i]);
}
return ret;
}
// Driver's code
const arr = [5, 4, 3, 2, 1];
// Function call
const ret = retResult(arr);
console.log('[', ret.join(', '), ']');
}
//this code is contributed by uttamdp_10
Time Complexity: O(N * log 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