Generate array having differences between count of occurrences of every array element on its left and right
Last Updated :
15 Mar, 2023
Given an array A[] consisting of N integers, the task is to construct an array B[] such that for every ith index, B[i] = X - Y, where X and Y are the count of occurrences of A[i] after and before the ith index.
Examples:
Input: A[] = {3, 2, 1, 2, 3}
Output: 1 1 0 -1 -1
Explanation:
arr[0] = 3, X = 1, Y = 0. Therefore, print 1.
arr[1] = 2, X = 1, Y = 0. Therefore, print 1.
arr[2] = 1, X = 0, Y = 0. Therefore, print 0.
arr[3] = 2, X = 0, Y = 1. Therefore, print -1.
arr[4] = 3, X = 0, Y = 1. Therefore, print -1.
Input: A[] = {1, 2, 3, 4, 5}
Output: 0 0 0 0 0
Naive Approach:
The simplest approach to solve the problem is to traverse the array and consider every array element and compare it with all the elements on its left and right. For every array element, print the difference in its count of occurrences in its left and right.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: Follow the steps below to optimize the above approach:
- Initialize two arrays left[] and right[] to store frequencies of array elements present on the left and right indices of every array element.
- Compute the left and right cumulative frequency tables.
- Print the difference of same indexed elements from the two frequency arrays.
Below is the implementation of the above approach:
C++
// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to construct array of
// differences of counts on the left
// and right of the given array
void constructArray(int A[], int N)
{
// Initialize left and right
// frequency arrays
int left[N + 1] = { 0 };
int right[N + 1] = { 0 };
int X[N + 1] = { 0 }, Y[N + 1] = { 0 };
// Construct left cumulative
// frequency table
for (int i = 0; i < N; i++) {
X[i] = left[A[i]];
left[A[i]]++;
}
// Construct right cumulative
// frequency table
for (int i = N - 1; i >= 0; i--) {
Y[i] = right[A[i]];
right[A[i]]++;
}
// Print the result
for (int i = 0; i < N; i++) {
cout << Y[i] - X[i] << " ";
}
}
// Driver Code
int main()
{
int A[] = { 3, 2, 1, 2, 3 };
int N = sizeof(A) / sizeof(A[0]);
// Function Call
constructArray(A, N);
return 0;
}
Java
// Java program of the above approach
import java.io.*;
class GFG{
// Function to construct array of
// differences of counts on the left
// and right of the given array
static void constructArray(int A[], int N)
{
// Initialize left and right
// frequency arrays
int[] left = new int[N + 1];
int[] right = new int[N + 1];
int[] X = new int[N + 1];
int[] Y = new int[N + 1];
// Construct left cumulative
// frequency table
for(int i = 0; i < N; i++)
{
X[i] = left[A[i]];
left[A[i]]++;
}
// Construct right cumulative
// frequency table
for(int i = N - 1; i >= 0; i--)
{
Y[i] = right[A[i]];
right[A[i]]++;
}
// Print the result
for (int i = 0; i < N; i++)
{
System.out.print(Y[i] - X[i] + " ");
}
}
// Driver Code
public static void main(String[] args)
{
int A[] = { 3, 2, 1, 2, 3 };
int N = A.length;
// Function Call
constructArray(A, N);
}
}
// This code is contributed by akhilsaini
Python3
# Python3 program of the above approach
# Function to construct array of
# differences of counts on the left
# and right of the given array
def constructArray(A, N):
# Initialize left and right
# frequency arrays
left = [0] * (N + 1)
right = [0] * (N + 1)
X = [0] * (N + 1)
Y = [0] * (N + 1)
# Construct left cumulative
# frequency table
for i in range(0, N):
X[i] = left[A[i]]
left[A[i]] += 1
# Construct right cumulative
# frequency table
for i in range(N - 1, -1, -1):
Y[i] = right[A[i]]
right[A[i]] += 1
# Print the result
for i in range(0, N):
print(Y[i] - X[i], end = " ")
# Driver Code
if __name__ == '__main__':
A = [ 3, 2, 1, 2, 3 ]
N = len(A)
# Function Call
constructArray(A, N)
# This code is contributed by akhilsaini
C#
// C# program of the above approach
using System;
class GFG{
// Function to construct array of
// differences of counts on the left
// and right of the given array
static void constructArray(int[] A, int N)
{
// Initialize left and right
// frequency arrays
int[] left = new int[N + 1];
int[] right = new int[N + 1];
int[] X = new int[N + 1];
int[] Y = new int[N + 1];
// Construct left cumulative
// frequency table
for(int i = 0; i < N; i++)
{
X[i] = left[A[i]];
left[A[i]]++;
}
// Construct right cumulative
// frequency table
for(int i = N - 1; i >= 0; i--)
{
Y[i] = right[A[i]];
right[A[i]]++;
}
// Print the result
for(int i = 0; i < N; i++)
{
Console.Write(Y[i] - X[i] + " ");
}
}
// Driver Code
public static void Main()
{
int[] A = { 3, 2, 1, 2, 3 };
int N = A.Length;
// Function Call
constructArray(A, N);
}
}
// This code is contributed by akhilsaini
JavaScript
<script>
// JavaScript program of the above approach
// Function to construct array of
// differences of counts on the left
// and right of the given array
function constructArray(A, N)
{
// Initialize left and right
// frequency arrays
let left = [];
let right = [];
let X = [];
let Y = [];
for(let i = 0; i < N; i++)
{
X[i] = 0;
left[i] = 0;
right[i] = 0;
Y[i]= 0;
}
// Construct left cumulative
// frequency table
for(let i = 0; i < N; i++)
{
X[i] = left[A[i]];
left[A[i]]++;
}
// Construct right cumulative
// frequency table
for(let i = N - 1; i >= 0; i--)
{
Y[i] = right[A[i]];
right[A[i]]++;
}
// Print the result
for(let i = 0; i < N; i++)
{
document.write(Y[i] - X[i] + " ");
}
}
// Driver Code
let A = [ 3, 2, 1, 2, 3 ];
let N = A.length;
// Function Call
constructArray(A, N);
// This code is contributed by target_2
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read