Suppose we have a list of strings called votes, here each entry is in lowercase letters and they are representing votes on candidates in order from highest to lowest preference. Here the rank of a candidate depends first by the number of votes received on the highest preference. Now if there are ties, we shall check the number of votes received on next highest preference, and so on. If there are still ties, then they will be ranked alphabetically. So we have to find the final ranking of the teams in order from highest to lowest ranked.
So, if the input is like votes = ["zyx", "zxy", "xyz"], then the output will be "zxy", as z received the most number of highest preference, so it is ranked first. Then x received the second most number of highest preference, and y didn't receive any highest preference votes.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
from collections import defaultdict class Solution: def solve(self, votes): count = len(votes) cand = defaultdict(lambda:  * count) for v in votes: for i, c in enumerate(v): cand[c][i] += 1 return "".join(sorted(cand.keys(), key=lambda x: (cand[x], -ord(x)), reverse=True)) ob = Solution() votes = ["zyx", "zxy", "xyz"] print(ob.solve(votes))
["zyx", "zxy", "xyz"]