DSA Factory
Free Intervals lessonsIntervals · Stage 1 · Sweep line · Step 3

Total time covered

Add up the total time covered by at least one meeting, counting overlapping stretches only once, by sweeping through the start and end events. About 18 minutes.

Count each stretch once

Meetings [1, 4] and [2, 6] overlap. Adding their lengths, 3 and 4, gives 7, but the time from 1 to 6 is only 5 units. The shared stretch from 2 to 4 was counted twice.

Instead of lengths, look at time itself. Between two neighbouring events, the number of running meetings does not change. So each gap is either covered, if the count is above zero, or free.

Adding lengths: counts overlaps twice.
Gaps between events: have one fixed count.

Sweep and add the covered gaps

Build the events, a plus one at each start and a minus one at each end, and sort them. Walk through, remembering the previous event time and the running count.

At each event, if the count before it was above zero, the gap since the previous event is covered, so add its length. Then apply the change and move on. Each stretch of time is added at most once.

Count above zero? add the gap length.
Then update: the count and the previous time.
In code
if cur > 0:
    total += t - prev   # something ran
prev = t
Meetings [1, 3], [2, 5], [8, 9]. Covered time: 1 to 5, and 8 to 9.
123456789[1, 3][2, 5][8, 9]

Time 1: the first meeting starts. Nothing was covered before, so the total is 0.

Move 1 of 5
Quick check

Meetings [0, 10] and [5, 8]. How much time is covered?

  1. A10
  2. B13
  3. C15
Show the answer

10. The second meeting lies inside the first, so only 0 to 10 is covered.

Your problem

Total covered time

You are given meetings, each as [start, end), occupying from start up to but not including end. Return the total length of time during which at least one meeting is running. Overlapping stretches count only once.

Example
meetings = [[1, 4], [2, 6], [8, 9]] → 6

0 ≤ meetings.length ≤ 100,000 · 0 ≤ start < end ≤ 1,000,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve