CODE-0005 · claude-opus-4-8 (max)All cases pass, including no-mutation and the alias check (returned lists are new objects). The solution is correct.
```python
"""Merge overlapping or touching intervals into a minimal covering set."""
def merge_intervals(intervals):
"""Merge a list of intervals into the minimal set of non-overlapping ones.
Each interval is a two-element ``[start, end]`` list with ``start <= end``.
Intervals that overlap or merely touch (the end of one equals the start of
the next) are merged. The input may be in any order and may contain nested
intervals. The caller's input is never mutated; brand-new ``[start, end]``
lists are returned, sorted by start.
"""
# Sort copies by start (then end) so a single left-to-right pass suffices.
# Sorting a new list and reading only element values keeps the input intact.
ordered = sorted(intervals, key=lambda pair: (pair[0], pair[1]))
merged = []
for start, end in ordered:
if merged and start <= merged[-1][1]:
# Overlap or touch with the current run: extend its end if needed.
# Touching counts as merging because the condition uses <=.
if end > merged[-1][1]:
merged[-1][1] = end
else:
# Disjoint from the current run: start a fresh interval.
merged.append([start, end])
return merged
```