Merge intervals with gap

Write codeMedium14 min

Your task

Given an unsorted list of closed intervals [start, end] and a nonnegative gap g, repeatedly merge any two intervals whose distance is at most g, where overlapping intervals have distance 0 and disjoint ones are separated by the space between them. Keep merging until no pair qualifies, then return the resulting intervals sorted by start. Example: [[1,3],[6,8]] with g = 3 gives [[1,8]], but with g = 2 stays [[1,3],[6,8]].

Examples

merge_with_gap(intervals: list[list[int]], g: int) -> list[list[int]]
Example 1
Inputmerge_with_gap([[1, 3], [6, 8]], 3)
Output[[1, 8]]