I have an application where I have a series of non overlapping fixed width intervals, each of which have a given key. Each interval has the same width, and there may be contiguous intervals. Essentially I want to group the intervals and keys in such a way that I minimize the amount of separate intervals. This could be done by merging contiguous intervals with the same key or looking for matching intervals and combining them into single intervals with multiple keys. My current algorithm tries the above two approaches and sees which results in the smallest number of intervals, but I feel like there must be a smarter way of approaching the problem. Any advice would be much appreciated!
For example:
|-----| |-----| intervals with key k1 (contiguous)
|-----| interval with key k2
|-----| interval with key k3
In this problem the intervals with key k1 could be merged to a single contiguous interval, resulting in 3 instead of four total intervals. Or the first interval for each key k1, k2 and k3 could be combined to one interval with keys k1, k2 and k3, resulting in one interval plus the second remaining interval in k1.
Worst case would be something like 70,000 intervals.