Sort by start time first, that's the key move.
Sort the intervals by their start times, then iterate through them while maintaining a 'current' merged interval, extending it whenever the next interval overlaps. This greedy approach ensures a single linear pass after sorting, yielding an O(n log n) overall solution dominated by the sort step.
Pro tip: Proactively mention edge cases like an empty input array, a single interval, or intervals that are only touching (e.g., [1,2] and [2,3]) and clarify with your interviewer whether touching intervals should be merged — this signals production-level thinking that Meta values.
Confirm input format (e.g., list of [start, end] pairs), whether intervals can be unsorted, and edge cases like empty arrays or touching intervals. Ask if in-place modification is preferred or a new list is acceptable.
Sort the array of intervals based on the start value of each interval. This guarantees that any overlapping interval with the current one can only appear immediately after it in the sorted order.
Initialize a result list with the first interval, then for each subsequent interval check if its start is less than or equal to the current interval's end. If so, extend the end to the maximum of both ends; otherwise, push the current interval to results and start a new one.
After the loop, ensure the last active interval is appended to the result list, as it won't be pushed inside the loop iteration.
State the time complexity as O(n log n) due to sorting and O(n) space for the output. Walk through 2-3 test cases including normal overlap, no overlap, and fully contained intervals to validate correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.