Determine if Two Events Have Conflict

Similar question: 836. Rectangle Overlap

Consider two segments (or intervals) as two time slots. Let’s say we have the following two time slots:

  • Slot 1: 1 PM to 3 PM
  • Slot 2: 2 PM to 4 PM

These slots represent two events happening during the day. Now we want to find out if these two time slots overlap or not.

To understand if they overlap, we need to check if there is any common time between these two slots. In this case, between 2 PM and 3 PM, both events are happening at the same time.

To express this programmatically, we need to check if the start of one slot is before or equal to the end of the other slot, and if the start of the other slot is before or equal to the end of the first slot.

For our example, the start of Slot 1 (1 PM) is before the end of Slot 2 (4 PM), and the start of Slot 2 (2 PM) is before the end of Slot 1 (3 PM). So, these two slots overlap.

Expressed in code as:

  • left1 <= right2 && left2 <= right1

This is a general rule for checking overlap, not just for time slots but also for any kind of segments or intervals, such as ranges of numbers.

So, any time you have two intervals and you need to check if they overlap, you can use this rule. This rule ensures that we don’t have any false positives (identifying overlap when there isn’t any) or false negatives (missing an overlap). In other words, it is a sufficient (enough) and necessary (required) condition to determine if two intervals overlap.

class Solution:
    def haveConflict(self, event1: List[str], event2: List[str]) -> bool:
        return event1[0] <= event2[1] and event2[0] <= event1[1]