Date: 08-03-24
Understanding the Problem
- In this problem the input is a non-empty array of arbitrary intervals. Our solution is required to merge any overlapping intervals, for instance, if theres an interval
[3, 5], [4, 7]
, we know that 4 overlaps in both intervals therefore our solution should merge these into[3,7]
. Finally, we return the new intervals (2d array) once we’re doing merging all overlapping intervals (the order of these intervals is not important).
Example
Approach 1
- In this solution the way we can check for overlapping intervals is to check the end value of interval compare to the start value of the second interval. If the end of the first interval is greater than or equal to start of the second interval then we know we have overlapping intervals and need to merge them. This works when interval one is sorted relative to interval two, however, if we do the same comparison and they’re switched we end up triggering a false overlap. This is because, for instance
1: [3, 4] 2: [1, 2]
, if we compare the end to the start, we see that4 >= 1
but these two intervals are not overlapping - To solve for this comparison issues, we need to first sort the intervals based on the starting value.
Algorithm
- Define an output array to store the new merged intervals
- Sort the input array based on the first element of the intervals
- Begin iterating over the input array comparing the first element of the current interval with the previous interval and its second element. In the instance of the first element in the input array there’s nothing to compare it, therefore we just place it in the output array
- We keep iterating until we’ve reached a comparison that overlaps
- If we find a merging interval we just need to modify the last interval in the output array and its ending element. To find which value belongs in the ending element of that interval we simply find the
max
of the ending of both overlapping intervals.
Implementation
Complexity Analysis
- Time Complexity:
- Space Complexity: