Insert and Merge an Interval
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write insertInterval(intervals, newInterval). intervals is an array of [start, end] pairs of whole numbers, with start no more than end, sorted by start, and no two of them overlap or touch; it may be empty. Return a new array: the intervals with newInterval added, sorted by start, after merging it with every interval it overlaps or touches, so [1, 3] and [3, 5] become [1, 5]. Don't change intervals or newInterval. For example, insertInterval([[1, 3], [6, 9]], [2, 5]) is [[1, 5], [6, 9]].
Your code must pass
- Merges the new interval with those it overlaps
- Merges intervals that only touch
- Inserts at the start, middle or end when nothing overlaps
- Handles an empty list
- Leaves the inputs unchanged