Algorithm-Day14-Merge-Intervals-lc-56
š§© Problem Description
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.
Example:
1 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]] |
š” Brute Force? Not Ideal
You could check every pair and try to merge, but:
- You would need to compare all combinations
- ā Time complexity is too high (O(n²) or worse)
š” Optimal Approach: Sort + Merge
⨠Key Idea
- Sort the intervals by start time
- Iterate through intervals:
- If the current interval overlaps with the previous one, merge them
- Otherwise, add the previous interval to result
This approach ensures that we process all intervals in a linear scan after sorting.
1 | class Solution { |
ā± Time and Space Complexity
- Time Complexity: O(n log n)
For sorting the intervals - Space Complexity: O(n)
For the result list (output), auxiliary space is constant
āļø Summary
- This is a classic sort-then-scan problem
- Make sure to handle edge cases like fully nested intervals (e.g., [1,10], [2,5])
- Very common pattern in scheduling, calendar, and timeline problems
Sorting followed by greedy merging is a powerful approach for interval problems.