Problem overview
Merge receives intervals as an int[,], one interval per row: the start in column 0 and the end in column 1. It returns the intervals that remain after merging all overlapping ones, as an int[][] sorted by start.
Two intervals overlap when they share at least one point, so intervals that only touch, such as [1,4] and [4,5], merge into [1,5].
For {{1,3},{2,6},{8,10},{15,18}} the result is {{1,6},{8,10},{15,18}}: the first two overlap and merge. For {{6,8},{1,9},{2,4},{4,7}} the input is unsorted, and [1,9] covers all the others, so the result is {{1,9}}.
Approach: sort first
If the intervals are in no particular order, any interval might overlap any other, and checking all pairs is O(n²). After sorting by start, the intervals that overlap come one after another. Walk through them in order and keep a list of merged intervals. For each interval, only the last merged interval matters:
- If the last merged interval ends before this one starts, there is a gap. Nothing so far can overlap this interval, so it starts a new merged interval.
- Otherwise it overlaps the last merged interval, which is extended to cover both: its end becomes the larger of the two ends.
The larger end matters because an interval can lie completely inside the last merged one, like [2,3] inside [1,10], and then the end has to stay at 10.
An int[,] is one block of memory, so its rows can't be sorted directly. The lesson sorts an array of row numbers and reads the rows through it.
This is the standard way to turn a quadratic problem into a sort plus a scan: once the data is in order, a single running answer is enough, and the answer only ever needs to look back at one element.
Step by step
- Store the row count
intervals.GetLength(0)inrows. - Create
order, anint[]of sizerows, to hold row numbers. - Fill it with
0, 1, ..., rows - 1using a one-lineforloop. - Sort
orderwithArray.Sortand the comparisonintervals[first, 0] - intervals[second, 0], so rows with a smaller start come first. For the rows{{6,8},{1,9},{2,4},{4,7}}the sortedorderis1, 2, 3, 0. - Create
merged, aList<int[]>. Its final size isn't known, so it must be able to grow. - Loop over
orderwithforeach. The loop variablerowis a row number ofintervals, not a position inorder. - Name the two ends:
startisintervals[row, 0]andendisintervals[row, 1]. - Start a new merged interval when
mergedis empty or the last merged end is less thanstart. Use<, not<=, so touching intervals merge. Addnew int[]{start, end}. - Otherwise extend the last one: set its end to
Math.Maxof its own end andend. - Return
merged.ToArray(), which turns the list into anint[][].
Tracing the first example
For {{1,3},{2,6},{8,10},{15,18}} the intervals are already sorted. The list merged after each interval looks like this:
[1,3] -> [1,3]
[2,6] -> [1,6]
[8,10] -> [1,6] [8,10]
[15,18] -> [1,6] [8,10] [15,18]
The interval [2,6] starts at 2, before the last merged end 3, so the last merged interval grows to end at 6. The interval [8,10] starts after 6, so it opens a new one. For the unsorted example {{6,8},{1,9},{2,4},{4,7}}, the sorted order visits [1,9], [2,4], [4,7] and [6,8]. The first becomes the merged interval, and each later one starts before 9 and ends before 9, so Math.Max keeps the end at 9. The result is a single [1,9].
The solution in C#
class Solution {
public int[][] Merge(int[,] intervals) {
int rows = intervals.GetLength(0);
int[] order = new int[rows];
for (int i = 0; i < rows; i++) order[i] = i;
Array.Sort(order, (first, second) => intervals[first, 0] - intervals[second, 0]);
List<int[]> merged = new List<int[]>();
foreach (int row in order) {
int start = intervals[row, 0], end = intervals[row, 1];
if (merged.Count == 0 || merged[merged.Count - 1][1] < start) {
merged.Add(new int[]{start, end});
} else {
merged[merged.Count - 1][1] = Math.Max(merged[merged.Count - 1][1], end);
}
}
return merged.ToArray();
}
}
Details worth knowing:
- Two array shapes. The input is a rectangular
int[,], read asintervals[row, 0]. The output is a jaggedint[][], an array of separate small arrays, read asresult[k][0]. The method has to copy each interval into a newint[]because a row of anint[,]is not an array of its own. - Changing an element in place.
merged[merged.Count - 1]gives the array stored in the list, not a copy of it. Assigning to its index[1]changes that array, which is how the end gets extended. - Two variables in one declaration.
int start = ..., end = ...;declares both asint. - Subtraction in the comparison is safe for the constraint range, 0 to 1,000,000. Values near the limits of
intwould make the difference wrap, andCompareToavoids that. - Usings.
List<T>lives inSystem.Collections.Generic, andArrayandMathinSystem.
Complexity
Time: O(n log n). The sort costs O(n log n) and the merging pass O(n).
Space: O(n) for order and merged.
Edge cases and common mistakes
- Touching intervals.
{{1,4},{4,5}}returns{{1,5}}. A<=in the gap test would split them. - Nested intervals.
{{1,10},{2,3}}returns{{1,10}}. Assigning the new end withoutMath.Maxwould shrink the interval to[1,3]. - One interval.
{{5,6}}returns{{5,6}}. - No overlaps.
{{1,2},{3,4}}comes back unchanged. - Single points.
{{2,2},{2,2}}returns{{2,2}}: an interval can have equal start and end. - Skipping the sort. Without it,
{{6,8},{1,9},{2,4},{4,7}}produces wrong intervals.
Testing
{{1,3},{2,6},{8,10},{15,18}}gives{{1,6},{8,10},{15,18}}.{{1,4},{4,5}}gives{{1,5}}.{{6,8},{1,9},{2,4},{4,7}}gives{{1,9}}.{{1,10},{2,3}}gives{{1,10}}.{{1,2},{3,4}}gives{{1,2},{3,4}}.{{2,2},{2,2}}gives{{2,2}}.
