How to detect whether any intervals overlap in a list of start and end times with PHP

1 Answer

0 votes
function hasOverlap(array $intervals): bool {
    if (empty($intervals)) {
        return true;
    }

    // Sorting is essential because once intervals are ordered by 
    // start time, any overlap can only occur between adjacent intervals.
    usort($intervals, function($a, $b) {
        return $a[0] <=> $b[0];
    });
    // (5,9), (11,12), (15,17)

    // (5,9) and (11,12) → 11 < 9? No
    // (11,12) and (15,17) → 15 < 12? No

    // The loop compares each interval with the one before it.
    for ($i = 1; $i < count($intervals); $i++) {
        if ($intervals[$i][0] < $intervals[$i - 1][1]) {
            return false; // Overlap found
        }
    }

    return true; // No overlap
}

$intervals = [
    [11, 12],
    [5, 9],
    [15, 17]
];

if (hasOverlap($intervals)) {
    echo "There are NO overlapping intervals\n";
} else {
    echo "There ARE overlapping intervals\n";
}



/*
run:

There are NO overlapping intervals

*/

 



answered Apr 8 by avibootz

Related questions

...