#986
Medium Algorithms Interval list intersections
Array Two Pointers Sweep Line
73.0% acceptance
Feb 25, 2026
5899
128
You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b.
The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn interval_intersection(first_list: Vec<Vec<i32>>, second_list: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let (mut i, mut j) = (0, 0);
let mut res = Vec::new();
while i < first_list.len() && j < second_list.len() {
let lo = first_list[i][0].max(second_list[j][0]);
let hi = first_list[i][1].min(second_list[j][1]);
if lo <= hi { res.push(vec![lo, hi]); }
if first_list[i][1] < second_list[j][1] { i += 1; } else { j += 1; }
}
res
}
}