Start learning free

LESSON 551 OF 671 · INTERVALS

Insert Interval in Java: O(n) Single Pass

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

    JAVA · INTERVALS

    Insert Interval in Java, explained

    Problem overview

    The method insert receives an int[][] named intervals, sorted by start with no two intervals overlapping, and an int[] named newInterval. It inserts the new interval, merges it with every interval it overlaps, and returns the result as an int[][], still sorted and with no overlaps. Intervals that only touch, like [1,4] and [4,5], share the point 4, so they merge into [1,5].

    For intervals = [[1,3],[6,9]] and newInterval = [2,5] the result is [[1, 5], [6, 9]]. For [[1,2],[3,5],[6,7],[8,10],[12,16]] and [4,8] the result is [[1, 2], [3, 10], [12, 16]]: the new interval overlaps [3,5] and [6,7] and touches [8,10] at 8, so all four become [3,10]. With intervals = [] and [5,7] the result is [[5, 7]]. The statement asks for O(n) time.

    Approach: before, overlapping, after

    The input is already sorted, so there is no need to sort again, which would cost O(n log n). The existing intervals fall into three groups, in this order:

    1. Before. They end before newInterval starts. They go into the answer unchanged.
    2. Overlapping. They start no later than the growing merged interval ends. Each one can only widen the new interval: an earlier start or a later end. All of them collapse into one interval.
    3. After. They start after the merged interval ends. They go into the answer unchanged.

    One index i walks through the array exactly once, and each group's loop picks up where the previous one stopped. The merged interval is added between groups one and three, so the result stays sorted by start.

    Take the second example, [4,8] against [[1,2],[3,5],[6,7],[8,10],[12,16]]. [1,2] ends at 2, before 4, so it is copied. [3,5] starts at 3, which is no later than 8, so the loop merges it: the start stays 3 (the smaller of 4 and 3) and the end stays 8 (the larger of 8 and 5). [6,7] and [8,10] start at 6 and 8, both no later than 8, so they merge too, and the end becomes 10. [12,16] starts at 12, after 10, so it is copied. The result is [[1, 2], [3, 10], [12, 16]], as listed above.

    Step by step

    1. Create result, a List<int[]> backed by a new ArrayList, since its final size isn't known.
    2. Store n, the number of intervals, and declare the index i starting at 0. All three parts share it.
    3. Part one, the loop. Run while i < n and intervals[i][1] < newInterval[0]. Use <: an interval ending exactly at newInterval[0] touches the new one, and touching intervals merge. Test i < n first, so && stops before reading past the end of the array.
    4. Copy and advance. Add intervals[i] to result and do i++.
    5. Part two, the variables. Declare start = newInterval[0] and end = newInterval[1]. They hold the growing merged interval.
    6. The overlap loop. Run while i < n and intervals[i][0] <= end. Every interval left ends at or after newInterval[0], so it overlaps exactly when it starts by end. The sort order means that once one fails the test, all the rest do too.
    7. Widen the start with Math.min(start, intervals[i][0]).
    8. Widen the end with Math.max(end, intervals[i][1]). Keeping the larger end matters when an interval lies completely inside, like [4,5] inside [3,9].
    9. Advance with i++, or the loop would look at the same interval forever.
    10. Add the merged interval as new int[]{start, end}. If nothing overlapped, it is newInterval unchanged.
    11. Part three, the loop. Run while i < n.
    12. Copy the rest with result.add(intervals[i]) and i++.
    13. Return result.toArray(new int[0][]), which copies the list into an array of arrays of the right size.

    The solution in Java

    class Solution {
        public int[][] insert(int[][] intervals, int[] newInterval) {
            List<int[]> result = new ArrayList<>();
            int n = intervals.length;
            int i = 0;
            while (i < n && intervals[i][1] < newInterval[0]) {
                result.add(intervals[i]);
                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(intervals[i]);
                i++;
            }
            return result.toArray(new int[0][]);
        }
    }
    

    Java details worth noticing:

    • Imports. List and ArrayList live in java.util. Outside the lesson's editor the file needs import java.util.*;.
    • Multiple declarations on one line. int start = newInterval[0], end = newInterval[1]; declares two int variables, each with its own initializer.
    • Short-circuit &&. The right side runs only when the left side is true. That is why i < n must come first. Reversed, the loop would throw ArrayIndexOutOfBoundsException after the last interval.
    • Rows are shared with the input. result.add(intervals[i]) adds the same int[] object, not a copy. That is fine, since nothing here changes it, but a caller who later edits the returned rows would also change the input's rows.
    • toArray(new int[0][]). The empty array gives the element type, int[], and the method returns an int[][] of the right length. A List<int[]> can't use int[][] directly because generics hold objects, and arrays are objects.

    Complexity

    Time: O(n). The index i only moves forward, and the three loops together advance it at most n times. The calls to add are constant time on average.

    Space: O(n) for the result, which holds up to n + 1 intervals. Apart from the output, only a few integers are used.

    Edge cases and common mistakes

    • Empty input. With [] and [5,7], none of the loops runs, and the merged interval is [5,7], giving [[5, 7]].
    • The new interval goes first. [[3,4]] with [1,2] gives [[1, 2], [3, 4]]: part one copies nothing, the new interval is added, and part three copies [3,4].
    • The new interval goes last. [[1,2]] with [5,6] gives [[1, 2], [5, 6]].
    • An interval around the new one. [[3,9]] with [4,5] gives [[3, 9]]. The start and end both keep [3,9]'s values, because of the min and the max.
    • Touching intervals. Using <= in the first loop or < in the second would leave touching intervals apart. The statement says they merge.
    • Setting end instead of taking the max. An interval inside the new one would shrink the end.
    • Forgetting i++. Any of the three loops would run forever.

    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]].
    • [] with [5,7] gives [[5, 7]].
    • [[3,4]] with [1,2] gives [[1, 2], [3, 4]].
    • [[1,2]] with [5,6] gives [[1, 2], [5, 6]].
    • [[3,9]] with [4,5] gives [[3, 9]].
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free