Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to efficiently merge int ranges in a stream?

We are given a continuous stream of integer ranges like [1,3], [5,10], [2,6], ... when each new range comes, we need to check with existing ranges and see if it overlaps with any existing range, and if any overlap is found, all the overlapping ranges are removed and the merged range is inserted instead. We need an efficient algorithm for this. Note that the range comes one at a time which forms a stream...

Was asked this question during an interview. Ideas?

The intent is to merge overlapping ranges into one. for example, if we have 3 ranges coming in the following order: [1,3], [2,6], [5,10]. Then we first merge the first two into [1,6], then merge with the 3rd and it becomes [1,10].

like image 836
Robin Avatar asked Jan 20 '11 14:01

Robin


People also ask

How do you combine intervals?

A simple approach is to start from the first interval and compare it with all other intervals for overlapping, if it overlaps with any other interval, then remove the other interval from the list and merge the other into the first interval. Repeat the same steps for the remaining intervals after the first.

How do you find overlapping intervals?

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.


1 Answers

The standard algorithm for this problem is an interval tree.

like image 198
Keith Randall Avatar answered Sep 22 '22 05:09

Keith Randall