Erlang Equi Leader
-module(equi_leader).
-export([equi_leader/1]).
equi_leader(A) ->
N = length(A),
{LeaderSize, LeaderValue} = leader_scan(A),
Candidate = case LeaderSize > 0 of
true -> LeaderValue;
false -> -1
end,
LeaderCount = length([X || X <- A, X =:= Candidate]),
Leader = case LeaderCount > N / 2 of
true -> Candidate;
false -> -1
end,
{_, Count} = lists:foldl(fun({K, V}, {LCount, Equi}) ->
LCount1 = case V =:= Leader of
true -> LCount + 1;
false -> LCount
end,
LeftHalf = (K + 1) div 2,
RightHalf = (N - K - 1) div 2,
RCount = LeaderCount - LCount1,
Equi1 = case LCount1 > LeftHalf andalso RCount > RightHalf of
true -> Equi + 1;
false -> Equi
end,
{LCount1, Equi1}
end, {0, 0}, lists:zip(lists:seq(0, N - 1), A)),
Count.
leader_scan(A) ->
lists:foldl(fun(V, {Size, Value}) ->
case Size of
0 -> {1, V};
_ ->
case Value =:= V of
true -> {Size + 1, Value};
false -> {Size - 1, Value}
end
end
end, {0, undefined}, A).
This keeps leader counts on both sides of the split and counts positions where the same leader survives in each half.