KatInterview

Peak Overlap of Half-Open Time Ranges

Greedy & IntervalsAuto-graded · 21 test cases
MediumAuto-gradedGreedy & Intervalssweep-lineintervalssorting

Last updated

Compute the largest number of simultaneously running half-open time ranges using a sweep over sorted start and end events, with correct handling of ties at boundaries.

Peak Concurrent Ranges

You are given a collection of time ranges. Each range is a pair [begin, finish] and covers every moment t with begin <= t < finish. In other words, the range includes its begin moment but does not include its finish moment.

Determine the greatest number of ranges that cover one single moment in time.

Because finish is excluded, a range that finishes at time t does not overlap with a range that begins at time t.

Input

  • loans: a list of [begin, finish] pairs of integers, with begin < finish.

Output

Return one integer: the maximum number of ranges that are simultaneously active at any moment.

Constraints

  • 1 <= len(loans) <= 10^5
  • 0 <= begin < finish <= 10^9
  • Several ranges may share the same begin time, the same finish time, or both.
  • A single range is a valid input and gives an answer of 1.
  • Time values are too large to allocate an array indexed by time.

Examples

Example 1

Input: max_active_loans([[1, 5], [2, 6], [5, 8]])

Output: 2

Example 2

Input: max_active_loans([[1, 10], [2, 3], [4, 5]])

Output: 2

Hints

Hint 1

The number of active ranges can only change at a begin time or a finish time, so you only need to examine those moments.

Hint 2

Break each range into two events: one that adds 1 at its begin time and one that subtracts 1 at its finish time, then process the events in time order.

Hint 3

When a begin and a finish share the same time, handle the finish first, because the finishing range is no longer active at that moment. Sorting (time, delta) tuples with delta -1 for finishes does this automatically.