Skip to content
Advertisement

Count of elements from the array

I am counting the element from array, which is greater then the given element (k)

JavaScript

I solved with comparing only one number, but what if I have an array to compare with

Advertisement

Answer

A simple O(nk) solution would be to go through arr for each number in arr2 and count the number of values that are greater.

JavaScript

However, we can do better than this by extending the method you’ve already identified – sorting arr and using binary search to identify the position of each value in arr2. If arr2 is also sorted then we can use the previously identified position as the initial left-hand edge of our binary search, since we know that subsequent elements in arr2 have to be greater than the current value.

Here’s some Java code to illustrate:

JavaScript

I’ve simplified the code quite a bit by making use of the Arrays.binarySearch method.

For small values of n and k the simple approach will probably be faster, but as they grow the binarySearch approach will take over, despite the cost of the initial sort.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement