Course contentsShow
← Python
Lesson 706 of 1,06011. Standard Library EssentialsFree lesson

Managing Overlapping Time Intervals

Identify and resolve conflicts when processing overlapping time intervals by calculating intersections and unions between multiple time-based ranges.

In this lesson, you will learn how to identify, merge, and find intersections between overlapping time intervals to streamline scheduling and resource management.

Understanding Overlaps

When dealing with time-based data—such as meeting room bookings or task schedules—you often encounter intervals represented as (start, end) tuples. Two intervals (s1, e1) and (s2, e2) overlap if max(s1, s2) < min(e1, e2).

Merging Intervals

To process a collection of intervals, the most efficient strategy is to first sort them by their start times. Once sorted, you can iterate through the list, comparing each interval with the last "merged" one. If the current interval’s start time is less than or equal to the previous interval’s end time, you have an overlap and can merge them by updating the end time to max(end1, end2).

def merge_intervals(intervals):
    if not intervals: return []
    intervals.sort()
    merged = [intervals[0]]
    for current_start, current_end in intervals[1:]:
        last_start, last_end = merged[-1]
        if current_start <= last_end:
            merged[-1] = (last_start, max(last_end, current_end))
        else:
            merged.append((current_start, current_end))
    return merged

Calculating Intersections

If your goal is to find where multiple time ranges intersect (e.g., finding the shared free time of two calendars), the logic changes. An intersection exists only if the max of the start times is less than the min of the end times.

def get_intersection(i1, i2):
    start = max(i1[0], i2[0])
    end = min(i1[1], i2[1])
    return (start, end) if start < end else None

Why This Matters

By treating time intervals as mathematical ranges, you can move beyond simple list storage to robust logic. Whether you are building a booking system or analyzing log files, sorting by start time is the "golden rule" that reduces a complex O(n2)O(n^2) comparison problem into a linear O(nlog⁡n)O(n \log n) pass. Once your intervals are consolidated or intersected, you can easily determine total duration, identify gaps, or assign resources without conflict.

Key Takeaway: Always sort your time intervals by start time first, as it transforms the complex task of finding overlaps into a straightforward, linear scan of the data.