Skip to content

Instantly share code, notes, and snippets.

@dalloglio
Last active April 16, 2024 01:01
Show Gist options
  • Save dalloglio/eadb309f58b1a26aa8a7eecd81c34cef to your computer and use it in GitHub Desktop.
Save dalloglio/eadb309f58b1a26aa8a7eecd81c34cef to your computer and use it in GitHub Desktop.
Algorithm to find the majority element in an array in linear time and constant space using the Boyer-Moore Voting algorithm. This algorithm works by keeping track of a candidate majority element and its count. It iterates through the array, updating the candidate and count based on certain conditions.
function findMajorityElement(nums) {
let candidate = nums[0]
let count = 1
for (let i = 1; i < nums.length; i++) {
if (count === 0) {
candidate = nums[i]
count = 1
else if (nums[i] === candidate) {
count++
} else {
count--
}
}
return candidate
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment