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.
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.
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.
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.
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.
The basic idea:
startIntervals - endIntervals
and whenever this number is 0, there should be no interval in that range.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With