To solve this problem, we need to determine the maximum number of overlapping intervals at any given time. The key insight is to use a sorted list of events (start and end of intervals) to efficiently track the number of overlapping intervals as we iterate through time.
Approach
- Event Creation: Convert each interval into two events: a start event (with a +1 delta) and an end event (with a -1 delta).
- Sorting Events: Sort the events first by time. If two events have the same time, end events (-1) are processed before start events (+1) to avoid counting non-overlapping intervals (e.g., an interval ending at time
tand another starting attdo not overlap). - Track Overlaps: Iterate through the sorted events, maintaining a count of current overlapping intervals. Update the maximum count whenever the current count exceeds the previous maximum.
Solution Code
def max_overlapping_intervals(intervals):
events = []
for start, end in intervals:
events.append((start, 1)) # Start event: increment count
events.append((end, -1)) # End event: decrement count
# Sort events: first by time, then end events (-1) come before start events (1)
events.sort(key=lambda x: (x[0], x[1]))
current_overlap = 0
max_overlap = 0
for time, delta in events:
current_overlap += delta
if current_overlap > max_overlap:
max_overlap = current_overlap
return max_overlap
Explanation
- Event Creation: Each interval contributes two events. For an interval
[s, e], we add(s, +1)(start of the interval) and(e, -1)(end of the interval). - Sorting: By sorting events, we ensure we process time in order. Handling end events first at the same time ensures we don't count intervals that just start as overlapping with those that just ended.
- Tracking: As we process each event, we adjust the current overlap count. The maximum value of this count during the iteration gives the maximum number of overlapping intervals.
This approach efficiently computes the result with a time complexity of O(n log n) due to sorting, where n is the number of intervals. This is optimal for this problem.
Example: For intervals [[1,3], [2,4], [5,7], [6,8]], the maximum overlapping count is 2 (e.g., intervals [1,3] and [2,4] overlap between 2 and 3). The code correctly returns this value.
This solution is robust and handles all edge cases, including intervals that start/end at the same time and fully overlapping intervals. It's widely used in scheduling and interval analysis problems.

作者声明:本文包含人工智能生成内容。