Skip to content
PHP Logo

How can PHP developers optimize their code to avoid quadratic time complexity when checking for overlapping time slots in an array?

When checking for overlapping time slots in an array, PHP developers can optimize their code by sorting the array based on the start time of each slot. Then, they can iterate through the sorted array and compare each time slot with the next one to determine if there is an overlap. This approach reduces the time complexity from quadratic to linear.

php
function checkOverlap($timeSlots) {
    usort($timeSlots, function($a, $b) {
        return $a['start'] - $b['start'];
    });

    $n = count($timeSlots);
    for ($i = 0; $i < $n - 1; $i++) {
        if ($timeSlots[$i]['end'] > $timeSlots[$i + 1]['start']) {
            return true; // Overlapping time slots found
        }
    }

    return false; // No overlapping time slots
}

// Example usage
$timeSlots = [
    ['start' => 1, 'end' => 3],
    ['start' => 2, 'end' => 4],
    ['start' => 5, 'end' => 7]
];

if (checkOverlap($timeSlots)) {
    echo "Overlapping time slots found";
} else {
    echo "No overlapping time slots";
}