AlgoInsight

DSA problem

Insert Interval

MediumIntervalsPattern: Intervalstop150GoogleFacebookAmazonMicrosoftLinkedIn

You are given an array of non-overlapping intervals intervals sorted by their start times, and a new interval newInterval = [start, end] to insert. Insert newInterval into intervals such that the result is still sorted by start time and contains no overlapping intervals (merging if necessary). Return the resulting list.

Because intervals is already sorted and non-overlapping, you do not need to re-sort. A clean three-phase approach handles the work in a single linear pass. Phase one copies every interval that ends strictly before newInterval starts: these are untouched by the insertion and belong at the front of the result.

Phase two merges all intervals that overlap with newInterval. An interval [a, b] overlaps with newInterval when a <= newInterval[1] and b >= newInterval[0]. In the sorted scan, after phase one we walk through every interval whose start is at most newInterval[1], expanding newInterval to absorb each one: newInterval[0] = min(newInterval[0], a) and newInterval[1] = max(newInterval[1], b). After the loop append the (possibly grown) newInterval to the result.

Phase three copies all remaining intervals (those that start strictly after newInterval[1]) unchanged. Each input interval is visited at most once, so the total time is O(n) with O(n) output space.

Examples

Example 1
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Explanation: [1,3] overlaps with [2,5] and merges to [1,5]. [6,9] does not overlap with the merged result.
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: [1,2] is before; [3,5], [6,7], [8,10] all overlap with [4,8] and merge into [3,10]; [12,16] is after.
Example 3
Input: intervals = [], newInterval = [5,7]
Output: [[5,7]]
Explanation: An empty input produces a result with just the new interval.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arrayintervals

Browse all DSA problems