MEDIUM NC#131 Blind #36 Intervals
56. Merge Intervals
๐ Problem
Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Sort intervals by start time
- โ If current interval overlaps with last merged, merge them
- โ Otherwise, add current interval to result
- โ Time: O(n log n), Space: O(n) for result
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขSort intervals by start time
- โขIf current interval overlaps with last merged, merge them
- โขOtherwise, add current interval to result
Common Pitfalls
- โขTime: O(n log n), Space: O(n) for result
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
merge([[1,3],[2,6],[8,10],[15,18]]); Expected:
[[1,6], [8,10], [15,18]] Test Case 2
Not run Input:
merge([[1,4],[4,5]]); Expected:
[[1,5]] Test Case 3
Not run Input:
merge([[1,4],[0,4]]); Expected:
[[0,4]] ๐ Code Editor
๐ค Output