Start learning free

LESSON 268 OF 314 · INTERVALS

Merge Intervals in C#: Sort by Start, then One Pass, O(n log n)

Practice O(n log n) Read the full explanation

You get an array of intervals. Each interval is a pair [starti, endi]. It covers every point from its start to its end.

Merge the intervals that overlap. Return an array of the intervals you end up with, sorted by start.

Two intervals overlap if they share at least one point. Intervals that only touch count too. For example, [2,5] and [5,6] share the point 5. They become [2,6].

 

Example 1:

Input: intervals = [[5,8],[1,3],[7,11],[13,14]]
Output: [[1,3],[5,11],[13,14]]
Explanation: The input is not sorted.
[5,8] and [7,11] share 7 and 8.
They become [5,11].
[1,3] and [13,14] overlap no other interval.

Example 2:

Input: intervals = [[2,5],[5,6],[9,9]]
Output: [[2,6],[9,9]]
Explanation: [2,5] and [5,6] touch at 5.
That is enough to merge them.
[9,9] is a single point.
It stays on its own.

Example 3:

Input: intervals = [[3,20],[4,6],[10,12]]
Output: [[3,20]]
Explanation: [4,6] and [10,12] lie inside [3,20].
All three merge into [3,20].
It ends at 20, not at 12.

 

Constraints:

  • 1 to 100,000 intervals, in any order.
  • Each start and end is a whole number from 0 to 1,000,000.
  • No start is greater than its end.

Note:

Your algorithm should run in O(n log n) time, where n is the number of intervals.

STEP 1 OF 10
    Ctrl + Enter to check

    C# · INTERVALS

    Merge Intervals in C#, explained

    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

    1. Store the row count intervals.GetLength(0) in rows.
    2. Create order, an int[] of size rows, to hold row numbers.
    3. Fill it with 0, 1, ..., rows - 1 using a one-line for loop.
    4. Sort order with Array.Sort and the comparison intervals[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 sorted order is 1, 2, 3, 0.
    5. Create merged, a List<int[]>. Its final size isn't known, so it must be able to grow.
    6. Loop over order with foreach. The loop variable row is a row number of intervals, not a position in order.
    7. Name the two ends: start is intervals[row, 0] and end is intervals[row, 1].
    8. Start a new merged interval when merged is empty or the last merged end is less than start. Use <, not <=, so touching intervals merge. Add new int[]{start, end}.
    9. Otherwise extend the last one: set its end to Math.Max of its own end and end.
    10. Return merged.ToArray(), which turns the list into an int[][].

    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 as intervals[row, 0]. The output is a jagged int[][], an array of separate small arrays, read as result[k][0]. The method has to copy each interval into a new int[] because a row of an int[,] 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 as int.
    • Subtraction in the comparison is safe for the constraint range, 0 to 1,000,000. Values near the limits of int would make the difference wrap, and CompareTo avoids that.
    • Usings. List<T> lives in System.Collections.Generic, and Array and Math in System.

    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 without Math.Max would 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}}.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free