150NeetCode 150

130.Insert Interval

MediumBlind 75Intervals ยท 1/6

Problem

You are given an array of non-overlapping intervals intervals, sorted in ascending order by start, where intervals[i] = [start_i, end_i], and a new interval newInterval = [start, end].

Insert newInterval so that the result is still sorted by start and still non-overlapping, merging any intervals that overlap with it. Return the resulting array. Intervals that touch ([1,2] and [2,3]) count as overlapping.

Examples

Input:  intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Explanation: [2,5] overlaps [1,3] -> merged into [1,5].
Input:  intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: [4,8] overlaps [3,5], [6,7] and [8,10].
Input:  intervals = [], newInterval = [5,7]
Output: [[5,7]]

Constraints

  • 0 <= intervals.length <= 10^4
  • intervals[i].length == 2, 0 <= start_i <= end_i <= 10^5
  • intervals is sorted by start_i and contains no overlaps.
  • newInterval.length == 2, 0 <= start <= end <= 10^5

๐Ÿ’ก Key Insight

Because the input is already sorted and disjoint, every existing interval falls into exactly one of three groups relative to newInterval: entirely before it (end < newStart), overlapping it, or entirely after it (start > newEnd). These groups are contiguous, so one left-to-right pass copies the first group, folds the middle group into newInterval with min/max, and copies the rest.

Brute Force (Append, Sort, Merge)

TimeO(n log n)SpaceO(n)

Intuition

Ignore the fact that the input is sorted: add newInterval to the list, sort everything by start, and run the standard "merge intervals" sweep.

Algorithm

  1. Copy intervals into a list and add newInterval.
  2. Sort by start.
  3. Sweep: if the current interval starts after the last merged end, append it; otherwise extend the last merged end with max.

Visualization

[[1,3],[6,9]] + [2,5] -> sort -> [[1,3],[2,5],[6,9]]
merge: [1,3] ; [2,5] overlaps (2 <= 3) -> [1,5] ; [6,9] starts after 5 -> append
result [[1,5],[6,9]]

Code

java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> all = new ArrayList<>(Arrays.asList(intervals));
        all.add(newInterval);
        all.sort((a, b) -> Integer.compare(a[0], b[0]));
        List<int[]> merged = new ArrayList<>();
        for (int[] cur : all) {
            if (merged.isEmpty() || merged.get(merged.size() - 1)[1] < cur[0]) {
                merged.add(new int[] {cur[0], cur[1]}); // gap: new block
            } else {
                int[] last = merged.get(merged.size() - 1);
                last[1] = Math.max(last[1], cur[1]); // overlap: extend
            }
        }
        return merged.toArray(new int[0][]);
    }
}

Complexity

  • Time: O(n log n) โ€” the sort dominates.
  • Space: O(n) โ€” the copied and merged lists.

Complexity Comparison

Approach Time Space
Append, Sort, Merge O(n log n) O(n)
Binary Search + Merge O(n) O(n)
Single Linear Pass O(n) O(n)

Common Pitfalls

  • Using <= in the "before" check (intervals[i][1] <= start) โ€” touching intervals like [1,2] and [2,5] must merge.
  • Comparing overlapping intervals against the original newInterval end instead of the growing end.
  • Forgetting to add the merged interval when it lies after all existing intervals (or when intervals is empty).
  • Mutating input arrays while also returning them in the result โ€” create a new array for the merged interval.