Skip to content
BytePatterns

Merge Overlapping Spans

MediumIntervals#intervals#sorting#merge~20m

Problem

You are given closed spans [start, end] in any order. Combine every group of spans that overlap into a single span covering the whole group, and return the result sorted by start. Spans that share even a single point, such as [1, 4] and [4, 5], count as overlapping.

Examples

Input:  spans = [[1, 3], [8, 10], [2, 6], [15, 18]]
Output: [[1, 6], [8, 10], [15, 18]]
Why:    [1, 3] and [2, 6] overlap; the others stand alone
Input:  spans = [[1, 10], [2, 3], [4, 5]]
Output: [[1, 10]]
Why:    spans sitting entirely inside another disappear into it
Input:  spans = [[5, 7]]
Output: [[5, 7]]
Why:    edge case, a single span has nothing to merge with

Hints

0 / 3

Stuck on the idea rather than the code? Merge Intervals covers it.