I have to find the most frequent number (or mode) from a sorted array of ranges. This range consists simply of a start and end number that is inclusive. As an example arr[0] could contain the numbers {0, 3}, which would then mean the numbers {0, 1, 2, 3}. The ranges are sorted by start number, and when start numbers are equal they are sorted by the end number. Both in ascending order.
The array is filled with n of these ranges. I need to find a way to find the number that occurs in the most ranges.
I have thought of a solution that goes through all the numbers once, but this is in O(n * m), where m is the average length of the ranges. This is an horrendously slow algorithm for the size I am dealing with.
I have also looked at some faster solutions such as this, but I can't think of an efficient way of implementing it when you cannot easily find the kth number, because the ranges can be wildly different sizes.
I'm currently trying to implement this in C, but any idea's or links to resources dealing with this are greatly appreciated.
{a, b}
to two events "add 1 at a
" and "subtract 1 at b+1
".For example, if we have 3 ranges {0, 5}, {2, 9}, {4, 7}
, each range will be like this:
0123456789
------
--------
----
And sorted events are:
Executing these events, the value becomes the highest 3 after executing the 3rd event and before executing the 4th event. Therefore we can say that the most appering numbers are 4 and 5.
The time complexity is O(N log N) because:
The space complexity is O(N) for storing the events.