TypeScript Number Of Disc Intersections
function numberOfDiscIntersections(a: number[]): number {
let sum = 0;
let active = 0;
const c = a.length;
const start: number[] = new Array(c).fill(0);
const end: number[] = new Array(c).fill(0);
for (let k = 0; k < c; k++) {
const v = a[k];
const startKey = k < v ? 0 : k - v;
start[startKey]++;
const endKey = k + v >= c ? c - 1 : k + v;
end[endKey]++;
}
for (let k = 0; k < c; k++) {
sum += active * start[k] + (start[k] * (start[k] - 1)) / 2;
active += start[k] - end[k];
if (sum > 10000000) {
return -1;
}
}
return sum;
}
This sorts disc start and end points and counts active overlaps without comparing every pair directly.