#57
Medium Algorithms Insert interval
Array
44.8% acceptance
Jan 12, 2026
11765
915
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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn insert(intervals: Vec<Vec<i32>>, new_interval: Vec<i32>) -> Vec<Vec<i32>> {
let mut result = Vec::new();
let mut new_interval = new_interval;
let mut i = 0;
// Add all intervals that come before the new interval
while i < intervals.len() && intervals[i][1] < new_interval[0] {
result.push(intervals[i].clone());
i += 1;
}
// Merge overlapping intervals
while i < intervals.len() && intervals[i][0] <= new_interval[1] {
new_interval[0] = new_interval[0].min(intervals[i][0]);
new_interval[1] = new_interval[1].max(intervals[i][1]);
i += 1;
}
result.push(new_interval);
// Add remaining intervals
while i < intervals.len() {
result.push(intervals[i].clone());
i += 1;
}
result
}
}