KatInterview

Largest Group Anchored by One Overlapping Interval

Greedy & IntervalsAuto-graded · 22 test cases
MediumAuto-gradedGreedy & Intervalsintervalsbinary-searchsorting

Last updated

Find the largest set of intervals that all intersect one chosen anchor interval, using sorting and binary search to beat quadratic time.

A company has n employees. Employee i is available during the inclusive time window [start_time[i], end_time[i]], so the arrays start_time and end_time are aligned by index.

You want to assemble a group that contains an anchor employee. The anchor's window must intersect the window of every other member of the group. Windows [a, b] and [c, d] intersect when they share at least one time point, that is, when max(a, c) <= min(b, d). Touching at a single endpoint counts as intersecting.

Two members who are not the anchor are not required to intersect each other. Only their relationship with the anchor matters.

Return the largest possible size of such a group, with the anchor counted as a member. If there are no employees, return 0.

The solution should run faster than O(n^2).

Constraints

  • 0 <= n <= 10^5, where n = len(start_time) = len(end_time)
  • start_time[i] <= end_time[i] for every i
  • Time values are integers and may be large or negative
  • Windows may be identical or share endpoints

Examples

Example 1

Input: max_anchored_group([2, 5, 6, 8], [5, 6, 10, 9])

Output: 3

Example 2

Input: max_anchored_group([1, 4, 7], [3, 6, 9])

Output: 1

Example 3

Input: max_anchored_group([0, 0, 0], [0, 0, 0])

Output: 3

Hints

Hint 1

For a fixed anchor, nothing limits the other members except that they overlap the anchor, so the best group is every window that overlaps it (the anchor included). Then maximize over anchors.

Hint 2

Counting overlaps directly for each anchor is quadratic. Count the windows that do NOT overlap instead: those that end strictly before the anchor starts, and those that start strictly after the anchor ends.

Hint 3

These two failing sets can never share a window, so you can subtract their sizes from n. Sort the starts and the ends once and use binary search, taking care with strict versus non-strict comparisons at the endpoints.