Files
troupe-standup/wizard-work/beam/merge_intervals.py
T

24 lines
853 B
Python

"""Merge overlapping intervals.
merge_intervals(intervals) -> list of [start, end] (inclusive endpoints).
Accepts any iterable of (start, end) pairs. Sorts by start then end.
Handles empty, single, touching (adjacent) intervals per `merge_touching`.
"""
from __future__ import annotations
from typing import Iterable, Tuple, List
def merge_intervals(intervals: Iterable[Tuple[int, int]], *, merge_touching: bool = False) -> List[List[int]]:
items = sorted((tuple(x) for x in intervals), key=lambda p: (p[0], p[1]))
if not items:
return []
out: List[List[int]] = [list(items[0])]
for s, e in items[1:]:
last = out[-1]
threshold = last[1] + (1 if merge_touching else 0)
if s <= threshold:
if e > last[1]:
last[1] = e
else:
out.append([s, e])
return out