Merge Overlapping Intervals

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.

For example –

Example 1-

Input: [[1,4], [2,5], [6,9]] Output: [[1,5], [6,9]]

Example 2-

Input: [[7,8], [2,3], [5,9]] Output: [[2,3], [5,9]]

Example 3-

Input: [[1,4], [2,6], [3,5]] Output: [[1,6]]

Merge overlapping intervals

We have discussed the problem statement. Now, let’s think how we can solve this problem. What’s the time and space complexity of our solution?

Programming video tutorials

Find Top k most frequent elements

Merge Overlapping Intervals – Java Code

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).

Merge Overlapping Intervals InterviewBit Solution – Java Code

I have already explained the logic to solve this problem. Let’s write its code.

Video Tutorial

In this video tutorial, I have explained an approach to merge intervals.

Merge Overlapping intervals Video Tutorial

Merge Overlapping Intervals Video Tutorial

Tagged . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.