Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersecting overlapping intervals in Java

I have an input set of date ranges that may overlap. Instead of combining these overlapping date ranges, I want to create new date ranges with adjusted dates, e.g.:

|---------------------–|
        |-----| 
            |--------------–|

should end up in:

|-------|---|-|--------|----|

Is there an efficient way to solve this with Java?

Thanks in advance!

UPDATE: I didn't mention my own approach in my first question, so here it is: I'd simply take the start and the end date of an interval and add it to a sorted set. Afterwards I'd iterate over the set and create new intervals based on re-ordered dates.

like image 322
u6f6o Avatar asked Jul 09 '13 08:07

u6f6o


People also ask

How do you find overlapping intervals in Java?

Java Program to find overlapping intervals among a given set of intervals. In this approach, we are going to take a count array and for each given interval start time we will do count[startTime]++ and for end time, do count[endTime]--. sum > 2 it means there is overlapping intervals.

How do you combine overlapping intervals?

A simple approach is to start from the first interval and compare it with all other intervals for overlapping, if it overlaps with any other interval, then remove the other interval from the list and merge the other into the first interval. Repeat the same steps for the remaining intervals after the first.

What is an overlapping interval?

Let's take the following overlapping intervals example to explain the idea: If both ranges have at least one common point, then we say that they're overlapping. In other words, we say that two ranges and are overlapping if: On the other hand, non-overlapping ranges don't have any points in common.


2 Answers

You could use Guava's Range support. Haven't used it with Date objects but it could work. Combined with RangeSet you could add all date ranges and then check if a Date is in the ranges, get the complete range, etc.

like image 184
ssindelar Avatar answered Oct 04 '22 06:10

ssindelar


The basic idea:

  • Split up each interval into start and end points
  • Sort the points
  • Iterate through the points and create the new intervals between all neighbouring points.
    Keep track of startIntervals - endIntervals and whenever this number is 0, there should be no interval in that range.
like image 45
Bernhard Barker Avatar answered Oct 04 '22 06:10

Bernhard Barker