CODE-0005 · claude-opus-4-8 (xhigh)
"""Merge overlapping (and touching) intervals into a minimal cover.

Only the Python standard library is used.
"""

from typing import List


def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
    """Return the minimal list of non-overlapping intervals covering the same points.

    Each input interval is a two-element ``[start, end]`` list with ``start <= end``.

    Rules:
      - Overlapping intervals are merged into one.
      - Touching intervals (end of one equals start of the next, e.g. ``[1, 2]`` and
        ``[2, 3]``) are merged into one (``[1, 3]``).
      - Input may be in any order and may contain nested intervals.
      - Empty input returns an empty list.
      - The caller's input is not mutated; fresh ``[start, end]`` lists are returned.
    """
    if not intervals:
        return []

    # Sort by start (then end) without mutating the caller's input. ``sorted`` builds
    # a new outer list; each element is the original inner list, so we never write
    # through to the caller's data and we copy values out when building results.
    ordered = sorted(intervals, key=lambda interval: (interval[0], interval[1]))

    merged: List[List[int]] = []
    for start, end in ordered:
        if merged and start <= merged[-1][1]:
            # Overlaps or touches the current run: extend its end if needed.
            if end > merged[-1][1]:
                merged[-1][1] = end
        else:
            # Disjoint from the current run: start a new interval (fresh list).
            merged.append([start, end])

    return merged