Back to Practice
#0256
Insert Interval
MediumDSA28 min20 XP
Problem
Intervals are sorted and non-overlapping. Insert new_interval, merge if necessary, and return the updated interval list.
Why This Matters
Insert interval tests whether you can split a timeline into before, merge, and after sections without overcomplicating it.
Function Signature
def insert_interval(intervals, new_interval):
Examples
Example 1
Inputintervals = [[1,3],[6,9]], new_interval = [2,5]
Output[[1, 5], [6, 9]]
The new interval overlaps [1,3] and extends it to [1,5].
Constraints
- Return the exact requested value.
- Handle edge cases cleanly.
- Use the intended DSA pattern when brute force would scale poorly.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Merge one interval
Input[[1,3],[6,9]], [2,5]
Expected[[1, 5], [6, 9]]
The new interval merges with the first interval.
Merge many intervals
Input[[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8]
Expected[[1, 2], [3, 10], [12, 16]]
The new interval connects three middle intervals.
Hidden Test Categories
new interval before all intervalsnew interval after all intervalsempty intervals