The task:
Given a list of elements, find the majority element, which appears more than half the time (> floor(len(lst) / 2.0)).
You can assume that such element exists.
For example, given [1, 2, 1, 1, 3, 4, 0], return 1.
My solution:
const lst = [1, 2, 1, 1, 3, 4, 0];
const findMajorityElem = lst => lst.reduce((acc, x) => {
acc[x] = acc[x] ? acc[x] + 1 : 1;
// If I can assume that such an element exists, then it's sufficient to check which element occurs the most.
if (!acc.major || acc.major[1] < acc[x]) { acc.major = [x, acc[x]]; }
return acc;
}, {major: null}).major[0];
console.log(findMajorityElem(lst));
[1, 2, 1, 1, 3, 4, 0]
, 1 appears 3 times,floor(len(lst) / 2.0))
is 3, and since 3 is not more than 3, therefore 1 is not the majority element, and the example list doesn't have a majority element. \$\endgroup\$