Skip to content

Instantly share code, notes, and snippets.

@JoshuaRotimi
Created December 12, 2023 08:33
Show Gist options
  • Select an option

  • Save JoshuaRotimi/91b60a22d625747ce111c2cfabcb6a59 to your computer and use it in GitHub Desktop.

Select an option

Save JoshuaRotimi/91b60a22d625747ce111c2cfabcb6a59 to your computer and use it in GitHub Desktop.
Given an array of integers, return the majority element.
// Given an array of integers, return the majority element.
// If there is no majority element, return if the array is majority even or odd numbers,
// and if there is none, say so.
function findMajorityNumber(arr) {
const counts = new Map();
let evenCount = 0;
let oddCount = 0;
for (const num of arr) {
counts.set(num, (counts.get(num) || 0) + 1);
if (num % 2 === 0) {
evenCount++;
} else {
oddCount++;
}
}
let majorityNums = [];
let maxCount = 0;
for (const [num, count] of counts) {
if (count > maxCount) {
majorityNums = [num];
maxCount = count;
} else if (count === maxCount) {
majorityNums.push(num);
}
}
if (majorityNums.length === 1) {
return majorityNums[0];
} else {
if (evenCount > oddCount) {
return 'Majority even';
} else if (oddCount > evenCount) {
return 'Majority odd';
} else {
return 'No Majority';
}
}
}
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 10];
console.log(findMajorityNumber(numbers));
console.log(findMajorityNumber([3,1,4,1]))
console.log(findMajorityNumber([33,44,55,66,77]))
console.log(findMajorityNumber([1,2,3,4]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment