C# / .NET
Mid-level (2–5 yrs)
Coding
Very frequent
C#
intervals
sorting
LeetCode
arrays
Merge overlapping intervals from a list of [start, end] pairs
cs-mid-006
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Log in to save progress.
Model answer
Sort the intervals by start time. Iterate and compare each interval to the last element in the result list. If the current start is less than or equal to the last result's end, they overlap — extend the end if needed. Otherwise append the current interval as a new entry. This is O(n log n) for the sort and O(n) for the merge pass.
Code example
public int[][] Merge(int[][] intervals)
{
if (intervals.Length <= 1) return intervals;
// Sort by start
Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
var result = new List<int[]> { intervals[0] };
for (int i = 1; i < intervals.Length; i++)
{
var last = result[^1];
if (intervals[i][0] <= last[1]) // overlapping
last[1] = Math.Max(last[1], intervals[i][1]);
else
result.Add(intervals[i]);
}
return result.ToArray();
}
// Test
var merged = Merge(new[] { new[]{1,3}, new[]{2,6}, new[]{8,10}, new[]{15,18} });
// [[1,6],[8,10],[15,18]]
Follow-up
How would you handle this if intervals arrive in a stream and you need to maintain a sorted set?