Peak Activity Count from Time Intervals
Greedy & IntervalsAuto-graded · 20 test casesLast updated
Tests sweep-line techniques for interval overlap detection, event aggregation at boundaries, and proper handling of half-open interval semantics.
You are analyzing activity logs where each record is a time interval [start, end) measured in seconds. Your goal is to find the maximum number of activities that were running at the same instant, and report one time when that maximum was achieved.
Interval Semantics
- Each interval
[start, end)is half-open: it includes the starting secondstartbut excludes the ending secondend. - An activity is considered active at time
tif and only ifstart ≤ t < end. - Two intervals
[a, b)and[c, d)overlap at timetonly if both containtunder the rule above. - Specifically, if one interval ends at time
t(meaningend = t) and another starts at timet(meaningstart = t), they do not overlap because the first is not active attwhile the second is active starting att.
Task
Write a function that accepts a list of intervals and returns a two-element list [max_count, time]:
max_count: the maximum number of intervals that overlap at any single moment.time: any integer timestamp at which exactlymax_countintervals are active.
If the input list is empty, return [0, 0].
Input
intervals: a list of[start, end)pairs where each pair satisfiesstart < end.
Output
- A list
[max_count, time]as described above. - If multiple times achieve the maximum, you may return any one of them.
Constraints
0 ≤ len(intervals) ≤ 100,000- For each interval,
0 ≤ start < end ≤ 1,000,000,000 - Target time complexity:
O(n log n)
Examples
Example 1
Input: peak_activity_count([[0, 10], [5, 12], [11, 13], [2, 7]])
Output: [3, 5]
Hints
Hint 1
The overlap count only changes when intervals start or end, so focus on those event times.
Hint 2
Transform each interval into two events: a start event and an end event, then process them in time order.
Hint 3
When multiple events happen at the same instant, combine their effects before updating the active count to correctly handle the half-open boundary rule.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The number of overlapping intervals is piecewise constant over time, changing only when intervals begin or terminate. We use a sweep-line strategy to efficiently track these transitions.
Algorithm steps:
-
Generate events: Transform each interval
[start, end)into two events:(start, +1)marking when an interval becomes active(end, -1)marking when an interval becomes inactive
-
Sort events by their timestamp in ascending order.
-
Sweep through time: Process events left to right, maintaining a counter of currently active intervals:
- At each distinct timestamp, group all events occurring at that moment
- Apply their combined effect (sum all deltas) to the active counter
- Track the maximum value observed and the timestamp where it first occurs
-
Respect half-open semantics: Grouping events at identical timestamps ensures that when one interval ends at time
tand another starts att, their net contribution is zero at that instant, correctly reflecting that they do not overlap.
Correctness
Between any two consecutive event times, no interval starts or stops, so the overlap count stays fixed. By examining the active count immediately after processing each distinct timestamp, we visit every constant segment exactly once. The largest active count encountered is the global maximum, and its associated timestamp is valid because the count applies to the half-open range starting at that time.
The grouping mechanism is essential: it prevents the brief illusion of overlap when an interval's end coincides with another's start, which would violate the definition of half-open intervals.
Complexity Analysis
- Time complexity:
O(n log n)due to sorting2nevents; the sweep itself runs inO(n). - Space complexity:
O(n)for the event list.
Full Solution
from typing import List
def peak_activity_count(intervals: List[List[int]]) -> List[int]:
if not intervals:
return [0, 0]
events = []
for start, end in intervals:
events.append((start, 1))
events.append((end, -1))
events.sort()
active = 0
best_count = 0
best_time = 0
i = 0
while i < len(events):
time = events[i][0]
delta = 0
while i < len(events) and events[i][0] == time:
delta += events[i][1]
i += 1
active += delta
if active > best_count:
best_count = active
best_time = time
return [best_count, best_time]