The following is a practice interview question that was given to me by someone, and I\'m not sure what the best solution to this is:
Given a set of ranges
I can suggest following algorithm with complexity O(n log n)
without using Intervals trees.
Let introduce some notation. We should cover a range (X,Y)
by intervals (x_i,y_i)
.
First sort given intervals (x_i,y_i)
by start point. It will take O(n log n)
Let select from intervals (x_i,y_i)
with x_i <= X
interval (x_k,y_k)
with maximum of y_i
. Because interval already sorted by start point, we can just increment index, while interval satisfies condition. If y_k
less than X
, there are no solution for given set and range. In other case interval (x_k,y_k)
contains 'X' and has maximal end point among intervals containing X
.
Now we need to cover an interval (y_k, Y)
, to satisfy overlapping condition. Because for all intervals containing X has end point less than y_k+1
, we can start from last interval from the previous step.
Each interval was used only once in this stage, so the time complexity of this part is O(n)
and in total O(n log n)
.
Following code snippet for solution:
intervals // given intervals from set S
(X, Y) // range to cover
sort intervals
i = 0 // start index
start = X // start point
result_set // set to store result
while start <= Y && i < len(intervals):
next_start = intervals[i].y
to_add = intervals[i]
while intervals[i].x <= start && i < len(intervals):
if next_start > intervals[i].y:
next_start = intervals[i].y
to_add = intervals[i]
i++
if(next_start < start):
print 'No solution'
exit
start = next_start
result_set add to_add