![]() |
VOOZH | about |
Given two unsorted arrays a[] and b[]. Both arrays may contain duplicate elements. For each element in a[], find the count of 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]
Explanation:
For a[0] = 1, there are 4 elements in b (0, 1, 1, 1) that are ≤ 1.
For a[1] = 2, there are 5 elements in b (0, 1, 1, 1, 2) that are ≤ 2.
For a[2] = 3, there are 5 elements in b that are ≤ 3.
Similarly, for a[3] = 4, there are 6 elements in b that are ≤ 4, and for a[4] = 7 and a[5] = 9, there are also 6 elements in b that are ≤ 7 and ≤ 9, respectively.Input: a[] = [4, 8, 7, 5, 1], b[] = [4, 48, 3, 0, 1, 1, 5]
Output: [5, 6, 6, 6, 3]
Explanation:
For a[0] = 4, there are 5 elements in b (4, 3, 0, 1, 1) that are ≤ 4.
For a[1] = 8 and a[2] = 7, there are 6 elements in b that are ≤ 8 and ≤ 7.
For a[3] = 5, there are 6 elements in b that are ≤ 5.
For a[4] = 1, there are 3 elements in b (0, 1, 1) that are ≤ 1.
Table of Content
The idea is to use two loops, the outer loop iterates through each element in array
a[], and for every element ina[], the inner loop traverses arrayb[]to count how many elements inb[]are less than or equal to the current element froma[].
4 5 5 6 6 6
The idea is to sort the elements of array b[], then perform a modified binary search on array b[]. For each element x of array a[], find the last index of the largest element smaller than or equal to x in sorted array b[]. The index of the largest element will give the count of elements.
4 5 5 6 6 6
Instead of implementing the binary search in the above approach, we can use inbuilt function upper bound in C++ (and bisect_right in Python) that returns the first index ind in the array where the value arr[ind] > target.
4 5 5 6 6 6
The core idea is to first pair each element of
a[]with its original index and sort the array based on values. Similarly,b[]is sorted to enable efficient traversal. Using a two-pointer approach, we iterate throughb[]just once, incrementing the pointer whenever the current element inb[]is less than or equal to the current element ina[]. This gives us the count of such elements efficiently. Finally, the count is stored at the original index of the corresponding element ina[], ensuring the result maintains the initial ordering ofa[].
4 5 5 6 6 6
The main idea is to first construct a frequency array for
b[]to record how often each number appears. This frequency array is then transformed into a prefix sum array, where each index holds the total count of elements inb[]that are less than or equal to that index. With this preprocessed data, the count for any element ina[]can then be retrieved in constant time.
Illustration:
4 5 5 6 6 6