Insert Interval

MediumIntervals · Linear Sweep🧩 Intervals & Line SweepLeetCode #57 ↗Updated

Problem

intervals is a list of non-overlapping intervals sorted by start. Add newInterval to it and return a list that is still sorted and non-overlapping, merging newInterval with every interval it overlaps (touching endpoints count as overlap).
Input[[1,3],[6,9]], new=[2,5]Output[[1,5],[6,9]]
Input[[1,2],[3,5],[6,7]], new=[4,6]Output[[1,2],[3,7]]
Input[], new=[5,7]Output[[5,7]]

0 ≤ n ≤ 104  ·  intervals sorted by start, disjoint  ·  0 ≤ start ≤ end ≤ 105

Try it yourself

Java
class Solution {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Because the input is already sorted and disjoint, the intervals split into three contiguous groups: entirely before the new one, overlapping it, and entirely after it. Copy, merge, copy — one pass.
PatternIntervals & Line Sweep

Instinct See [start, end] pairs, meetings, bookings or the word "overlap"? Sort by an endpoint, then sweep left to right carrying one running fact.

Memory hack Sort, then sweep - start time to merge, end time to choose, +1/-1 events to count the crowd.

Open the Intervals & Line Sweep guide →

Approaches

Brute ForceAppend, Sort, Merge

Time O(n log n)Space O(n)

Ignore the sorted guarantee: add newInterval to the list, sort by start, and run the standard Merge Intervals sweep. Correct for any input, but re-sorts data that is already sorted.

Java
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[] in : all) {
        if (merged.isEmpty() || merged.get(merged.size() - 1)[1] < in[0]) {
            merged.add(new int[] {in[0], in[1]});
        } else {
            int[] last = merged.get(merged.size() - 1);
            last[1] = Math.max(last[1], in[1]);
        }
    }
    return merged.toArray(new int[0][]);
}

Reuses a known routine; wastes the sorted-input guarantee.

At a glance

LevelApproachTimeSpace
Brute ForceAppend, Sort, MergeO(n log n)O(n)
OptimalThree-Phase Linear SweepO(n)O(n) output
Common pitfalls
  • Forgetting the new interval when it goes at the very end or the list is empty.
  • Using < in the overlap test — [1,5] and new [5,7] must merge.
  • Mutating the caller's newInterval array in place — copy into locals.
Interview tips
  • Point out the given sortedness — it's why O(n) is possible.
  • Describe the three phases before coding; each is a simple while loop.
  • Test: empty list, insert at front, at back, and swallowing everything.
Pattern
Sorted intervals + one new interval → skip-before / merge-overlap / copy-after linear sweep.
My notes saved in this browser