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]
This problem is already discussed in the previous post. 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 small range. A range of values that can be used as index in an array.
The idea is to use an array to create a direct address table initially filled with zero, such that hash[i] gives the count of an element in the second array arr2. Now, calculate pre-sum of the hash array. Doing this, hash[i] will now give the count of elements less than or equal to in second array arr2.
Now, traverse the first array and print hash[arr1[i]].
Below program illustrate the above approach:
4 5 5 6 6 6
Another method:(Using vector and map)
4 5 5 6 6 6
- For each element in 1st array count elements less than or equal to it in 2nd array
- Count equal element pairs in the given array
- Adding elements of an array until every element becomes greater than or equal to k
- 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 XOR of remaining elements
- Check if the array has an element which is equal to sum of all the remaining elements
- Check if the array has an element which is equal to product of remaining elements
- Count pairs in an array such that both elements has equal set bits
- Count of index pairs with equal elements in an array
- Count of smaller or equal elements in sorted array
- Count elements less than or equal to a given value in a sorted rotated array
- Noble integers in an array (count of greater elements is equal to value)
- Count elements that are divisible by at-least one element in another array
- Find an element in array such that sum of left array is equal to sum of right array
- Count the number of elements which are greater than any of element on right side of an array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.