Merge Intervals
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. **Examples:** ```typescript merge([[1,3],[2,6],[8,10],[15,18]]) // [[1,6],[8,10],[15,18]] merge([[1,4],[4,5]]) // [[1,5]] ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(n log n)
- Space complexity: O(n)
Sorting intervals by start time takes O(n log n). Linear scan takes O(n).
Follow-Up Questions Interviewers Ask About Merge Intervals
- Why sort by start time rather than end time?
Sorting by start time ensures that any interval that could possibly merge with the current interval appears immediately next.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.