Skip to lesson

Merge and insert intervals

Sorting intervals by start time brings overlapping spans adjacent, making merging possible in linear time.

Why sorting by start time clusters overlapping intervals

An interval is a range with a start and an end, such as a meeting from 10 to 11. Two intervals overlap when one starts before the other ends.

Activity selection sorts intervals by finish time to discard conflicts. In contrast, interval merging aims to fuse overlapping ranges together. Sorting by start time ensures that overlapping intervals appear consecutively.

Brute force repeatedly compares every pair of intervals to find overlaps. This quadratic approach is slow when handling thousands of intervals.

Step by step

Step 1 of 5

Array: 1, 3.
activeStart
1
activeEnd
3
Sorted intervals: [1,3], [2,6], [8,10], [15,18]. Start with [1,3].

Sorting intervals by start time groups candidates naturally. After sorting, each interval only needs to compare against the previous interval. This reduces interval merging to a single pass running in log-linear time.

The three interval overlap cases

When comparing the current interval to the previous interval, three situations arise.

In case one, intervals are completely disjoint. The current start exceeds the previous end. Here, the previous interval is complete and appended to output. The current interval becomes the new active span.

Example 1 · Brute force: merge any overlapping pair until none remain, O(n^2)

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        List<int[]> list = new ArrayList<>();        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};        for (int[] x : intervals) list.add(x.clone());
        boolean merged = true;        while (merged) {            merged = false;            for (int i = 0; i < list.size() && !merged; i++) {                for (int j = i + 1; j < list.size() && !merged; j++) {                    int[] a = list.get(i);                    int[] b = list.get(j);                    if (a[0] <= b[1] && b[0] <= a[1]) {          // they overlap                        a[0] = Math.min(a[0], b[0]);                        a[1] = Math.max(a[1], b[1]);                        list.remove(j);                        merged = true;                           // start the search again                    }                }            }        }        list.sort((a, b) -> Integer.compare(a[0], b[0]));        for (int[] r : list) System.out.println(Arrays.toString(r));    }}
Output
[1, 6]
[8, 10]
[15, 18]

What this code does

  • Any two overlapping intervals are fused, and the search restarts from the beginning.
  • Each restart compares every pair again, so many overlaps cost O(n^2) or worse.
  • Sorting by start puts overlapping intervals next to each other, so one pass is enough.

Example 2 · Optimal: sort by start, then one pass, O(n log n) time

MergeIntervalsDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class MergeIntervalsDemo {    public static int[][] merge(int[][] intervals) {        if (intervals.length <= 1) return intervals;        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
        List<int[]> merged = new ArrayList<>();        int[] current = intervals[0];        merged.add(current);
        for (int i = 1; i < intervals.length; i++) {            int[] next = intervals[i];            if (next[0] <= current[1]) {                current[1] = Math.max(current[1], next[1]);            } else {                current = next;                merged.add(current);            }        }        return merged.toArray(new int[merged.size()][]);    }
    public static void main(String[] args) {        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};        int[][] res = merge(intervals);        for (int[] r : res) {            System.out.println(Arrays.toString(r));        }    }}
Output
[1, 6]
[8, 10]
[15, 18]

What this code does

  • Sorts intervals by their start coordinate.
  • Fuses [1, 3] and [2, 6] into [1, 6] because 2 is less than or equal to 3.
  • Appends [8, 10] and [15, 18] as disjoint intervals.
  • Sorting puts overlapping intervals side by side, so each interval is compared only with the last merged one.

In case two and three, intervals overlap. If current end exceeds previous end, the span expands. If current end is within previous end, it is fully contained. Both overlap cases update the active end using Math.max.

Find the bug

Spot the merge bug

Select the line that is wrong.

Intervals that touch, like [1, 3] and [3, 5], should merge.

Round 1 of 3

Inserting intervals and computing intersections

Inserting a new interval into sorted disjoint intervals takes linear time. No re-sorting is required.

Example 3 · Insert Interval in Sorted Disjoint List

InsertIntervalDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class InsertIntervalDemo {    public static int[][] insert(int[][] intervals, int[] newInterval) {        List<int[]> res = new ArrayList<>();        int i = 0;        int n = intervals.length;
        // Phase 1: add all intervals ending before newInterval starts        while (i < n && intervals[i][1] < newInterval[0]) {            res.add(intervals[i]);            i++;        }
        // Phase 2: merge overlapping intervals        while (i < n && intervals[i][0] <= newInterval[1]) {            newInterval[0] = Math.min(newInterval[0], intervals[i][0]);            newInterval[1] = Math.max(newInterval[1], intervals[i][1]);            i++;        }        res.add(newInterval);
        // Phase 3: add all intervals starting after newInterval ends        while (i < n) {            res.add(intervals[i]);            i++;        }        return res.toArray(new int[res.size()][]);    }
    public static void main(String[] args) {        int[][] intervals = {{1, 2}, {3, 5}, {6, 7}, {8, 10}, {12, 16}};        int[] newInterval = {4, 8};        int[][] res = insert(intervals, newInterval);        for (int[] r : res) {            System.out.println(Arrays.toString(r));        }    }}
Output
[1, 2]
[3, 10]
[12, 16]

What this code does

  • Phase 1 appends [1, 2] which strictly precedes [4, 8].
  • Phase 2 fuses [3, 5], [6, 7], and [8, 10] with [4, 8] into [3, 10].
  • Phase 3 appends [12, 16] which starts strictly after 10.

Example 4 · Interval List Intersections

IntervalIntersectionDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class IntervalIntersectionDemo {    public static int[][] intervalIntersection(int[][] firstList, int[][] secondList) {        List<int[]> res = new ArrayList<>();        int i = 0;        int j = 0;
        while (i < firstList.length && j < secondList.length) {            int start = Math.max(firstList[i][0], secondList[j][0]);            int end = Math.min(firstList[i][1], secondList[j][1]);
            if (start <= end) {                res.add(new int[]{start, end});            }
            if (firstList[i][1] < secondList[j][1]) {                i++;            } else {                j++;            }        }        return res.toArray(new int[res.size()][]);    }
    public static void main(String[] args) {        int[][] a = {{0, 2}, {5, 10}, {13, 23}, {24, 25}};        int[][] b = {{1, 5}, {8, 12}, {15, 24}, {25, 26}};        int[][] res = intervalIntersection(a, b);        for (int[] r : res) {            System.out.println(Arrays.toString(r));        }    }}
Output
[1, 2]
[5, 5]
[8, 10]
[15, 23]
[24, 24]
[25, 25]

What this code does

  • Overlap exists when start max is less than or equal to end min.
  • Produces single point intersections like [5, 5] when boundaries touch.
  • Advances the pointer of the interval ending earlier.

The algorithm operates in three distinct phases. First, add all intervals that finish before the new interval starts. Second, merge all intervals that overlap the new interval. Update the new start and end using min and max. Third, append all remaining intervals that start after the new interval. Similarly, interval intersections use two pointers to find overlapping spans. Advance whichever interval finishes earlier to explore future overlaps.

Next step

Check your understanding

10 quick questions