KatInterview

Peak Activity Count from Time Intervals

Greedy & IntervalsAuto-graded · 20 test cases
MediumAuto-gradedGreedy & Intervalsintervalssweep-linesorting

Last 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 second start but excludes the ending second end.
  • An activity is considered active at time t if and only if start ≤ t < end.
  • Two intervals [a, b) and [c, d) overlap at time t only if both contain t under the rule above.
  • Specifically, if one interval ends at time t (meaning end = t) and another starts at time t (meaning start = t), they do not overlap because the first is not active at t while the second is active starting at t.

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 exactly max_count intervals are active.

If the input list is empty, return [0, 0].

Input

  • intervals: a list of [start, end) pairs where each pair satisfies start < 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.