Field Trip Vote

Easyhash mapAlso known as Majority Element

Your class is choosing a field trip. Every student writes the code of one destination on a slip: 4 for the aquarium, 9 for the science museum, 17 for the climbing wall, and so on. The slips go into a box and are read out one by one.

The school rule says a trip only goes ahead if one destination gets more than half of all votes. This time the teacher already knows it happened. You just need to say which destination won.

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

Five votes, so the winner needs at least 3. The museum, code 9, got 3. The aquarium and the climbing wall got one each.

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

Seven votes, so the winner needs at least 4. Code 17 got exactly 4. The first vote read out was a 4, but that does not make it the winner.

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 and count how many slips match it. Return the first code whose count is more than half.

Every vote can trigger a full scan, so this is O(n²). With 50,000 votes that is up to 2.5 billion comparisons. Sorting also works, because 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