TypeScript Tape Equilibrium
function tapeEquilibrium(a: number[]): number {
let firstPart = 0;
let secondPart = a.reduce((sum, v) => sum + v, 0);
let min = Infinity;
for (let i = 0; i < a.length - 1; i++) {
firstPart += i;
secondPart -= i;
const difference = Math.abs(firstPart - secondPart);
min = difference < min ? difference : min;
}
return min;
}
This keeps left and right running sums and updates the smallest difference at each split point.
TypeScript Triangle
function triangle(a: number[]): number {
const sorted = [...a].sort((x, y) => x - y);
const c = sorted.length;
if (c < 3) {
return 0;
}
for (let i = 0; i < c - 2; i++) {
if (sorted[i] > 0 && sorted[i] > sorted[i + 2] - sorted[i + 1]) {
return 1;
}
}
return 0;
}
This sorts the values and checks nearby triples, because a valid triangle only needs one local match after sorting.