TypeScript Equi Leader
function equiLeader(a: number[]): number {
let leaderSize = 0;
let value = 0;
for (const v of a) {
if (leaderSize === 0) {
leaderSize++;
value = v;
} else if (value !== v) {
leaderSize--;
} else {
leaderSize++;
}
}
const candidate = leaderSize > 0 ? value : -1;
let leaderCount = 0;
for (const v of a) {
if (v === candidate) {
leaderCount++;
}
}
let leader = -1;
if (leaderCount > a.length / 2) {
leader = candidate;
}
const count = a.length;
let lLeaderCount = 0;
let equiLeaders = 0;
for (let k = 0; k < count; k++) {
const v = a[k];
const leftHalf = Math.trunc((k + 1) / 2);
const rightHalf = Math.trunc((count - k - 1) / 2);
if (v === leader) {
lLeaderCount++;
}
const rLeaderCount = leaderCount - lLeaderCount;
if (lLeaderCount > leftHalf && rLeaderCount > rightHalf) {
equiLeaders++;
}
}
return equiLeaders;
}
This keeps leader counts on both sides of the split and counts positions where the same leader survives in each half.