↻one more pass.
Intervals · Medium

Merge Intervals: the idea to remember.

Return disjoint intervals covering the same points as a set of closed intervals.

Solve on LeetCode ↗

The core insight

Sort by start. Extend the most recent output interval when the next one overlaps; otherwise start a new interval.

Why it works

After sorting, an interval that starts after the current end cannot overlap any earlier completed interval.

The mistake to avoid

The overlap comparison is inclusive for closed intervals. Use Integer.compare instead of subtraction in comparators.

Time: O(n log n)Space: O(n) including output

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int[][] merge(int[][] intervals) {
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
    List<int[]> out = new ArrayList<>();
    for (int[] cur : intervals) {
        if (out.isEmpty() || cur[0] > out.get(out.size() - 1)[1]) out.add(cur.clone());
        else out.get(out.size() - 1)[1] = Math.max(out.get(out.size() - 1)[1], cur[1]);
    }
    return out.toArray(new int[0][]);
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.