THN Interview Prep

057. Insert Interval

At a Glance

  • Topic: Array
  • Pattern: Analyze Pattern
  • Difficulty: Medium
  • LeetCode: 057

Problem Statement

You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.

Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).

Return intervals after the insertion.

Note that you don't need to modify intervals in-place. You can make a new array and return it.

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

Constraints:

0 <= intervals.length <= 104

...

Approach & Solution Steps

  • Insert then run mergeO(n) time / O(n) space.
  • Single pass three-way mergeO(n) time / O(n) space. <- pick this in interview.

Optimal JS Solution

function insert(intervals, newInterval) {
	const result = [];
	let newStart = newInterval[0];
	let newEnd = newInterval[1];
	let index = 0;
	while (index < intervals.length && intervals[index][1] < newStart) {
		result.push(intervals[index]);
		index++;
	}
	while (index < intervals.length && intervals[index][0] <= newEnd) {
		newStart = Math.min(newStart, intervals[index][0]);
		newEnd = Math.max(newEnd, intervals[index][1]);
		index++;
	}
	result.push([newStart, newEnd]);
	while (index < intervals.length) {
		result.push(intervals[index]);
		index++;
	}
	return result;
}

Edge Cases & Pitfalls

  • Always consider empty or null inputs.
  • Watch out for off-by-one index errors.

Mark this page when you finish learning it.

Last updated on

Spotted something unclear or wrong on this page?

On this page