
Problem
Solution
Submissions
Merge Intervals
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to merge overlapping intervals. Given an array of intervals where each interval is represented as [start, end], merge all overlapping intervals and return an array of non-overlapping intervals that cover all the intervals in the input. Two intervals overlap if they have at least one common point.
Example 1
- Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
- Output: [[1,6],[8,10],[15,18]]
- Explanation:
- Sort intervals by start time: [[1,3],[2,6],[8,10],[15,18]].
- Compare [1,3] and [2,6]: 3 >= 2, so they overlap.
- Merge [1,3] and [2,6] to get [1,6]. Compare [1,6] and [8,10]: 6 < 8, so no overlap.
- Compare [8,10] and [15,18]: 10 < 15, so no overlap.
- Final result: [[1,6],[8,10],[15,18]]
- Sort intervals by start time: [[1,3],[2,6],[8,10],[15,18]].
Example 2
- Input: intervals = [[1,4],[4,5]]
- Output: [[1,5]]
- Explanation:
- Sort intervals by start time: [[1,4],[4,5]].
- Compare [1,4] and [4,5]: 4 >= 4, so they overlap (touching intervals).
- Merge [1,4] and [4,5] to get [1,5]. Final result: [[1,5]]
- Sort intervals by start time: [[1,4],[4,5]].
Constraints
- 1 ≤ intervals.length ≤ 10^4
- intervals[i].length == 2
- 0 ≤ start_i ≤ end_i ≤ 10^4
- Time Complexity: O(n log n) due to sorting
- Space Complexity: O(n) for the result array
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Sort the intervals by their start times to process them in order
- Initialize result array with the first interval
- Iterate through remaining intervals and compare with the last interval in result
- If current interval overlaps with last interval in result, merge them
- If no overlap, add current interval to result
- Two intervals [a,b] and [c,d] overlap if b >= c (assuming a <= c after sorting)