Start learning free

LESSON 269 OF 314 · INTERVALS

Insert Interval in C#: One Pass in Three Parts, O(n)

Practice O(n) Read the full explanation

You get an array of intervals. Each interval is a pair [starti, endi]. The list is sorted by start, and no two intervals overlap.

You also get one more interval, newInterval = [start, end].

Add newInterval to the list. Merge it with every interval it overlaps. Return an array of the resulting intervals, still sorted by start and with no overlaps.

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

 

Example 1:

Input: intervals = [[2,4],[7,9],[12,15]], newInterval = [8,13]
Output: [[2,4],[7,15]]
Explanation: [8,13] overlaps [7,9] and [12,15].
The three become [7,15].
[2,4] ends before 8. It stays as it is.

Example 2:

Input: intervals = [[1,2],[6,8]], newInterval = [3,5]
Output: [[1,2],[3,5],[6,8]]
Explanation: [3,5] fits in the gap between [1,2] and [6,8].
Nothing merges.

Example 3:

Input: intervals = [[0,3],[5,6]], newInterval = [3,5]
Output: [[0,6]]
Explanation: [3,5] touches [0,3] at 3.
It also touches [5,6] at 5.
All three join into one.

 

Constraints:

  • 0 to 100,000 intervals in intervals. The list can be empty.
  • Each start and end, in intervals and in newInterval, is from 0 to 1,000,000.
  • No start is greater than its end.
  • intervals is sorted by start.
  • Each interval ends before the next one starts (endi < starti+1). They don't even touch.

Note:

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

