Rust Number Of Disc Intersections
fn number_of_disc_intersections(a: &[i64]) -> i64 {
let c = a.len();
let mut start = vec![0i64; c];
let mut end = vec![0i64; c];
for (k, &v) in a.iter().enumerate() {
let k = k as i64;
let key = if k < v { 0 } else { (k - v) as usize };
start[key] += 1;
let key = if k + v >= c as i64 { c - 1 } else { (k + v) as usize };
end[key] += 1;
}
let mut sum = 0i64;
let mut active = 0i64;
for k in 0..c {
sum += active * start[k] + (start[k] * (start[k] - 1)) / 2;
active += start[k] - end[k];
if sum > 10_000_000 {
return -1;
}
}
sum
}
This sorts disc start and end points and counts active overlaps without comparing every pair directly.