Election Winner

Medium · rating 1300 · Strings, Hashing

The first line contains n, the number of votes. Each of the next n lines is a candidate's name. Print the name with the most votes. If several tie, print the lexicographically smallest name.

Constraints: 1 ≤ n ≤ 105

Editorial

Approach

Count votes per name in a hash map. Determine the winning tally, then among the candidates who reached it, pick the lexicographically smallest name so ties resolve deterministically.

from collections import Counter
counts = Counter(names)
top = max(counts.values())
print(min(n for n, v in counts.items() if v == top))

Complexity

Time: O(n) over the votes (plus name-length costs). Space: O(k) for k distinct candidates.

Related problems

Open Election Winner in Code Arena →