Examples:
Input: votes [] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie" , "john", "johnny", "jamie", "johnny", "john"}; Output: John We have four Candidates with name as ’John’,’ Johnny’, ’jamie’,’ jackie’. The candidates John and Johny get maximum votes. Since John is alphabetically smaller, we print it.
We have a solution to this problem, please refer to candidate names . We can quickly fix this problem in Python using Dictionary data structure . The approach is very simple,
- Convert the given list of votes to a dictionary using counter (iterator) . We will have a dictionary with the names of candidates as key and their frequency (number) as values .
- Since more than one candidate can receive the same number of votes , and in this situation we need to print a lexicographically smaller name, so now we will create another dictionary, going through the previously created dictionary, the number of votes will be key, and the names of candidates — value .
- Now find the value for the maximum number of votes cast for a candidate and get a list of candidates matched against that count.
- Sort the list of candidates who have the same number of votes, and print the first element of the sorted list to print a lexicographically smaller name.
|
Output:
john