"""Blind 75, Interval section (5 problems)."""
import heapq
from typing import List


def insert(intervals: List[List[int]], new: List[int]) -> List[List[int]]:
    """LC 57. Three phases on the sorted list: copy the ones before, merge the overlapping, copy the rest."""
    out, i, n = [], 0, len(intervals)
    start, end = new
    while i < n and intervals[i][1] < start:
        out.append(intervals[i])
        i += 1
    while i < n and intervals[i][0] <= end:
        start, end = min(start, intervals[i][0]), max(end, intervals[i][1])
        i += 1
    out.append([start, end])
    out.extend(intervals[i:])
    return out


def merge(intervals: List[List[int]]) -> List[List[int]]:
    """LC 56. Sort by start; extend the last merged interval while the next one overlaps it."""
    out: List[List[int]] = []
    for s, e in sorted(intervals):
        if out and s <= out[-1][1]:
            out[-1][1] = max(out[-1][1], e)
        else:
            out.append([s, e])
    return out


def erase_overlap_intervals(intervals: List[List[int]]) -> int:
    """LC 435. Greedy by end time: keep the interval that finishes first, drop anything that clashes."""
    removed, last_end = 0, float("-inf")
    for s, e in sorted(intervals, key=lambda x: x[1]):
        if s >= last_end:
            last_end = e
        else:
            removed += 1
    return removed


def can_attend_meetings(intervals: List[List[int]]) -> bool:
    """LC 252 (Premium). Sort by start; any meeting that starts before the previous ends is a clash."""
    intervals = sorted(intervals)
    return all(intervals[i][0] >= intervals[i - 1][1] for i in range(1, len(intervals)))


def min_meeting_rooms(intervals: List[List[int]]) -> int:
    """LC 253 (Premium). Min-heap of end times = rooms in use; reuse a room whose meeting already ended."""
    ends: List[int] = []
    for s, e in sorted(intervals):
        if ends and ends[0] <= s:
            heapq.heapreplace(ends, e)
        else:
            heapq.heappush(ends, e)
    return len(ends)
