DEV Community

Discussion on: Fun With Linear Time: My Favorite Algorithm

Collapse
 
ahmedmusallam profile image
Ahmed Musallam • Edited

This is awesome!!

Could not help but rewrite it in javascript to help me understand it better. It's not the syntax, but me trying to wrap my head around it. here is what I have:

function findLeader(votes) {
  // after one vote, we have a leader
  let leader = votes[0];
  let count = 1;

  for (i = 1; i < votes.length; i++) {
    let vote = votes[i]
    if (vote === leader) // the lead may grow
      count++;
    else // or shrink
      count--; 

    // and they may be replaced
    if (count == 0) {
      leader = vote;
      count = 1;
    }
  }
  return leader;
}

console.log(findLeader(['a', 'b', 'a', 'c', 'b', 'c', 'a', 'a'])); // "a"
console.log(findLeader([0, 1, 1, 0, 1, 0, 1, 1])); // "1"

Collapse
 
healeycodes profile image
Andrew Healey

Looks great! Watch out for unshift() which could have an O(n) runtime.

Collapse
 
ahmedmusallam profile image
Ahmed Musallam

ah, good point, updated!