Video in progress

How do you merge overlapping time intervals, for example [[1,3],[2,6],[8,10]] → [[1,6],[8,10]]?

I sort the intervals by start time and then walk through them: if the current interval overlaps the last one, I extend its end with max; otherwise I start a new interval. Because of the sorting, it's O(n log n).

📖 Answer

static int[][] merge(int[][] intervals) {
    if (intervals.length == 0) return intervals;
    int[][] sorted = intervals.clone();
    Arrays.sort(sorted, Comparator.comparingInt(a -> a[0]));

    List<int[]> out = new ArrayList<>();
    int[] cur = sorted[0].clone();
    for (int i = 1; i < sorted.length; i++) {
        int[] next = sorted[i];
        if (next[0] <= cur[1]) {
            cur[1] = Math.max(cur[1], next[1]);
        } else {
            out.add(cur);
            cur = next.clone();
        }
    }
    out.add(cur);
    return out.toArray(new int[0][]);
}

Why is Math.max needed? Take [1,10] and [2,3]: the second sits inside the first. If you write cur[1] = next[1], the interval shrinks to 3.

<= or < depends on the business. Do [1,3] and [3,5] merge? For a meeting room, if one ends at 3 and the next starts at 3, they usually don't overlap. Ask the interviewer about this.

This problem shows up often in production: booking calendars, compacting IP ranges, merging discount periods.