Skip to the content

The most voted and the least voted

Problem

In the class vote every ballot is a candidate's number. The list 1, 1, 2, 2, 7, 8, 4, 5, 1 and 4 is ten ballots: number 1 took three, numbers 2 and 4 two each, and 5, 7 and 8 one each.

Write a function that takes the list of ballots and returns the difference between the votes of the most voted and those of the least voted. In the example above that is 3 minus 1, so you return 2.

The rules: only the candidates who got at least one vote count. If everybody tied, the difference is 0. With an empty list you return 0 too.

Counting every ballot against all the others works, but there is a shorter road: sort the ballots and the ones for the same candidate end up together, so one pass measuring how long each group is will do.

Examples

  • Ten ballots

    [1, 1, 2, 2, 7, 8, 4, 5, 1, 4] → 2

  • One takes four

    [1, 7, 9, 2, 3, 3, 1, 3, 3] → 3

  • A tie

    [1, 2, 1, 2] → 0

  • The most voted at the end

    [4, 4, 9, 9, 9] → 1

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def vote_difference(votes):
    pass

JavaScript

function voteDifference(votes) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n log n) challenges

See all challenges →