Example 1
- Input
- intervals = [[1,3],[6,9]], newInterval = [2,5]
- Output
- [[1,5],[6,9]]
The newcomer overlaps [1,3], producing [1,5]. The strict gap between 5 and 6 keeps [6,9] separate.
You are given a sorted list of non-overlapping intervals plus one new interval to insert. Splice it into the right position, merging every interval it overlaps, and return the still-sorted non-overlapping result.
Given a sorted list of non-overlapping closed intervals intervals and one closed interval newInterval, insert the newcomer and merge every overlap. Return intervals sorted by start with no overlaps. Closed means both endpoints belong to the interval: sharing even one endpoint counts as overlap.
The input list may be empty and an interval may be a single point. The implementations below preserve both arguments and return newly owned interval rows, so changing the result later does not change either input.
newInterval contain exactly two endpoints.The newcomer overlaps [1,3], producing [1,5]. The strict gap between 5 and 6 keeps [6,9] separate.
The newcomer joins [3,5] and [6,7], then touches [8,10] at 8. Closed endpoints make that contact an overlap, yielding [3,10].
With no existing blocks, the point interval is the entire answer. Its endpoints may be equal, and the returned row is a copy.
The newcomer touches the first block at 3 and the second at 6, connecting both into one closed block.
The newcomer is already contained in the existing interval, so the covered region stays [1,9].
Sorted, non-overlapping input splits around the newcomer into three regions: intervals entirely before it, intervals absorbed into it, and intervals entirely after it. In Example 1, [1,3] overlaps [2,5], widening the pending block to [1,5]; [6,9] then lies wholly after that block. There is no need to reorder the input or compare every pair. Because endpoints are included, [1,3] and [3,5] must merge; a strict gap is required to keep two blocks apart.
Reveal Append Sort Merge: intuition, complexity, and code
intervals list returns just [newInterval].newInterval touching an endpoint, such as [3,5] against [1,3], still overlaps and merges into [1,5].newInterval spanning everything collapses the whole list into a single interval.[1,3] and [3,5] share point 3 and must merge.Sorted input turns insertion into one linear pass: everything left is copied, everything overlapping is folded, and everything right is copied after the folded interval is emitted.