Skip to content
Advertisement

Finding overlapped intervals in a set of intervals

We have a login system that tracks how long people are connected. I would like to write a code to find people who were online at the same time. Look at this example, please:

JavaScript

Think of these as intervals of Person 1 to 4. I want the output of the algorithm to be something like this:

JavaScript

I tried to solve the problem with two for loops so that we get a list of people whose intervals overlap, but the problem is dealing with intervals for more than one person. for example, in the above example, [3,4] not have to come in [4, 5] in line three because it calculated as a three-person interval.

Advertisement

Answer

Heavily inspired by Minimum number of platforms required for a railway station, but maintaining a set of persons present instead of a count of trains present:

Also an implementation of the algorithm hinted at in Yves Daoust’s answer.

The idea is to first build a chronological list of all events, where an event is either the arrival or departure of a person.

Then we iterate on the list of events, maintaining a set of persons present, adding the persons who arrive and removing the persons who leave.

Below, the chronological list of events is implemented as a python dict mapping times to python lists of events, so that events happening at the same time, if any, are naturally grouped together.

JavaScript

This algorithm has time complexity O(N), where N is the number of persons. For comparison, the algorithm in Dani Mesejo’s answer has time complexity O(TN), where N is the number of persons and T the maximum time that any person is present, measured in number of instants.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement