
Problem
Solution
Submissions
Merge Intervals
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C program to merge all overlapping intervals. 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]]
- Output: [[1,6],[8,10],[15,18]]
- Explanation:
- Step 1: Sort the intervals based on the start time: [[1,3],[2,6],[8,10],[15,18]] (already sorted).
- Step 2: Initialize the result with the first interval: [[1,3]].
- Step 3: Consider interval [2,6]. Since 2 <= 3 (end of previous interval), these intervals overlap.
- Step 4: Merge [1,3] and [2,6] into [1,6]. Result: [[1,6]].
- Step 5: Consider interval [8,10]. Since 8 > 6 (end of previous merged interval), these intervals don't overlap.
- Step 6: Add [8,10] to the result. Result: [[1,6],[8,10]].
- Step 7: Consider interval [15,18]. Since 15 > 10 (end of previous interval), these intervals don't overlap.
- Step 8: Add [15,18] to the result. Final result: [[1,6],[8,10],[15,18]].
Example 2
- Input: intervals = [[1,4],[4,5]]
- Output: [[1,5]]
- Explanation:
- Step 1: Sort the intervals based on the start time: [[1,4],[4,5]] (already sorted).
- Step 2: Initialize the result with the first interval: [[1,4]].
- Step 3: Consider interval [4,5]. Since 4 <= 4 (end of previous interval), these intervals are touching and can be merged.
- Step 4: Merge [1,4] and [4,5] into [1,5]. Final result: [[1,5]].
Constraints
- 1 <= intervals.length <= 10^4
- intervals[i].length == 2
- 0 <= start_i <= end_i <= 10^4
- Time Complexity: O(n log n), where n is the number of intervals (due to sorting)
- Space Complexity: O(n), for storing the result
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 based on the start time.
- Initialize a result array with the first interval.
- For each interval, check if it overlaps with the last interval in the result array.
- If it overlaps, merge them by updating the end time of the last interval in the result.
- If it doesn't overlap, add it to the result array.