You are given a set of intervals S
. You have to find all intervals in S
that are contained in a given interval (a, b)
in minimum time complexity.
This can be done in O(n)
time by brute force, where n
is the number of intervals in set S
. But if I am allowed to do some pre-processing, can this be done in less than O(n)
time e.g. O(log n)
time?
Initially I was thinking of interval tree, but I don't think it is applicable here because interval tree is used to get all intervals that overlaps with a given interval.
An Interval NUMBER in music is measuring/counting the distance between ONE note/key and another. And remember, we always count our FIRST note/key as Number ONE! D = 1st key; E = 2nd key; F = 3rd key. Therefore, Interval Number from D up to F is a 3rd (3).
Following is complete algorithm. 1) Sort all intervals in increasing order of start time. This step takes O(nLogn) time. 2) In the sorted array, if start time of an interval is less than end of previous interval, then there is an overlap.
Sort the intervals by their end point, and then take each interval in end-point order, and put it into the bucket with the largest right-most end point, such that bucket. max_endpoint < interval. startpoint. If there is no such bucket, then you have to start a new one.
You can remodel your problem in the 2D-plane. Let the (begin, end)
of each interval be a two-dimensional point. (Note that all valid intervals will end up above the diagonal)
Your Interval-search-problem transforms into well-studied orthogonal 2D range queries with algorithms that have or runtime, where k is the number of points reported.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With