CODE-0005 · claude-opus-4-8 (high)def merge_intervals(intervals):
"""Merge overlapping or touching intervals into the minimal covering set.
Args:
intervals: list of [start, end] pairs with start <= end, in any order,
possibly overlapping or nested.
Returns:
A new list of non-overlapping [start, end] lists, sorted by start.
Intervals that overlap or merely touch are merged.
"""
if not intervals:
return []
# Copy each interval so the caller's input is never mutated, then sort by
# start (and end as a tiebreaker) without disturbing the original list.
ordered = sorted(([start, end] for start, end in intervals),
key=lambda pair: (pair[0], pair[1]))
merged = [ordered[0]]
for start, end in ordered[1:]:
last = merged[-1]
# Overlap or touch: the next start is at or before the current end.
if start <= last[1]:
if end > last[1]:
last[1] = end
else:
merged.append([start, end])
return merged