Created
December 12, 2023 08:33
-
-
Save JoshuaRotimi/91b60a22d625747ce111c2cfabcb6a59 to your computer and use it in GitHub Desktop.
Given an array of integers, return the majority element.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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