Skip to content

Instantly share code, notes, and snippets.

View dalloglio's full-sized avatar
😉

Ricardo Pires Dall Oglio dalloglio

😉
View GitHub Profile
@dalloglio
dalloglio / find-majority-element.js
Last active April 16, 2024 01:01
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++