Statement
Solution
Naive approach
The naive approach to merging intervals involves comparing each interval with all the intervals that come after it. If two intervals overlap, they are merged into a single interval by updating the start to the minimum of both start times and the end to the maximum of both end times. After merging, the second interval (the one being compared) is removed from the list, as its range is now included in the updated interval. The algorithm then checks for further overlaps with the updated interval from the same position. This process repeats until all overlapping intervals have been merged, resulting in a final list of non-overlapping intervals.
This process continues until all overlapping intervals are merged. While this method is easy to understand and doesn’t require extra space, it can be inefficient for large inputs because it compares each interval with many others, leading to a time complexity of
Optimized approach using the merge intervals pattern
The optimized approach starts by sorting the intervals in ascending order based on their start times. This step ensures overlapping intervals are positioned next to each other, making identifying and merging them easier. Once sorted, the algorithm initializes a result list with the first interval. It then iterates through the remaining intervals one by one, comparing each to the last interval in the result list.
If the current interval overlaps with the last one in the result (i.e., its start time is less than or equal to the end time of the last interval), the two intervals are merged by updating the end time to the maximum of both intervals’ end times. If there is no overlap, the current interval is added to the result list as a new entry. This process continues until all intervals have been processed. In the end, the result list contains the merged, non-overlapping intervals.