Intervals
Medium
Insert Interval
Insert a new interval into a sorted non-overlapping list.
10 min read
Solve on LeetCodeProblem Understanding
You are given an array of non-overlapping intervals sorted by start time. Your task is to insert a new interval into this list and merge any necessary intervals to maintain the sorted, non-overlapping property.
Example:
- Input:
intervals = [[1,3],[6,9]],newInterval = [2,5] - Output:
[[1,5],[6,9]] - Why?
[2,5]overlaps with[1,3]. Combining them gives[1,5].
Algorithm Strategy
Since the list is already sorted, we can solve this in O(N) time using a single pass with three phases:
- Skip Left: Add all intervals that come strictly before the new interval (where
end < newStart). - Merge Overlaps: Use a
whileloop to process intervals that overlap with the new one (wherestart <= newEnd). Continuously update the new interval to[min(start), max(end)]. - Append Right: Once overlaps are resolved, add the (possibly expanded) new interval, then add all remaining intervals.
Interactive Visualization
Step 1 / 1
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
