using System; using System.Collections.Generic; class Program { public static List<int[]> MergeIntervals(List<int[]> intervals) { intervals.Sort((a, b) => a[0].CompareTo(b[0])); List<int[]> merged = new List<int[]>(); foreach (var interval in intervals) { if (merged.Count == 0 || merged[merged.Count - 1][1] < interval[0]) { merged.Add(interval); } else { merged[merged.Count - 1][1] = Math.Max(merged[merged.Count - 1][1], interval[1]); } } return merged; } static void Main() { var intervals = new List<int[]> { new int[] {1, 3}, new int[] {2, 6}, new int[] {8, 10}, new int[] {15, 18} }; var result = MergeIntervals(intervals); foreach (var interval in result) { Console.Write($"{interval[0]}->{interval[1]} "); } } }
The code sorts intervals by start time, then merges overlapping ones by extending the end of the last merged interval.
Intervals [1,3] and [2,6] overlap, so they merge into [1,6]. Others remain separate.
Intervals represent ranges of values or time. Many problems involve overlapping intervals that need merging or scheduling, such as calendar events or resource usage.
The condition a[1] >= b[0] && a[0] <= b[1] returns true if intervals overlap or touch at the boundary.
Here, a ends at 5 and b starts at 5, so 5 >= 5 is true, so overlap is true. But the code mistakenly uses >= which includes touching as overlap.
Intervals [1,4], [2,5], and [3,6] overlap between 3 and 4, so maximum overlap is 3.
The new interval [4,8] overlaps with [3,5], [6,7], and [8,10]. They merge into [3,10].
Intervals [1,2] and [12,16] remain separate.