STEP 1 OF 13
    Ctrl + Enter to check

    C# · INTERVALS

    Insert Interval in C#, explained

    Problem overview

    Insert receives intervals as an int[,], one interval per row (start in column 0, end in column 1), already sorted by start with no two overlapping. It also receives newInterval, an int[] holding a start and an end. It returns the intervals after inserting the new one, merged with everything it overlaps, as an int[][] that is still sorted and overlap-free.

    Intervals that only touch count as overlapping: [1,4] and [4,5] become [1,5].

    For {{1,3},{6,9}} and [2,5] the result is {{1,5},{6,9}}. For {{1,2},{3,5},{6,7},{8,10},{12,16}} and [4,8] it is {{1,2},{3,10},{12,16}}: the new interval overlaps [3,5] and [6,7] and touches [8,10] at 8. With no intervals at all, inserting [5,7] gives {{5,7}}.

    Approach: three groups, one pointer

    You could append the new interval and run a general merge of overlapping intervals, but that needs a sort and costs O(n log n). The input is already sorted, so one pass is enough. Every existing interval falls into exactly one of three groups, in this order:

    1. Before. Intervals that end before the new one starts. They are copied unchanged.
    2. Overlapping. Intervals that overlap or touch the new one. They are all absorbed into one growing interval, whose start can only get smaller and whose end can only get larger.
    3. After. Intervals that start after the merged interval ends. They are copied unchanged.

    One index i walks through the rows, and each group picks up where the previous one stopped. The merged interval is added between the first and third groups, which keeps the result sorted.

    Step by step

    1. Create result, an empty List<int[]>, because the final size isn't known up front.
    2. Store the row count intervals.GetLength(0) in n, and declare the index i at 0.
    3. Group one: a while loop that runs while i < n and intervals[i, 1] < newInterval[0]. Check i < n first: && stops evaluating when it is false, so row i is never read once the rows run out. Use <, because an interval ending exactly at newInterval[0] touches the new one and must merge.
    4. Copy each such row into result as new int[]{intervals[i, 0], intervals[i, 1]}, then do i++. A row of an int[,] isn't an array of its own, so its two numbers are copied into a new array.
    5. Start the growing interval: start = newInterval[0] and end = newInterval[1].
    6. Group two: a while loop that runs while i < n and intervals[i, 0] <= end. Every remaining interval ends at or after newInterval[0], so it overlaps exactly when it starts by end. Use <=: touching intervals merge. Once one starts after end, the sorted order means all the rest do too.
    7. Widen start to Math.Min(start, intervals[i, 0]).
    8. Widen end to Math.Max(end, intervals[i, 1]). An interval can sit entirely inside the new one, like [4,5] inside [3,9], and then end must stay at 9.
    9. Advance with i++. Without it the loop would look at the same row forever.
    10. Add the merged interval new int[]{start, end} to result. If nothing overlapped, start and end are still the new interval's own values.
    11. Group three: a while loop while i < n that copies each remaining row and does i++.
    12. Return result.ToArray(), which gives an int[][].

    For the second example, the first group copies [1,2], since 2 is less than 4. The second group absorbs [3,5] (start 3, end 5), then [6,7] and [8,10] (end 10), and stops at [12,16] because 12 is more than 10. The merged [3,10] is added, and the third group copies [12,16].

    The solution in C#

    class Solution {
        public int[][] Insert(int[,] intervals, int[] newInterval) {
            List<int[]> result = new List<int[]>();
            int n = intervals.GetLength(0);
            int i = 0;
            while (i < n && intervals[i, 1] < newInterval[0]) {
                result.Add(new int[]{intervals[i, 0], intervals[i, 1]});
                i++;
            }
            int start = newInterval[0], end = newInterval[1];
            while (i < n && intervals[i, 0] <= end) {
                start = Math.Min(start, intervals[i, 0]);
                end = Math.Max(end, intervals[i, 1]);
                i++;
            }
            result.Add(new int[]{start, end});
            while (i < n) {
                result.Add(new int[]{intervals[i, 0], intervals[i, 1]});
                i++;
            }
            return result.ToArray();
        }
    }
    

    Details worth knowing:

    • Short-circuit &&. In i < n && intervals[i, 1] < ... the second test runs only if the first is true. Swapping them would throw an IndexOutOfRangeException when i reaches n.
    • Input and output shapes differ. The input is a rectangular int[,] (intervals[i, 0]) and the output is a jagged int[][] (result[k][0]). The new interval is a plain int[], indexed newInterval[0].
    • Empty input. An int[,] with zero rows has GetLength(0) equal to 0, so the three loops are skipped or end at once and only the new interval is added.
    • List<T> needs System.Collections.Generic, and Math needs System.

    Complexity

    Time: O(n). The index i only moves forward, so each interval is looked at once across the three loops. No sort is needed, because the input is already sorted.

    Space: O(n) for the output list, which holds up to n + 1 intervals. Nothing else grows with the input.

    Edge cases and common mistakes

    • No intervals. Inserting [5,7] gives {{5,7}}.
    • New interval before everything. {{3,5}} with [1,2] gives {{1,2},{3,5}}.
    • New interval after everything. {{3,5}} with [6,8] gives {{3,5},{6,8}}.
    • New interval inside an existing one. {{3,9}} with [4,5] gives {{3,9}}.
    • New interval covering everything. {{1,2},{5,6}} with [0,9] gives {{0,9}}.
    • Touching. {{1,5}} with [5,7] gives {{1,7}}. Using <= in the first loop or < in the second would leave the two intervals separate.
    • Gap between neighbours. {{1,2},{6,7}} with [3,4] gives {{1,2},{3,4},{6,7}}.
    • Forgetting i++. The loop never ends.

    Testing

    • {{1,3},{6,9}} with [2,5] gives {{1,5},{6,9}}.
    • {{1,2},{3,5},{6,7},{8,10},{12,16}} with [4,8] gives {{1,2},{3,10},{12,16}}.
    • No intervals with [5,7] gives {{5,7}}.
    • {{1,2},{3,4}} with [5,6] gives {{1,2},{3,4},{5,6}}.
    • {{1,5}} with [5,7] gives {{1,7}}.
    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