881634. Winner of an election
Easy
Winner of an Election
Summary
In this problem, we are given a list of votes where each vote is represented as a string (candidate name). We need to determine the winner of the election. The problem involves manipulating strings and using hash data structures.
Detailed Explanation
To solve this problem, we can use a hash map (or dictionary) to store the count of votes for each candidate. We iterate through the list of votes and increment the count for each candidate in the hash map. Finally, we find the candidate with the maximum vote count to determine the winner.
Here is a step-by-step breakdown of the solution:
- Initialize an empty hash map (e.g.,
HashMap<String, Integer>) to store the count of votes for each candidate. - Iterate through the list of votes and increment the count for each candidate in the hash map.
- Find the candidate with the maximum vote count by iterating through the hash map.
Time complexity: O(n), where n is the number of votes. Space complexity: O(1), as we only use a constant amount of space to store the hash map.
Optimized Solutions
Java
import java.util.HashMap;
import java.util.Map;
public class ElectionWinner {
public static String findWinner(String[] votes) {
Map<String, Integer> candidateVotes = new HashMap<>();
for (String vote : votes) {
candidateVotes.put(vote, candidateVotes.getOrDefault(vote, 0) + 1);
}
return Collections.max(candidateVotes.entrySet(), (a, b) -> a.getValue().compareTo(b.getValue())).getKey();
}
}