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[].
Source: Amazon Interview Experience | Set 354 (For SDE-2)
Examples:
Input : arr1[] = [1, 2, 3, 4, 7, 9]
arr2[] = [0, 1, 2, 1, 1, 4]
Output : [4, 5, 5, 6, 6, 6]
So the number of elements less than or equal to
1 is 4, 2 is 5, 3 is 5, 4 is 6, 7 is 6 and 9 is 6.
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]
So the number of elements less than or equal to
5 is 4, 10 is 6, 2 is 1, 6 is 5, 1 is 0, 8 is 6,
6 is 5 and 12 is 7
Naive Approach:
Approach: The idea is to use two loops, the outer loop for elements of array arr1[] and an inner loop for elements of array arr2[]. Then for each element of arr1[], count elements less than or equal to it in arr2[].
Algorithm :
- Traverse through the elements of the first array from start to end.
- For every element in the first array.
- Traverse through the elements in the second array and find the count of elements that are less than or equal to the element of the first array.
- Print the count for every index.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void countEleLessThanOrEqual( int arr1[], int arr2[],
int m, int n)
{
for ( int i = 0; i < m; i++) {
int count = 0;
for ( int j = 0; j < n; j++)
if (arr2[j] <= arr1[i])
count++;
cout << count << " " ;
}
}
int main()
{
int arr1[] = { 1, 2, 3, 4, 7, 9 };
int arr2[] = { 0, 1, 2, 1, 1, 4 };
int m = sizeof (arr1) / sizeof (arr1[0]);
int n = sizeof (arr2) / sizeof (arr2[0]);
countEleLessThanOrEqual(arr1, arr2, m, n);
return 0;
}
|
Java
import java.util.Arrays;
class GFG {
static int countEleLessThanOrEqual(
int arr1[], int arr2[],
int m, int n)
{
for ( int i = 0 ; i < m; i++) {
int count = 0 ;
for ( int j = 0 ; j < n; j++)
if (arr2[j] <= arr1[i])
count++;
System.out.print(count + " " );
}
return m;
}
public static void main(String[] args)
{
int arr1[] = { 1 , 2 , 3 , 4 , 7 , 9 };
int arr2[] = { 0 , 1 , 2 , 1 , 1 , 4 };
countEleLessThanOrEqual(
arr1, arr2, arr1.length, arr2.length);
}
}
|
Python3
def countEleLessThanOrEqual(arr1, arr2, m, n):
for i in range (m):
count = 0
for j in range (n):
if (arr2[j] < = arr1[i]):
count + = 1
print (count, end = " " )
arr1 = [ 1 , 2 , 3 , 4 , 7 , 9 ]
arr2 = [ 0 , 1 , 2 , 1 , 1 , 4 ]
m = len (arr1)
n = len (arr2)
countEleLessThanOrEqual(arr1, arr2, m, n)
|
C#
using System;
class GFG {
static void countEleLessThanOrEqual(
int [] arr1, int [] arr2,
int m, int n)
{
for ( int i = 0; i < m; i++) {
int count = 0;
for ( int j = 0; j < n; j++)
if (arr2[j] <= arr1[i])
count++;
Console.Write((count) + " " );
}
}
public static void Main()
{
int [] arr1 = { 1, 2, 3, 4, 7, 9 };
int [] arr2 = { 0, 1, 2, 1, 1, 4 };
countEleLessThanOrEqual(arr1,
arr2, arr1.Length, arr2.Length);
}
}
|
Javascript
<script>
function countEleLessThanOrEqual(arr1, arr2, m, n)
{
for (let i = 0; i < m; i++) {
let count = 0;
for (let j = 0; j < n; j++)
if (arr2[j] <= arr1[i])
count++;
document.write(count + " " );
}
}
let arr1 = [ 1, 2, 3, 4, 7, 9 ];
let arr2 = [ 0, 1, 2, 1, 1, 4 ];
let m = arr1.length;
let n = arr2.length;
countEleLessThanOrEqual(arr1, arr2, m, n);
</script>
|
Complexity Analysis:
- Time complexity: O(m * n).
Considering arr1[] and arr2[] are of sizes m and n respectively.
- Space Complexity: O(1).
As no extra space is required
Efficient Solution:
Approach: Sort the elements of 2nd array, i.e., array arr2[]. Then perform a modified binary search on array arr2[]. For each element x of array arr1[], find the last index of the largest element smaller than or equal to x in sorted array arr2[]. The index of the largest element will give the count of elements.
Algorithm:
- Sort the second array.
- Traverse through the elements of the first array from start to end.
- For every element in the first array.
- Do a binary search on the second array and find the index of the largest element smaller than or equal to the element of the first array.
- The index of the largest element will give the count of elements. Print the count for every index.
C++
#include <bits/stdc++.h>
using namespace std;
int binary_search( int arr[], int l, int h, int x)
{
while (l <= h) {
int mid = (l + h) / 2;
if (arr[mid] <= x)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
void countEleLessThanOrEqual(
int arr1[], int arr2[],
int m, int n)
{
sort(arr2, arr2 + n);
for ( int i = 0; i < m; i++) {
int index = binary_search(
arr2, 0, n - 1, arr1[i]);
cout << (index + 1) << " " ;
}
}
int main()
{
int arr1[] = { 1, 2, 3, 4, 7, 9 };
int arr2[] = { 0, 1, 2, 1, 1, 4 };
int m = sizeof (arr1) / sizeof (arr1[0]);
int n = sizeof (arr2) / sizeof (arr2[0]);
countEleLessThanOrEqual(arr1, arr2, m, n);
return 0;
}
|
Java
import java.util.Arrays;
class GFG {
static int binary_search(
int arr[], int l,
int h, int x)
{
while (l <= h) {
int mid = (l + h) / 2 ;
if (arr[mid] <= x)
l = mid + 1 ;
else
h = mid - 1 ;
}
return h;
}
static void countEleLessThanOrEqual(
int arr1[], int arr2[],
int m, int n)
{
Arrays.sort(arr2);
for ( int i = 0 ; i < m; i++) {
int index = binary_search(
arr2, 0 , n - 1 , arr1[i]);
System.out.print((index + 1 ) + " " );
}
}
public static void main(String[] args)
{
int arr1[] = { 1 , 2 , 3 , 4 , 7 , 9 };
int arr2[] = { 0 , 1 , 2 , 1 , 1 , 4 };
countEleLessThanOrEqual(
arr1, arr2, arr1.length,
arr2.length);
}
}
|
Python3
def bin_search(arr, n, x):
l = 0
h = n - 1
while (l < = h):
mid = int ((l + h) / / 2 )
if (arr[mid] < = x):
l = mid + 1 ;
else :
h = mid - 1
return h
def countElements(arr1, arr2, m, n):
arr2.sort()
for i in range (m):
index = bin_search(arr2, n, arr1[i])
print (index + 1 ,end = " " )
arr1 = [ 1 , 2 , 3 , 4 , 7 , 9 ]
arr2 = [ 0 , 1 , 2 , 1 , 1 , 4 ]
m = len (arr1)
n = len (arr2)
countElements(arr1, arr2, m, n)
|
C#
using System;
public class GFG {
static int binary_search( int [] arr,
int l, int h, int x)
{
while (l <= h) {
int mid = (l + h) / 2;
if (arr[mid] <= x)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
static void countEleLessThanOrEqual(
int [] arr1, int [] arr2,
int m, int n)
{
Array.Sort(arr2);
for ( int i = 0; i < m; i++) {
int index = binary_search(
arr2, 0, n - 1, arr1[i]);
Console.Write((index + 1) + " " );
}
}
public static void Main()
{
int [] arr1 = { 1, 2, 3, 4, 7, 9 };
int [] arr2 = { 0, 1, 2, 1, 1, 4 };
countEleLessThanOrEqual(arr1,
arr2, arr1.Length, arr2.Length);
}
}
|
Javascript
<script>
function binary_search(arr,l,h,x)
{
while (l <= h) {
let mid = Math.floor((l + h) / 2);
if (arr[mid] <= x)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
function countEleLessThanOrEqual(arr1,arr2,m,n)
{
arr2.sort( function (a,b){ return a-b;});
for (let i = 0; i < m; i++) {
let index = binary_search(
arr2, 0, n - 1, arr1[i]);
document.write((index + 1) + " " );
}
}
let arr1=[1, 2, 3, 4, 7, 9 ];
let arr2=[0, 1, 2, 1, 1, 4];
countEleLessThanOrEqual(
arr1, arr2, arr1.length,
arr2.length);
</script>
|
PHP
<?php
function binary_search( $arr , $l , $h , $x )
{
while ( $l <= $h )
{
$mid = ( floor ( $l + $h ) / 2);
if ( $arr [ $mid ] <= $x )
$l = $mid + 1;
else
$h = $mid - 1;
}
return $h ;
}
function countEleLessThanOrEqual( $arr1 ,
$arr2 , $m , $n )
{
sort( $arr2 ); sort( $arr2 , $n );
for ( $i = 0; $i < $m ; $i ++)
{
$index = binary_search( $arr2 , 0,
$n -1, $arr1 [ $i ]);
echo ( $index +1), " " ;
}
}
$arr1 = array (1, 2, 3, 4, 7, 9);
$arr2 = array (0, 1, 2, 1, 1, 4);
$m = sizeof( $arr1 ) / sizeof( $arr1 [0]);
$n = sizeof( $arr2 ) / sizeof( $arr2 [0]);
countEleLessThanOrEqual( $arr1 , $arr2 , $m , $n );
?>
|
Complexity Analysis:
- Time Complexity: O(mlogn + nlogn).
Considering arr1[] and arr2[] of sizes m and n respectively.
- Space Complexity: O(1).
As no extra space is required
Another way of solving the problem is to sort the second array and use the upper_bound() inbuilt function for each value of first array.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void countEleLessThanOrEqual( int arr1[], int arr2[], int m, int n)
{
sort(arr2, arr2 + n);
for ( int i = 0; i < m; i++) {
int x = upper_bound(arr2, arr2 + n, arr1[i]) - arr2;
cout << x << " " ;
}
}
int main()
{
int arr1[] = { 1, 2, 3, 4, 7, 9 };
int arr2[] = { 0, 1, 2, 1, 1, 4 };
int m = sizeof (arr1) / sizeof (arr1[0]);
int n = sizeof (arr2) / sizeof (arr2[0]);
countEleLessThanOrEqual(arr1, arr2, m, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static int upper_bound( int arr[], int key)
{
int upperBound = 0 ;
while (upperBound < arr.length)
{
if (arr[upperBound] <= key)
upperBound++;
else {
return upperBound;
}
}
return upperBound;
}
public static void countEleLessThanOrEqual( int arr1[],
int arr2[],
int m, int n)
{
Arrays.sort(arr2);
for ( int i = 0 ; i < m; i++) {
int x = upper_bound(arr2, arr1[i]);
System.out.print(x + " " );
}
}
public static void main(String[] args)
{
int arr1[] = { 1 , 2 , 3 , 4 , 7 , 9 };
int arr2[] = { 0 , 1 , 2 , 1 , 1 , 4 };
int m = arr1.length;
int n = arr2.length;
countEleLessThanOrEqual(arr1, arr2, m, n);
}
}
|
Python3
def upper_bound(arr, key):
upperBound = 0
while (upperBound < len (arr)):
if (arr[upperBound] < = key):
upperBound + = 1
else :
return upperBound
return upperBound
def countEleLessThanOrEqual(arr1, arr2, m, n):
arr2.sort()
for i in range (m):
x = upper_bound(arr2, arr1[i])
print (x, end = " " )
arr1 = [ 1 , 2 , 3 , 4 , 7 , 9 ]
arr2 = [ 0 , 1 , 2 , 1 , 1 , 4 ]
m = len (arr1)
n = len (arr2)
countEleLessThanOrEqual(arr1, arr2, m, n)
|
C#
using System;
using System.Collections;
public class GFG {
public static int upper_bound( int [] arr, int key)
{
int upperBound = 0;
while (upperBound < arr.Length) {
if (arr[upperBound] <= key)
upperBound++;
else {
return upperBound;
}
}
return upperBound;
}
public static void countEleLessThanOrEqual( int [] arr1,
int [] arr2,
int m, int n)
{
Array.Sort(arr2);
for ( int i = 0; i < m; i++) {
int x = upper_bound(arr2, arr1[i]);
Console.Write(x + " " );
}
}
static public void Main()
{
int [] arr1 = { 1, 2, 3, 4, 7, 9 };
int [] arr2 = { 0, 1, 2, 1, 1, 4 };
int m = arr1.Length;
int n = arr2.Length;
countEleLessThanOrEqual(arr1, arr2, m, n);
}
}
|
Javascript
function upper_bound(arr, key)
{
let upperBound = 0;
while (upperBound < arr.length)
{
if (arr[upperBound] <= key)
upperBound++;
else {
return upperBound;
}
}
return upperBound;
}
function countEleLessThanOrEqual(arr1, arr2, m, n)
{
arr2.sort();
for (let i = 0; i < m; i++) {
let x = upper_bound(arr2, arr1[i]);
console.log(x + " " );
}
}
let arr1 = [ 1, 2, 3, 4, 7, 9 ];
let arr2 = [ 0, 1, 2, 1, 1, 4 ];
let m = arr1.length;
let n = arr2.length;
countEleLessThanOrEqual(arr1, arr2, m, n);
|
Time Complexity: O(n logn + m log n), where m and n represents the size of the given two arrays.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Another Approach: We can also use two pointers to find our solution. first, sort both the arrays. after sorting put i pointer for arr1 and j pointer for arr2 at the beginning. we will traverse over the elements of arr1 by using i pointer & inside this loop, we will go over each element of arr2 by j pointer. wherever arr2[j] <= arr1[i] we will increase j . if the condition fails print j.
Note:- this will give answer in sorted manner
C++
#include <bits/stdc++.h>
using namespace std;
void countEleLessThanOrEqual( int arr1[], int arr2[], int m, int n)
{
sort(arr1, arr1 + m);
sort(arr2, arr2 + n);
int j = 0;
for ( int i = 0; i < m; i++)
{
while (j < n && arr2[j] <= arr1[i])
j++;
cout << j << " " ;
}
}
int main()
{
int arr1[] = {1, 2, 3, 4, 7, 9};
int arr2[] = {0, 1, 2, 1, 1, 4};
int m = sizeof (arr1) / sizeof (arr1[0]);
int n = sizeof (arr2) / sizeof (arr2[0]);
countEleLessThanOrEqual(arr1, arr2, m, n);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static void countEleLessThanOrEqual( int [] arr1,
int [] arr2, int m,
int n)
{
Arrays.sort(arr1);
Arrays.sort(arr2);
int j = 0 ;
for ( int i = 0 ; i < m; i++)
{
while (j < n && arr2[j] <= arr1[i])
j++;
System.out.print(j + " " );
}
}
public static void main(String[] args)
{
int [] arr1 = { 1 , 2 , 3 , 4 , 7 , 9 };
int [] arr2 = { 0 , 1 , 2 , 1 , 1 , 4 };
int m = arr1.length;
int n = arr2.length;
countEleLessThanOrEqual(arr1, arr2, m, n);
}
}
|
Python3
def countEleLessThanOrEqual(arr1, arr2, m, n):
arr1.sort()
arr2.sort()
j = 0
for i in range (m):
while (j < n and arr2[j] < = arr1[i]):
j + = 1
print (j, end = " " )
arr1 = [ 1 , 2 , 3 , 4 , 7 , 9 ]
arr2 = [ 0 , 1 , 2 , 1 , 1 , 4 ]
m = len (arr1)
n = len (arr2)
countEleLessThanOrEqual(arr1, arr2, m, n)
" This code is contributed by rajatkumargla19"
|
C#
using System;
public class GFG
{
static void countEleLessThanOrEqual( int [] arr1,
int [] arr2, int m,
int n)
{
Array.Sort(arr1);
Array.Sort(arr2);
int j = 0;
for ( int i = 0; i < m; i++) {
while (j < n && arr2[j] <= arr1[i]) {
j++;
}
Console.Write(j + " " );
}
}
public static void Main()
{
int [] arr1 = { 1, 2, 3, 4, 7, 9 };
int [] arr2 = { 0, 1, 2, 1, 1, 4 };
countEleLessThanOrEqual(arr1, arr2, arr1.Length,
arr2.Length);
}
}
|
Javascript
function countEleLessThanOrEqual(arr1, arr2, m, n){
arr1.sort();
arr2.sort();
let j = 0;
for (let i = 0; i < m; i++)
{
while (j < n && arr2[j] <= arr1[i])
j++;
console.log(j + " " );
}
}
let arr1 = [ 1, 2, 3, 4, 7, 9 ];
let arr2 = [ 0, 1, 2, 1, 1, 4 ];
let m = arr1.length;
let n = arr2.length;
countEleLessThanOrEqual(arr1, arr2, m, n);
|
Time Complexity: O(nlogn + mlogm)
Auxiliary Space: O(1)
Another Approach: prefix-sum technique and hashing
Follow the steps to implement the approach:
- Create a hash table to store the frequency of elements in arr2. Initialize the hash table with zeros.
- Iterate through arr2 and update the frequency of each element in the hash table.
- Create a prefix sum array prefixSum of size 100010 (maximum element value + 10). Initialize prefixSum[0] with the frequency of the first element in arr2.
- Calculate the prefix sum array by adding the current frequency with the previous prefix sum.
- Iterate through arr1. For each element arr1[i], access prefixSum[arr1[i]] to get the count of elements less than or equal to arr1[i] in arr2.
- Store the counts in a result array or directly print them.
Below is the implementation:
C++
#include <iostream>
#include <vector>
using namespace std;
void countElements( int arr1[], int arr2[], int m, int n)
{
int result[m];
int frequency[100010] = {
0
};
for ( int i = 0; i < n; ++i) {
frequency[arr2[i]]++;
}
int prefixSum[100010];
prefixSum[0] = frequency[0];
for ( int i = 1; i < 100010; ++i) {
prefixSum[i] = prefixSum[i - 1] + frequency[i];
}
for ( int i = 0; i < m; ++i) {
result[i] = prefixSum[arr1[i]];
}
for ( int i = 0; i < m; ++i) {
cout << result[i] << " " ;
}
}
int main()
{
int arr1[] = { 1, 2, 3, 4, 7, 9 };
int arr2[] = { 0, 1, 2, 1, 1, 4 };
int m = sizeof (arr1) / sizeof (arr1[0]);
int n = sizeof (arr2) / sizeof (arr2[0]);
countElements(arr1, arr2, m, n);
return 0;
}
|
Java
import java.util.Arrays;
public class GFG {
public static void countElements( int [] arr1, int [] arr2,
int m, int n)
{
int [] result = new int [m];
int [] frequency = new int [ 100010 ];
for ( int i = 0 ; i < n; ++i) {
frequency[arr2[i]]++;
}
int [] prefixSum = new int [ 100010 ];
prefixSum[ 0 ] = frequency[ 0 ];
for ( int i = 1 ; i < 100010 ; ++i) {
prefixSum[i] = prefixSum[i - 1 ] + frequency[i];
}
for ( int i = 0 ; i < m; ++i) {
result[i] = prefixSum[arr1[i]];
}
for ( int i = 0 ; i < m; ++i) {
System.out.print(result[i] + " " );
}
}
public static void main(String[] args)
{
int [] arr1 = { 1 , 2 , 3 , 4 , 7 , 9 };
int [] arr2 = { 0 , 1 , 2 , 1 , 1 , 4 };
int m = arr1.length;
int n = arr2.length;
countElements(arr1, arr2, m, n);
}
}
|
Python3
def countElements(arr1, arr2, m, n):
result = [ 0 ] * m
frequency = [ 0 ] * 100010
for i in range (n):
frequency[arr2[i]] + = 1
prefixSum = [ 0 ] * 100010
prefixSum[ 0 ] = frequency[ 0 ]
for i in range ( 1 , 100010 ):
prefixSum[i] = prefixSum[i - 1 ] + frequency[i]
for i in range (m):
result[i] = prefixSum[arr1[i]]
for i in range (m):
print (result[i], end = " " )
print ()
if __name__ = = "__main__" :
arr1 = [ 1 , 2 , 3 , 4 , 7 , 9 ]
arr2 = [ 0 , 1 , 2 , 1 , 1 , 4 ]
m = len (arr1)
n = len (arr2)
countElements(arr1, arr2, m, n)
|
C#
using System;
public class GFG {
public static void CountElements( int [] arr1, int [] arr2,
int m, int n)
{
int [] result = new int [m];
int [] frequency
= new int [100010];
for ( int i = 0; i < n; ++i) {
frequency[arr2[i]]++;
}
int [] prefixSum = new int [100010];
prefixSum[0] = frequency[0];
for ( int i = 1; i < 100010; ++i) {
prefixSum[i] = prefixSum[i - 1] + frequency[i];
}
for ( int i = 0; i < m; ++i) {
result[i] = prefixSum[arr1[i]];
}
for ( int i = 0; i < m; ++i) {
Console.Write(result[i] + " " );
}
}
public static void Main( string [] args)
{
int [] arr1 = { 1, 2, 3, 4, 7, 9 };
int [] arr2 = { 0, 1, 2, 1, 1, 4 };
int m = arr1.Length;
int n = arr2.Length;
CountElements(arr1, arr2, m, n);
}
}
|
Javascript
function countElements(arr1, arr2, m, n) {
let result = [];
let frequency = new Array(100010).fill(0);
for (let i = 0; i < n; ++i) {
frequency[arr2[i]]++;
}
let prefixSum = [];
prefixSum[0] = frequency[0];
for (let i = 1; i < 100010; ++i) {
prefixSum[i] = prefixSum[i - 1] + frequency[i];
}
for (let i = 0; i < m; ++i) {
result[i] = prefixSum[arr1[i]];
}
for (let i = 0; i < m; ++i) {
console.log(result[i] + " " );
}
}
let arr1 = [1, 2, 3, 4, 7, 9];
let arr2 = [0, 1, 2, 1, 1, 4];
let m = arr1.length;
let n = arr2.length;
countElements(arr1, arr2, m, n);
|
Time Complexity: O(n + m)
Auxiliary Space: O(m)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!