How can I find an overlap between two given ranges? [closed]

Two ranges overlap in one of two basic cases:

  • one range contains the other completely (i.e. both the start and end of one range are between the start and end of the other), or
  • the start or end of one range is contained within the other range

Conversely, they do not overlap only if neither endpoint of each range is contained within the other range (cases 11 and 12 in your diagram). We can check whether the low end of either range is past the high end of the other, to detect both those cases:

if (a > d || c < b) {
    // no overlap
}
else {
    // overlap
}

We can invert the condition and then use DeMorgan’s laws to swap the order, if that’s preferable:

if (a <= d && c >= b) {
    // overlap
}
else {
    // no overlap
}

To find the actual overlap range, you take the maximum of the two low ends, and the minimum of the two high ends:

int e = Math.max(a,b);
int f = Math.min(c,d);
// overlapping range is [e,f], and overlap exists if e <= f.

All above assumes that the ranges are inclusive, that is, the range defined by a and c includes both the value of a and the value of c. It is fairly trivial to adjust for exclusive ranges, however.

Leave a Comment