This code finds the intersections of all overlapping intervals.
Example: if [0-20]
, [15-40]
, and [25-50]
are the 3 intervals then the output should be [15-20]
and [25-40]
.
I could not find an answer with complexity less than \$O(n^2)\$. Please suggest a better solution if one exists. Additionally, assume the input intervals are sorted by their start times.
public static Set<OverlapCoord> getOverlap(List<Interval> intervalList) {
if (intervalList == null) {
throw new NullPointerException("Input list cannot be null.");
}
final HashSet<OverlapCoord> hashSet = new HashSet<OverlapCoord>();
for (int i = 0; i < intervalList.size() - 1; i++) {
final Interval intervali = intervalList.get(i);
for (int j = 0; j < intervalList.size(); j++) {
final Interval intervalj = intervalList.get(j);
if (intervalj.getStart() < intervali.getEnd() && intervalj.getEnd() > intervali.getStart() && i != j) {
hashSet.add(new OverlapCoord(Math.max(intervali.getStart(),intervalj.getStart()),
Math.min(intervali.getEnd(), intervalj.getEnd())));
}
}
}
return hashSet;
}