For each element in 1st array count elements less than or equal to it in 2nd array - GeeksforGeeks

13 Feb, 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[].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.
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.
 
C++
Java
Python3
C#
Javascript
// C++ code for the above algorithm#include <bits/stdc++.h>using namespace std; // Function to count for each// element in 1st array,// elements less than or equal// to it in 2nd arrayvoid countEleLessThanOrEqual(int arr1[], int arr2[],                             int m, int n){    // Run two loops to count    // First loop to traverse the first array    // Second loop to traverse the second array    for (int i = 0; i < m; i++) {        int count = 0;         // Traverse through second array        for (int j = 0; j < n; j++)            if (arr2[j] <= arr1[i])                count++;         cout << count << " ";    }} // Driver program to test aboveint 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;}
import java.util.Arrays; class GFG {     // function to count for each    // element in 1st array,    // elements less than or equal    // to it in 2nd array    static int countEleLessThanOrEqual(        int arr1[], int arr2[],        int m, int n)    {        // Run two loops to count        // First loop to traverse the first array        // Second loop to traverse the second array        for (int i = 0; i < m; i++) {            int count = 0;             // Traverse through second array            for (int j = 0; j < n; j++)                if (arr2[j] <= arr1[i])                    count++;            System.out.print(count + " ");        }        return m;    }     // Driver method    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);    }} // This code is contributed by shivanisinghss2110
# Python3 code for the above algorithm # function to count for each element in 1st array,# elements less than or equal to it in 2nd arraydef countEleLessThanOrEqual(arr1, arr2, m, n):         # Run two loops to count    # First loop to traverse the first array    # Second loop to traverse the second array    for i in range(m):                 count = 0        # Traverse through second array        for j in range(n):            if (arr2[j] <= arr1[i]):                count+= 1                     print(count, end =" ") # Driver program to test abovearr1 = [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 shubhamsingh10
// C# implementation of For each elementusing System; class GFG {     // function to count for each element in 1st array,    // elements less than or equal to it in 2nd array    static void countEleLessThanOrEqual(        int[] arr1, int[] arr2,        int m, int n)    {        // Run two loops to count        // First loop to traverse the first array        // Second loop to traverse the second array        for (int i = 0; i < m; i++) {            int count = 0;             // Traverse through second array            for (int j = 0; j < n; j++)                if (arr2[j] <= arr1[i])                    count++;            Console.Write((count) + " ");        }    }     // Driver method    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);    }} // This code is contributed by mohit kumar 29.
<script> // JavaScript code for the above algorithm // Function to count for each// element in 1st array,// elements less than or equal// to it in 2nd arrayfunction countEleLessThanOrEqual(arr1, arr2, m, n){    // Run two loops to count    // First loop to traverse the first array    // Second loop to traverse the second array    for (let i = 0; i < m; i++) {        let count = 0;         // Traverse through second array        for (let j = 0; j < n; j++)            if (arr2[j] <= arr1[i])                count++;         document.write(count + " ");    }} // Driver program to test above     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);  // This code is contributed by Surbhi Tyagi. </script>
4 5 5 6 6 6 
Output:  
4 5 5 6 6 6 
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.
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++
Java
Python3
C#
PHP
Javascript
// C++ implementation of For each element in 1st// array count elements less than or equal to it// in 2nd array#include <bits/stdc++.h> using namespace std; // function returns the index of largest element// smaller than equal to 'x' in 'arr'. For duplicates// it returns the last index of occurrence of required// element. If no such element exits then it returns -1.int binary_search(int arr[], int l, int h, int x){    while (l <= h) {        int mid = (l + h) / 2;         // if 'x' is greater than or equal to arr[mid],        // then search in arr[mid+1...h]        if (arr[mid] <= x)            l = mid + 1;         // else search in arr[l...mid-1]        else            h = mid - 1;    }     // required index    return h;} // function to count for each element in 1st array,// elements less than or equal to it in 2nd arrayvoid countEleLessThanOrEqual(    int arr1[], int arr2[],    int m, int n){    // sort the 2nd array    sort(arr2, arr2 + n);     // for each element of 1st array    for (int i = 0; i < m; i++) {        // last index of largest element        // smaller than or equal to x        int index = binary_search(            arr2, 0, n - 1, arr1[i]);         // required count for the element arr1[i]        cout << (index + 1) << " ";    }} // Driver program to test aboveint 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 implementation of For// each element in 1st// array count elements less// than or equal to it// in 2nd array import java.util.Arrays; class GFG {    // method returns the index    // of largest element    // smaller than equal to 'x'    // in 'arr'. For duplicates    // it returns the last index    // of occurrence of required    // element. If no such element    // exits then it returns -1.    static int binary_search(        int arr[], int l,        int h, int x)    {        while (l <= h) {            int mid = (l + h) / 2;             // if 'x' is greater than or equal            // to arr[mid], then search in            // arr[mid+1...h]            if (arr[mid] <= x)                l = mid + 1;             // else search in arr[l...mid-1]            else                h = mid - 1;        }         // Required index        return h;    }     // Method to count for each    // element in 1st array,    // elements less than or equal    // to it in 2nd array    static void countEleLessThanOrEqual(        int arr1[], int arr2[],        int m, int n)    {        // Sort the 2nd array        Arrays.sort(arr2);         // for each element of 1st array        for (int i = 0; i < m; i++) {            // Last index of largest element            // smaller than or equal to x            int index = binary_search(                arr2, 0, n - 1, arr1[i]);             // Required count for the element arr1[i]            System.out.print((index + 1) + " ");        }    }     // Driver method    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);    }}
# python implementation of For each element in 1st# array count elements less than or equal to it# in 2nd array # function returns the index of largest element# smaller than equal to 'x' in 'arr'. For duplicates# it returns the last index of occurrence of required# element. If no such element exits then it returns -1def bin_search(arr, n, x):     l = 0  h = n - 1  while(l <= h):      mid = int((l + h) // 2)      # if 'x' is greater than or equal to arr[mid],      # then search in arr[mid + 1...h]      if(arr[mid] <= x):          l = mid + 1;      else:          # else search in arr[l...mid-1]          h = mid - 1  # required index  return h # function to count for each element in 1st array,# elements less than or equal to it in 2nd arraydef countElements(arr1, arr2, m, n):  # sort the 2nd array  arr2.sort()   # for each element in first array  for i in range(m):      # last index of largest element      # smaller than or equal to x      index = bin_search(arr2, n, arr1[i])      # required count for the element arr1[i]      print(index + 1,end=" ") # driver program to test above functionarr1 = [1, 2, 3, 4, 7, 9]arr2 = [0, 1, 2, 1, 1, 4]m = len(arr1)n = len(arr2)countElements(arr1, arr2, m, n) # This code is contributed by Aditi Sharma
// C# implementation of For each element// in 1st array count elements less than// or equal to it in 2nd arrayusing System; public class GFG {     // method returns the index of    // largest element smaller than    // equal to 'x' in 'arr'. For    // duplicates it returns the last    // index of occurrence of required    // element. If no such element    // exits then it returns -1.    static int binary_search(int[] arr,                             int l, int h, int x)    {        while (l <= h) {            int mid = (l + h) / 2;             // if 'x' is greater than or            // equal to arr[mid], then            // search in arr[mid+1...h]            if (arr[mid] <= x)                l = mid + 1;             // else search in            // arr[l...mid-1]            else                h = mid - 1;        }         // required index        return h;    }     // method to count for each element    // in 1st array, elements less than    // or equal to it in 2nd array    static void countEleLessThanOrEqual(        int[] arr1, int[] arr2,        int m, int n)    {         // sort the 2nd array        Array.Sort(arr2);         // for each element of 1st array        for (int i = 0; i < m; i++) {            // last index of largest            // element smaller than or            // equal to x            int index = binary_search(                arr2, 0, n - 1, arr1[i]);             // required count for the            // element arr1[i]            Console.Write((index + 1) + " ");        }    }     // Driver method    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);    }} // This code is contributed by Sam007.
<?php// php implementation of For each element// in 1st array count elements less than// or equal to it in 2nd array // function returns the index of largest// element smaller than equal to 'x' in// 'arr'. For duplicates it returns the// last index of occurrence of required// element. If no such element exits then// it returns -1.function binary_search($arr, $l, $h, $x){    while ($l <= $h)    {        $mid = (floor($l+$h) / 2);         // if 'x' is greater than or        // equal to arr[mid], then        // search in arr[mid+1...h]        if ($arr[$mid] <= $x)            $l = $mid + 1;         // else search in arr[l...mid-1]        else            $h = $mid - 1;    }         // required index    return $h;} // function to count for each element// in 1st array, elements less than or// equal to it in 2nd arrayfunction countEleLessThanOrEqual($arr1,                           $arr2, $m, $n){    // sort the 2nd array    sort($arr2); sort($arr2, $n);         // for each element of 1st array    for ($i = 0; $i < $m; $i++)    {        // last index of largest element        // smaller than or equal to x        $index = binary_search($arr2, 0,                        $n-1, $arr1[$i]);                 // required count for the        // element arr1[i]        echo ($index+1), " ";    }} // Driver program to test above$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);  //This code is contributed by nitin mittal.?>
<script> // Javascript implementation of For// each element in 1st// array count elements less// than or equal to it// in 2nd array         // method returns the index    // of largest element    // smaller than equal to 'x'    // in 'arr'. For duplicates    // it returns the last index    // of occurrence of required    // element. If no such element    // exits then it returns -1.       function binary_search(arr,l,h,x)    {        while (l <= h) {            let mid = Math.floor((l + h) / 2);              // if 'x' is greater than or equal            // to arr[mid], then search in            // arr[mid+1...h]            if (arr[mid] <= x)                l = mid + 1;              // else search in arr[l...mid-1]            else                h = mid - 1;        }          // Required index        return h;    }         // Method to count for each    // element in 1st array,    // elements less than or equal    // to it in 2nd array    function countEleLessThanOrEqual(arr1,arr2,m,n)    {        // Sort the 2nd array        arr2.sort(function(a,b){return a-b;});          // for each element of 1st array        for (let i = 0; i < m; i++) {            // Last index of largest element            // smaller than or equal to x            let index = binary_search(                arr2, 0, n - 1, arr1[i]);              // Required count for the element arr1[i]            document.write((index + 1) + " ");        }    }         // Driver method    let arr1=[1, 2, 3, 4, 7, 9 ];    let arr2=[0, 1, 2, 1, 1, 4];    countEleLessThanOrEqual(            arr1, arr2, arr1.length,            arr2.length);  // This code is contributed by patel2127 </script>
4 5 5 6 6 6 
Output:  
4 5 5 6 6 6
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.
C++
// C++ implementation of For each element in 1st// array count elements less than or equal to it// in 2nd array#include <bits/stdc++.h>using namespace std; // function to count for each element in 1st array,// elements less than or equal to it in 2nd arrayvoid countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n){    // sort the 2nd array    sort(arr2, arr2 + n);     // for each element of 1st array    for (int i = 0; i < m; i++) {        int x = upper_bound(arr2, arr2 + n, arr1[i]) - arr2;        cout << x << " ";    }} // Driver program to test aboveint 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;} // This code is contributed by Aditya Kumar (adityakumar129)
4 5 5 6 6 6 
This article is contributed by Ayush Jauhari. 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.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Sam007
nitin mittal
andrew1234
SHUBHAMSINGH10
mohit kumar 29
shivanisinghss2110
surbhityagi15
patel2127
amartyaghoshgfg
adityakumar129
Amazon
Binary Search
Arrays
Searching
Amazon
Arrays
Searching
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Binary Search
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1