Field Trip Vote

Easyhash mapAlso known as Majority Element

Your class is voting on a field trip. Each student writes one destination code on a slip: 4 for the aquarium, 9 for the science museum, 17 for the climbing wall, and so on. A trip goes ahead only if one destination gets more than half the votes, and the teacher knows that happened. You need to find the winning destination.

Your task

Write winningTrip(votes). Return the destination code that appears more than votes.length / 2 times.

Such a destination always exists, so there is always exactly one correct answer.

winningTrip(votes: int[]) → int

Examples

Example 1
Input
votes = [9, 4, 9, 17, 9]
Output
9
Why

There are five votes, so the winner needs at least 3. The science museum, code 9, got 3.

Example 2
Input
votes = [4, 4, 17, 17, 17, 17, 4]
Output
17
Why

There are seven votes, so the winner needs at least 4. Code 17 got exactly 4, and it does not matter that the first vote was a 4.

Constraints

  • 1 ≤ votes.length ≤ 50,000
  • 1 ≤ votes[i] ≤ 1,000,000
  • One value appears more than votes.length / 2 times.
Start with brute force

For each vote, scan the whole box, count the matching slips, and return the first code that is past half. That takes O(n²) time, which is up to 2.5 billion comparisons for 50,000 votes. Sorting also works, since the winner must fill the middle position, but it costs O(n log n) and reorders the slips.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code