For each element in 1st array count elements less than or equal to it in 2nd array | Set 2
Last Updated :
02 Sep, 2022
Given two unsorted arrays arr1[] and arr2[]. They may contain duplicates. For each element in arr1[] count elements less than or equal to it in array arr2[].
Examples:
Input : arr1[] = [1, 2, 3, 4, 7, 9]
arr2[] = [0, 1, 2, 1, 1, 4]
Output : [4, 5, 5, 6, 6, 6]
Explanation: There are 4 elements less than or equal to 1 in second array, similarly there are 5 elements less than 2 in second array, calculate the values similarly for other elements.
Input : arr1[] = [5, 10, 2, 6, 1, 8, 6, 12]
arr2[] = [6, 5, 11, 4, 2, 3, 7]
Output : [4, 6, 1, 5, 0, 6, 5, 7]
Explanation: There are 4 elements less than or equal to 5 in second array, similarly there are 6 elements less than 10 in second array, calculate the values similarly for other elements.
This problem is already discussed in the previous post.
Solution: In this article, a more optimized linear time solution to the above problem is discussed. The approach discussed here works for arrays with values in a small range. A range of values that can be used as an index in an array.
Approach: The idea is to create a prefix map up to the maximum element of the second array. The prefix array will store the maximum element up to that index, for example, prefix[i] will store the count of elements up to i. Then traverse through the first array and find the count of elements less than or equal to that element from the prefix array.
The prefix array is created by traversing through the prefix array and updating the current element by adding the precious element, i.e. prefix[i]+ =prefix[i-1].
Algorithm:
- Create extra space (prefix) of the size of a maximum element of the second and first array or a map.
- Traverse the second array.
- For every element of the second array increase the count of prefix array, i.e. prefix[arr2[i]]++
- Traverse through the prefix array from 1 to MAX (maximum element of the second and first array and update the ith element by adding the sum of i-1th element
- Now traverse through the first array and print the value of prefix[arr_1[i]]
Implementation:
C++
// C++ program for each element in 1st
// array count elements less than or equal to it
// in 2nd array
#include <iostream>
using namespace std;
#define MAX 100000
// Function for each element in 1st
// array count elements less than or equal to it
// in 2nd array
void countEleLessThanOrEqual(int arr1[], int m,
int arr2[], int n)
{
// Creating hash array initially
// filled with zero
int hash[MAX] = {0};
// Insert element of arr2[] to hash
// such that hash[i] will give count of
// element i in arr2[]
for (int i = 0; i < n; i++)
hash[arr2[i]]++;
// Presum of hash array
// such that hash[i] will give count of
// element less than or equals to i in arr2[]
for (int i=1; i<MAX; i++)
hash[i] = hash[i] + hash[i-1];
// Traverse arr1[] and print hash[arr[i]]
for (int i = 0; i < m; i++)
cout << hash[arr1[i]] << " ";
}
// Driver code
int main()
{
int arr1[] = {1, 2, 3, 4, 7, 9};
int arr2[] = {0, 1, 2, 1, 1, 4};
int m, n;
m = sizeof(arr1) / sizeof(arr1[0]);
n = sizeof(arr2) / sizeof(arr2[0]);
countEleLessThanOrEqual(arr1, m, arr2, n);
return 0;
}
Java
// Java program for each element
// in 1st array count elements
// less than or equal to it in
// 2nd array
import java.io.*;
class GFG
{
static int MAX = 100000;
// Function for each element
// in 1st array count elements
// less than or equal to it
// in 2nd array
static void countEleLessThanOrEqual(int arr1[], int m,
int arr2[], int n)
{
// Creating hash array initially
// filled with zero
int hash[] = new int[MAX];
// Insert element of arr2[] to
// hash such that hash[i] will
// give count of element i in arr2[]
for (int i = 0; i < n; i++)
hash[arr2[i]]++;
// Presum of hash array
// such that hash[i] will
// give count of element
// less than or equals to
// i in arr2[]
for(int i = 1; i < MAX; i++)
{
hash[i] = hash[i] +
hash[i - 1];
}
// Traverse arr1[] and
// print hash[arr[i]]
for (int i = 0; i < m; i++)
{
System.out.print(hash[arr1[i]] + " ");
}
}
// Driver code
public static void main (String[] args)
{
int arr1[] = {1, 2, 3, 4, 7, 9};
int arr2[] = {0, 1, 2, 1, 1, 4};
int m, n;
m = arr1.length;
n = arr2.length;
countEleLessThanOrEqual(arr1, m, arr2, n);
}
}
// This code is contributed
// by inder_verma
Python3
# Python 3 program for each element in 1st
# array count elements less than or equal
# to it in 2nd array
MAX = 100000
# Function for each element in 1st
# array count elements less than or
# equal to it in 2nd array
def countEleLessThanOrEqual(arr1, m, arr2, n):
# Creating hash array initially
# filled with zero
hash = [0 for i in range(MAX)]
# Insert element of arr2[] to hash
# such that hash[i] will give count
# of element i in arr2[]
for i in range(n):
hash[arr2[i]] += 1
# Presum of hash array such that
# hash[i] will give count of element
# less than or equals to i in arr2[]
for i in range(1, MAX, 1):
hash[i] = hash[i] + hash[i - 1]
# Traverse arr1[] and print hash[arr[i]]
for i in range(m):
print(hash[arr1[i]], end = " ")
# Driver code
if __name__ == '__main__':
arr1 = [1, 2, 3, 4, 7, 9]
arr2 = [0, 1, 2, 1, 1, 4]
m = len(arr1)
n = len(arr2)
countEleLessThanOrEqual(arr1, m, arr2, n)
# This code is contributed by
# Shashank_Sharma
C#
// C# program for each element
// in 1st array count elements
// less than or equal to it in
// 2nd array
using System;
public class GFG {
static int MAX = 100000;
// Function for each element
// in 1st array count elements
// less than or equal to it
// in 2nd array
static void countEleLessThanOrEqual(int []arr1, int m,
int []arr2, int n)
{
// Creating hash array initially
// filled with zero
int []hash = new int[MAX];
// Insert element of arr2[] to
// hash such that hash[i] will
// give count of element i in arr2[]
for (int i = 0; i < n; i++)
hash[arr2[i]]++;
// Presum of hash array
// such that hash[i] will
// give count of element
// less than or equals to
// i in arr2[]
for(int i = 1; i < MAX; i++)
{
hash[i] = hash[i] +
hash[i - 1];
}
// Traverse arr1[] and
// print hash[arr[i]]
for (int i = 0; i < m; i++)
{
Console.Write(hash[arr1[i]] + " ");
}
}
// Driver code
public static void Main ()
{
int []arr1 = {1, 2, 3, 4, 7, 9};
int []arr2 = {0, 1, 2, 1, 1, 4};
int m, n;
m = arr1.Length;
n = arr2.Length;
countEleLessThanOrEqual(arr1, m, arr2, n);
}
}
// This code is contributed by Shikha Singh.
PHP
<?php
// PHP program for each element in 1st
// array count elements less than or
// equal to it in 2nd array
$MAX = 100000 ;
// Function for each element in 1st
// array count elements less than or
// equal to it in 2nd array
function countEleLessThanOrEqual(&$arr1, $m,
&$arr2, $n)
{
global $MAX;
// Creating hash array initially
// filled with zero
$hash = array_fill(0, $MAX, NULL);
// Insert element of arr2[] to hash
// such that hash[i] will give count of
// element i in arr2[]
for ($i = 0; $i < $n; $i++)
$hash[$arr2[$i]]++;
// Presum of hash array such that hash[i]
// will give count of element less than
// or equals to i in arr2[]
for ($i = 1; $i < $MAX; $i++)
$hash[$i] = $hash[$i] + $hash[$i - 1];
// Traverse arr1[] and print hash[arr[i]]
for ($i = 0; $i < $m; $i++)
echo $hash[$arr1[$i]] . " ";
}
// Driver code
$arr1 = array(1, 2, 3, 4, 7, 9);
$arr2 = array(0, 1, 2, 1, 1, 4);
$m = sizeof($arr1);
$n = sizeof($arr2);
countEleLessThanOrEqual($arr1, $m, $arr2, $n);
// This code is contributed
// by ChitraNayal
?>
JavaScript
<script>
// JavaScript program for each element
// in 1st array count elements
// less than or equal to it in
// 2nd array
let MAX = 100000;
// Function for each element
// in 1st array count elements
// less than or equal to it
// in 2nd array
function countEleLessThanOrEqual(arr1,m,arr2,n)
{
// Creating hash array initially
// filled with zero
let hash = new Array(MAX);
for(let i=0;i<hash.length;i++)
{
hash[i]=0;
}
// Insert element of arr2[] to
// hash such that hash[i] will
// give count of element i in arr2[]
for (let i = 0; i < n; i++)
hash[arr2[i]]++;
// Presum of hash array
// such that hash[i] will
// give count of element
// less than or equals to
// i in arr2[]
for(let i = 1; i < MAX; i++)
{
hash[i] = hash[i] +
hash[i - 1];
}
// Traverse arr1[] and
// print hash[arr[i]]
for (let i = 0; i < m; i++)
{
document.write(hash[arr1[i]] + " ");
}
}
// Driver code
let arr1=[1, 2, 3, 4, 7, 9];
let arr2=[0, 1, 2, 1, 1, 4];
let m, n;
m = arr1.length;
n = arr2.length;
countEleLessThanOrEqual(arr1, m, arr2, n);
// This code is contributed by avanitrachhadiya2155
</script>
Complexity Analysis:
- Time Complexity: O(max), where max is the maximum element of both arrays
- Auxiliary Space: O(max), where max is the maximum element of both arrays.
Implementation:
C++
// C++ program for each element in 1st
// array count elements less than or equal to it
// in 2nd array
#include <iostream>
#include <map>
#include <vector>
// Function for each element in 1st
// array count elements less than or equal to it
// in 2nd array
void countLessThanOrEqual(const std::vector<int>& vec1,
const std::vector<int>& vec2) {
std::map<int, unsigned int> countOfVec2;
for (const auto& item : vec2) {
++countOfVec2[item];
}
unsigned int prev = 0;
for (auto& pair : countOfVec2) {
pair.second += prev;
prev = pair.second;
}
// Traverse arr1[] and print result
for (const auto& item : vec1) {
unsigned int result = (--countOfVec2.upper_bound(item))->second;
std::cout << result << " ";
}
}
// Driver code
int main()
{
std::vector<int> arr1 = { 1, 2, 3, 4, 7, 9 };
std::vector<int> arr2 = { 0, 1, 2, 1, 1, 4 };
countLessThanOrEqual(arr1, arr2);
return 0;
}
Java
// Java program for each element in 1st
// array count elements less than or equal to it
// in 2nd array
import java.util.*;
class GFG {
// Function for each element in 1st
// array count elements less than or equal to it
// in 2nd array
static void countLessThanOrEqual(int vec1[], int vec2[])
{
HashMap<Integer, Integer> countOfVec2 = new HashMap<>();
for(int item : vec2)
{
if(!countOfVec2.containsKey(item))
countOfVec2.put(item, 0);
countOfVec2.put(item, countOfVec2.get(item) + 1);
}
int prev = 0;
Vector<Integer> li = new Vector<Integer>();
for (Map.Entry<Integer, Integer> pair : countOfVec2.entrySet())
{
li.add(pair.getKey());
}
for(int pair : li)
{
countOfVec2.put(pair, countOfVec2.get(pair) + prev);
prev = countOfVec2.get(pair);
}
// Traverse arr1[] and print result
for(int item : vec1)
{
int i = 0, v = 0, last = 0;
for (Map.Entry<Integer, Integer> pair : countOfVec2.entrySet())
{
last = pair.getKey();
if(item < pair.getKey())
{
v = i;
break;
}
i++;
}
v -= 1;
if(v == -1)
{
v = last;
}
int result = countOfVec2.get(v);
System.out.print(result + " ");
}
}
// Driver code
public static void main(String[] args)
{
int arr1[] = {1, 2, 3, 4, 7, 9};
int arr2[] = {0, 1, 2, 1, 1, 4};
countLessThanOrEqual(arr1, arr2);
}
}
// This code is contributed by divyesh072019.
Python3
# Python3 program for each element in 1st
# array count elements less than or equal to it
# in 2nd array
# Function for each element in 1st
# array count elements less than or equal to it
# in 2nd array
def countLessThanOrEqual(vec1, vec2):
countOfVec2 = {}
for item in vec2:
if item not in countOfVec2:
countOfVec2[item] = 0
countOfVec2[item] += 1
prev = 0
for pair in countOfVec2:
countOfVec2[pair] += prev
prev = countOfVec2[pair]
val = list(countOfVec2)
# Traverse arr1[] and print result
for item in vec1:
i = 0
v = 0
for i in range(len(val)):
if item < val[i]:
v = i
break
v -= 1
if v == -1:
v = val[-1]
result = countOfVec2[v]
print(result, end = " ")
# Driver code
arr1 = [1, 2, 3, 4, 7, 9]
arr2 = [0, 1, 2, 1, 1, 4]
countLessThanOrEqual(arr1, arr2)
# This code is contributed by shubhamsingh10
C#
// C# program for each element in 1st
// array count elements less than or equal to it
// in 2nd array
using System;
using System.Collections.Generic;
class GFG {
// Function for each element in 1st
// array count elements less than or equal to it
// in 2nd array
static void countLessThanOrEqual(int[] vec1, int[] vec2)
{
Dictionary<int, int> countOfVec2 = new Dictionary<int, int>();
foreach(int item in vec2)
{
if(!countOfVec2.ContainsKey(item))
countOfVec2[item] = 0;
countOfVec2[item] += 1;
}
int prev = 0;
List<int> li = new List<int>();
foreach(KeyValuePair<int, int> pair in countOfVec2)
{
li.Add(pair.Key);
}
foreach(int pair in li)
{
countOfVec2[pair] += prev;
prev = countOfVec2[pair];
}
// Traverse arr1[] and print result
foreach(int item in vec1)
{
int i = 0, v = 0, last = 0;
foreach(KeyValuePair<int, int> pair in countOfVec2)
{
last = pair.Key;
if(item < pair.Key)
{
v = i;
break;
}
i++;
}
v -= 1;
if(v == -1)
{
v = last;
}
int result = countOfVec2[v];
Console.Write(result + " ");
}
}
// Driver code
static void Main()
{
int[] arr1 = {1, 2, 3, 4, 7, 9};
int[] arr2 = {0, 1, 2, 1, 1, 4};
countLessThanOrEqual(arr1, arr2);
}
}
// This code is contributed by divyeshrabadiya07.
JavaScript
<script>
// Javascript program for each element in 1st
// array count elements less than or equal to it
// in 2nd array
// Function for each element in 1st
// array count elements less than or equal to it
// in 2nd array
function countLessThanOrEqual(vec1,vec2)
{
let countOfVec2 = new Map();
for(let item = 0;item < vec2.length; item++)
{
if(!countOfVec2.has(vec2[item]))
countOfVec2.set(vec2[item], 0);
countOfVec2.set(vec2[item], countOfVec2.get(vec2[item]) + 1);
}
let prev = 0;
let li = [];
for (let [key, value] of countOfVec2.entries())
{
li.push(key);
}
for(let pair = 0; pair < li.length; pair++)
{
countOfVec2.set(pair, countOfVec2.get(li[pair]) + prev);
prev = countOfVec2.get(li[pair]);
}
// Traverse arr1[] and print result
for(let item=0; item<vec1.length;item++)
{
let i = 0, v = 0, last = 0;
for (let [key, value] of countOfVec2.entries())
{
last = key;
if(vec1[item] < key)
{
v = i;
break;
}
i++;
}
v -= 1;
if(v == -1)
{
v = last;
}
let result = countOfVec2.get(v);
document.write(result + " ");
}
}
// Driver code
let arr1=[1, 2, 3, 4, 7, 9];
let arr2=[0, 1, 2, 1, 1, 4];
countLessThanOrEqual(arr1, arr2);
// This code is contributed by rag2127
</script>
Complexity Analysis:
- Time Complexity: O(max) where max is the maximum element of both arrays.
- Auxiliary Complexity : O(max) where max is the maximum element of both arrays.
Similar Reads
For each in 1st array count less than or equal to it in 2nd array
You are given two unsorted arrays a[] and b[]. Both arrays may contain duplicate elements. For each element in a[], your task is to count how many elements in b[] are less than or equal to that element.Examples:Input: a[] = [1, 2, 3, 4, 7, 9], b = [0, 1, 2, 1, 1, 4]Output: [4, 5, 5, 6, 6, 6]Explanat
15+ min read
Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
Given two unsorted arrays arr1[] and arr2[], the task is to find the sum of elements of arr1[] such that the number of elements less than or equal to them in arr2[] is maximum. Examples: Input: arr1[] = {1, 2, 3, 4, 7, 9}, arr2[] = {0, 1, 2, 1, 1, 4} Output: 20 Below table shows the count of element
15 min read
Count elements in first Array with absolute difference greater than K with an element in second Array
Given two arrays arr1[] and arr2[] and an integer K, our task is to find the number elements in the first array, for an element x, in arr1[], there exists at least one element y, in arr2[] such that absolute difference of x and y is greater than the integer K. Examples: Input: arr1 = {3, 1, 4}, arr2
7 min read
Count of elements in first Array greater than second Array with each element considered only once
Given two sorted array of size N. The task is to find the maximum number of elements in the first array which are strictly greater than the elements of the second array such that an element can be considered only once. Examples: Input: arr1[] = { 20, 30, 50 }, arr2[] = { 25, 40, 60 } Output: 2 Expla
5 min read
Count of pairs having each element equal to index of the other from an Array
Given an integer N and an array arr[] that contains elements in the range [1, N], the task is to find the count of all pairs (arr[i], arr[j]) such that i < j and i == arr[j] and j == arr[i]. Examples: Input: N = 4, arr[] = {2, 1, 4, 3} Output: 2 Explanation: All possible pairs are {1, 2} and {3,
6 min read
Count elements less than or equal to a given value in a sorted rotated array
Given a sorted array of n distinct integers rotated at some point. Given a value x. The problem is to count all the elements in the array which are less than or equal to x. Examples: Input : arr[] = {4, 5, 8, 1, 3}, x = 6 Output : 4 Input : arr[] = {6, 10, 12, 15, 2, 4, 5}, x = 14 Output : 6 Naive A
15 min read
Count of pairs from arrays A and B such that element in A is greater than element in B at that index
Given two arrays A[] and B[] of size N, the task is to count the maximum number of pairs, where each pair contains one from each array, such that A[i] > B[i]. Also the array A can be rearranged any number of times. Examples: Input: A[] = {20, 30, 50}, B[]= {60, 40, 25} Output: 2 Explanation: Init
7 min read
Count of array elements which are greater than all elements on its left
Given an array arr[] of size n, the task is to count the number of array elements such that all the elements to its left are strictly smaller than it.Note: The first element of the array will be considered to be always satisfying the condition.Examples :Input: arr[] = [2, 4, 5, 6]Output: 4Explanatio
8 min read
Count all distinct pairs of repeating elements from the array for every array element
Given an array arr[] of N integers. For each element in the array, the task is to count the possible pairs (i, j), excluding the current element, such that i < j and arr[i] = arr[j]. Examples: Input: arr[] = {1, 1, 2, 1, 2}Output: 2 2 3 2 3Explanation:For index 1, remaining elements after excludi
7 min read
Count of index pairs with equal elements in an array | Set 2
Given an array arr[] of N elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i != j Examples: Input: arr[]={1, 2, 1, 1}Output: 3 Explanation:In the array arr[0]=arr[2]=arr[3]Valid Pairs are (0, 2), (0, 3) and (2, 3) Input: arr[]={2, 2, 3, 2, 3}Output: 4Ex
8 min read