Merging overlapping intervals is a staple interview problem for array manipulation and sorting.
Algorithm
- Sort intervals by start value.
- Initialize
mergedlist with the first interval. - For each subsequent interval
curr:- If
curr.start <= lastMerged.end, overlap exists! UpdatelastMerged.end = max(lastMerged.end, curr.end). - Otherwise, no overlap. Push
currintomerged.
- If
Complexity: Time O(N log N) due to sorting. Space O(N) for output.