How to detect whether any intervals overlap in a vector of start and end times with Rust

1 Answer

0 votes
fn has_overlap(intervals: &mut Vec<[i32; 2]>) -> bool {
    if intervals.is_empty() {
        return true;
    }

    // Sorting is essential because once intervals are ordered by 
    // start time, any overlap can only occur between adjacent intervals.
    intervals.sort_by_key(|x| x[0]);
    // (5,9), (11,12), (15,17)

    // (5,9) and (11,12) → 11 < 9? No
    // (11,12) and (15,17) → 15 < 12? No

    // The loop compares each interval with the one before it.
    for i in 1..intervals.len() {
        if intervals[i][0] < intervals[i - 1][1] {
            return false; // Overlap found
        }
    }

    return true; // No overlap
}

fn main() {
    let mut intervals = vec![
        [11, 12],
        [5, 9],
        [15, 17],
    ];

    if has_overlap(&mut intervals) {
        println!("There are NO overlapping intervals");
    } else {
        println!("There ARE overlapping intervals");
    }
}



/*
run:

There are NO overlapping intervals

*/

 



answered Apr 9 by avibootz

Related questions

...