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.
Input : arr1 = [1, 2, 3, 4, 7, 9] arr2 = [0, 1, 2, 1, 1, 4] Output : [4, 5, 5, 6, 6, 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]
Naive Approach: Using two loops, outer loop for elements of array arr1 and inner loop for elements of array arr2. Then for each element of arr1, count elements less than or equal to it in arr2.
Time complexity: O(m * n), considering arr1 and arr2 are of sizes m and n respectively.
Efficient 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.
4 5 5 6 6 6
Time Complexity: O(mlogn + nlogn), considering arr1 and arr2 are of sizes m and n respectively.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
- For each element in 1st array count elements less than or equal to it in 2nd array | Set 2
- Sum of elements in an array with frequencies greater than or equal to that element
- Check if the array has an element which is equal to sum of all the remaining elements
- Adding elements of an array until every element becomes greater than or equal to k
- Check if the array has an element which is equal to product of remaining elements
- Count of smaller or equal elements in sorted array
- Count elements less than or equal to a given value in a sorted rotated array
- Count pairs in an array such that both elements has equal set bits
- Count of index pairs with equal elements in an array
- Noble integers in an array (count of greater elements is equal to value)
- Find an element in array such that sum of left array is equal to sum of right array
- Count of only repeated element in a sorted array of consecutive elements
- Arrange array elements such that last digit of an element is equal to first digit of the next element
- Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
- Check if there exist two elements in an array whose sum is equal to the sum of rest of the array