Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 1x 1x 1x 1x 1x 1x 1x 2x 2x 9x 9x 2x 2x 2x 2x 2x 2x 3x 2x 2x 2x 3x 2x 2x 2x 1x 1x | // Given an array of integers of length N.
// Majority element occurs with > IN/2] frequency
// Find the majority element.
// • Constraints
// • 1 < N < 1e6
const majorityElement = (arr: number[]): number | undefined => {
if (!arr.length) return;
const dictionary = arr.reduce<Record<string, number>>((acc, current) => {
acc[current] = acc[current] ? acc[current] + 1 : 1;
return acc;
}, {});
const majority = Math.floor(arr.length / 2);
let result;
for(const key in dictionary) {
if (dictionary[key] > majority) {
result = Number(key);
break;
}
}
return result;
};
export default majorityElement;
|