Insert Interval

Medium#57merge

You get a list of intervals sorted by start, with no two overlapping, and one new interval. Put the new interval in, merge it with every interval it overlaps or touches, and return a list that is still sorted and has no overlaps. Our example: [0, 2], [3, 5], [7, 8], [9, 12] and the new [4, 7] — the answer is [0, 2], [3, 8], [9, 12].

input
intervals: intervals [start, end] sorted by start, no two of them meeting; newInterval: one more interval.
returns
intervals with newInterval added and merged with every interval it overlaps or touches, still sorted by start and with no two meeting.
constraints
  • 0 ≤ intervals.length ≤ 500
  • 0 ≤ startᵢ ≤ endᵢ ≤ 10⁵
  • intervals sorted by start, endᵢ < startᵢ₊₁
  • 0 ≤ newInterval[0] ≤ newInterval[1] ≤ 10⁵
our 14 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} intervals
 * @param {number[]} newInterval
 * @return {number[][]}
 */
function insert(intervals, newInterval) {

}
Ctrl ↵
format
reset

saved in this browser

14 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more intervals problems

Pattern “Intervals” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.