Search code examples
algorithmbinary-searchinterval-tree

Given set of intervals sorted according to Start time. Count all the intervals which has Time "T" in them in O(logn)


Suppose the list of intervals may be [[1,3],[2,4],[6,12]] and the Query time T = 3. The number of intervals which have 3 in the above list are 2 (i.e) [[1,3],[2,4]]. Is it possible to do this in O(logn) time?


Solution

  • This cannot be done in O(log n) time in the general case.

    You can binary search on the start time to find the last interval that could possibly contain the query time, but because there's no implied ordering on the end times, you have sequentially search from the start of the list to the item you identified as the last to determine if the query time is in any of those intervals.

    Consider, for example, [(1,7),(2,11),(3,8),(4,5),(6,10),(7,9)], with a query time of 7.

    Binary search on the start time will tell you that all of the intervals could contain the query time. But because the ending times are not in any particular order, you can't do a binary search on them. You have to look at each individual interval to determine if the ending time is greater than or equal to the query time. Here, you see that (4,5) does not contain the query time.