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

1 Answer

0 votes
def has_overlap(intervals):
    if not intervals:
        return True

    # Sorting is essential because once intervals are ordered by 
    # start time, any overlap can only occur between adjacent intervals.
    intervals.sort(key=lambda x: x[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 in range(1, len(intervals)):
        if intervals[i][0] < intervals[i - 1][1]:
            return False  # Overlap found

    return True  # No overlap


def main():
    intervals = [[11, 12], [5, 9], [15, 17]]

    if has_overlap(intervals):
        print("There are NO overlapping intervals")
    else:
        print("There ARE overlapping intervals")


if __name__ == "__main__":
    main()


"""
run:

There are NO overlapping intervals

"""

 



answered Apr 8 by avibootz

Related questions

...