In this post, we are going to solve a problem merge overlapping intervals.
Given a list of time intervals. Each interval has a start and end time. Write a code to merge all overlapping intervals. The given intervals may or may not be sorted.
In this problem, Given a collection of intervals, we have to merge all overlapping intervals.
Let’s first understand the algorithm to solve the merge intervals problem and then we will write its java code.
1) Sort all intervals in increasing order of start time.
2) Once all the intervals are sorted. The next step is to traverse the sorted intervals starting from the first interval and do the following steps for every interval.
a) If the current interval is not the first interval and it overlaps with the previous interval (i.e. b.start <= a.end). In that case, merge the current interval with the previous interval. Keep doing it while the interval overlaps with the previous one.
b) Else add the current interval to the output list of intervals.
3) When all the intervals are traversed, return the output list.
The time complexity of this approach is O(nlogn). The space complexity of this approach is O(1).