Problem
Given a set of intervals with possibly non-distinct start and end points, find all maximal gaps. A gap is defined as an interval that does not overlap with any given interval. All endpoints are integers and inclusive.
For example, given the following set of intervals:
$\{[2,6], [1,9], [12,19]\}$
The set of all maximal gaps is:
$\{[10,11]\}$
For the following set of intervals:
$\{[2,6], [1,9], [3,12], [18,20]\}$
The set of all maximal gaps is:
$\{[13,17]\}$
because that produces the maximal gap.
Proposed Algorithm
My proposed algorithm (modified approach taken by John L.) to compute these gaps is:
- Order the intervals by ascending start date.
- Initialise an empty list
gaps
that will store gaps - Initialise a variable,
last_covered_point
, to the end point of the first interval. - Iterate through all intervals in the sorted order. For each interval
[start, end]
, do the following.- If
start > last_covered_point + 1
, add the gap,[last_covered_point + 1, start - 1]
togaps
. - Assign
max(last_covered_point, end)
tolast_covered_point
.
- If
- Return
gaps
I have tested my algorithm on a few cases and it produces the correct results. But I cannot say with 100% guarantee that it works for every interval permutation and combination. Is there a way to prove this handles every permutation and combination?