MediumArrayIntervals

Insert Interval

LeetCode
1 approach, code in all languages

You start with a list of non-overlapping intervals that is already ordered by start value. A single new interval arrives, and you must slot it into the list so that the final collection stays sorted and free of overlaps, merging with any existing intervals that it touches.

Return the updated list. Because the original data is presorted, a full re-sort is unnecessary; a single linear pass can place and merge the newcomer.

Example 1

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

Output: [[1,5],[6,9]]

The new range 2-5 overlaps 1-3, so they fuse into 1-5 while 6-9 stays untouched.

Example 2

Input: intervals = [[1,2],[3,5],[6,7],[8,10]], newInterval = [4,8]

Output: [[1,2],[3,10]]

4-8 spans 3-5, 6-7 and 8-10, collapsing all three into 3-10.

Constraints

  • 0 ≤ intervals.length ≤ 10^4
  • intervals[i].length == 2 and newInterval.length == 2
  • 0 ≤ start ≤ end ≤ 10^5
  • intervals is sorted by start in ascending order with no overlaps
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now