Skip to content
BytePatterns

Insert and Merge a Span

MediumIntervals#intervals#merge~25m

Problem

A calendar stores busy spans as [start, end] pairs, sorted by start and never overlapping or touching. A new busy span arrives. Add it and return the updated list, still sorted and without overlaps, merging any spans that now overlap or share an endpoint. The list may be empty, and every span has start no greater than end.

Examples

Input:  spans = [[1, 2], [4, 6], [9, 10]], new = [5, 9]
Output: [[1, 2], [4, 10]]
Why:    [5, 9] overlaps [4, 6] and touches [9, 10], so all three merge
Input:  spans = [[1, 2], [5, 6]], new = [3, 4]
Output: [[1, 2], [3, 4], [5, 6]]
Why:    the new span fits in the gap
Input:  spans = [], new = [2, 3]
Output: [[2, 3]]
Why:    edge case, an empty calendar

Hints

0 / 3

Stuck on the idea rather than the code? Insert Interval covers it.