Arrays and strings · Exercise 13 of 100
Majority Element
A majority value occupies more than half the slots in an array. Count the occurrences of each value and compare them with half the length. If none exceeds that threshold, the array has no majority.
Try it yourself
Seven votes arrive as [pear, plum, plum, pear, plum, lime, plum]. Which fruit has a majority?
One-step hint
Keep a tally for each fruit. With seven votes, a majority must have more votes than all the other fruits combined.
Worked solution
- Half of seven is 3.5, so a fruit needs at least four votes to have a majority.
- Plum appears in slots two, three, five and seven. Its four votes make plum the majority.