The key to solving this problem is to first sort the intervals based on the starting time. Once sorted, we can iterate over the intervals and merge them if they overlap. Two intervals overlap if the start of the current interval is less than or equal to the end of the previous interval.
Time Complexity: O(n log n), due to sorting.
Space Complexity: O(n), required for the output array.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int[][] Merge(int[][] intervals) {
6 Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
7 List<int[]> merged = new List<int[]>();
8 foreach (var interval in intervals) {
9 if (merged.Count == 0 || merged[^1][1] < interval[0]) {
10 merged.Add(interval);
11 }
12 else {
13 merged[^1][1] = Math.Max(merged[^1][1], interval[1]);
14 }
15 }
16 return merged.ToArray();
17 }
18}
The Array.Sort
method in C# allows us to sort intervals efficiently. Overlapping intervals are merged using a list that dynamically adjusts as needed.
Another approach involves consecutive comparisons and inserting intervals into a new list if they do not overlap with the current interval being processed.
Time Complexity: O(n log n).
Space Complexity: O(n).
1def merge(intervals):
2 intervals.sort(key=lambda x: x[0])
3 merged = []
4 for interval in intervals:
5 if not merged or merged[-1][1] < interval[0]:
6 merged.append(interval)
7 else:
8 merged[-1][1] = max(merged[-1][1], interval[1])
9 return merged
In Python, the proposal is about sorting the intervals, looping through them, and confirming whether current intervals are merged thoroughly based on the ending values.