4
\$\begingroup\$

Challenge

There are n citizens voting in this year's HackLand election. Each voter writes the name of their chosen candidate on a ballot and places it in a ballot box. The candidate with the highest number of votes wins the election; if two or more candidates have the same number of votes, then the tied candidates' names are ordered alphabetically and the last name wins.

Complete the electionWinner function in your editor. It has 1 parameter: an array of strings, votes, describing the votes in the ballot box. This function must review these votes and return a string representing the name of the winning candidate.

My Code

function electionWinner(votes) {
    const vObj = {};
    for(let v of votes){
        vObj[v] = (vObj[v] || 0) + 1;
    }

    let winners = [];
    let maxVotes = 0;

    for(let name in vObj){
        if(vObj[name] > maxVotes){
            maxVotes = vObj[name];
            winners = [name];
        }
        else if (vObj[name] === maxVotes){
            winners.push(name);
        }
    }

    if(winners.length === 1){
        return winners[0];
    }
    winners.sort();
    return winners[winners.length - 1];
}
\$\endgroup\$
2
\$\begingroup\$

You can write this simpler:

if(winners.length === 1){
    return winners[0];
}
winners.sort();
return winners[winners.length - 1];

Like this:

winners.sort();
return winners[winners.length - 1];

Because if winner contains one element, winners.sort() will do nothing anyway.


vObj is a poor name for a map of vote counts per name.


It could be a good idea to decompose the implementation to smaller functions with a single responsibility:

  • Build a map of vote counts
  • Find winners
  • Find the single winner
\$\endgroup\$
0
2
\$\begingroup\$

Sorting has worse runtime complexity (O(n log n)) than the search for a minimum/maximum (O(n)). For small n that doesn't matter much but once you have tens of thousands of candidates tied for first place it should become noticeable.

Unfortunately Math.max.apply(null, winners) only works if candidate names are numeric but we can come up with another short solution:

return winners.reduce(function(a, b) { return (a >= b) ? a : b; });
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.