Rank Teams by Weighted Voting Tiers
Heaps, Sorting & SearchAuto-graded · 17 test casesLast updated
Tests the ability to design a multi-key custom sort comparator over aggregated data using a priority-queue-style ranking of teams from ranked ballots.
Rank Teams by Weighted Voting Tiers
A tournament collects ballots from voters. Each ballot is a list of distinct team names ordered from most preferred (index 0) to least preferred. Your task is to produce a final ranking of all teams.
Scoring Rules
- Position counts: For each team, count how many ballots placed it in 1st place, how many in 2nd place, and so on. These counts form the team's score vector.
- Primary sort: Teams are ranked by their score vectors in lexicographically descending order. That is, the team with the highest 1st-place count comes first; ties are broken by 2nd-place counts, then 3rd-place counts, and so on.
- Tie-break: If two teams have identical score vectors (which can only happen if they both received zero votes at every position), sort them alphabetically ascending by name.
Input
ballots: a list of ballots. Each ballot is a list of strings (team names). All ballots contain exactly the same set of teams in some order.- Every string in a ballot is a non-empty ASCII string of uppercase letters only.
Output
Return a single string: the team names joined by "," in final ranked order (1st-place team first).
Constraints
0 ≤ len(ballots) ≤ 2 0001 ≤ number of teams ≤ 26(at most 26 distinct teams)- Each team name is 1–8 uppercase ASCII letters.
- If
ballotsis empty, return the empty string"". - If there is only one team, return that team's name.
- All ballots are guaranteed to be non-empty and contain the same set of teams.
Examples
Example 1
Input: rank_teams([['ALPHA', 'BETA', 'GAMMA'], ['BETA', 'ALPHA', 'GAMMA'], ['ALPHA', 'BETA', 'GAMMA']])
Output: 'ALPHA,BETA,GAMMA'
Example 2
Input: rank_teams([['RED', 'BLUE'], ['BLUE', 'RED'], ['RED', 'BLUE'], ['BLUE', 'RED']])
Output: 'BLUE,RED'
Example 3
Input: rank_teams([['X', 'Y', 'Z'], ['Y', 'Z', 'X'], ['Z', 'X', 'Y']])
Output: 'X,Y,Z'
Hints
Hint 1
Build a dictionary mapping each team to a list of length equal to the number of teams, where position i holds the count of ballots that placed this team at index i.
Hint 2
Use sorted() with a key that returns a tuple: the negated score vector (so descending order works with the default ascending sort) followed by the team name (for alphabetical tie-breaking).
Hint 3
Remember that negating a list element-wise can be done with a tuple comprehension: tuple(-c for c in counts), and appending the team name at the end handles the final tie-break in one clean key.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
The problem reduces to sorting teams by a custom multi-level key:
- Build a score matrix: for each team, record how many ballots placed it at each rank position (index 0 = 1st place, etc.).
- Sort teams so that the team with the best (highest) 1st-place count comes first. Ties at position 0 fall through to position 1, then 2, and so on — this is exactly a lexicographically descending comparison of the score vectors.
- If two teams are still tied after all positions, sort them alphabetically (ascending) by name.
Implementation
We use Python's sorted() with a tuple key:
key = (tuple(-count for count in score_vector), team_name)
Negating the counts converts "descending by counts" into "ascending by negated counts", letting Python's default ascending sort handle everything in one pass. Appending the team name at the end of the key tuple gives the alphabetical tie-break for free.
Why it is correct
- Score vectors have the same length for all teams (= number of teams), so lexicographic comparison is well-defined and covers all positions.
- Negation is a monotone-reversing transformation, so descending order on original values equals ascending order on negated values.
- Python's
sorted()is stable, but we don't rely on stability — the explicit name component in the key makes the ordering fully deterministic.
Edge Cases
- Empty ballots: return
""immediately (no teams exist). - Single team: the score vector has one entry; sorting trivially returns that team.
- Perfect tie (all-zero vectors or symmetric distribution): the alphabetical component in the key ensures a unique, deterministic answer.
Complexity
- Time: O(V × T + T log T), where V = number of ballots and T = number of teams. Building scores is O(V × T); sorting T teams is O(T log T) with a key of length T, so O(T² log T) in the worst case — negligible for T ≤ 26.
- Space: O(T²) for the score matrix.
Reference Solution
from typing import List
def rank_teams(ballots: list) -> str:
if not ballots:
return ""
teams = ballots[0] # representative ballot gives us all team names
n = len(teams)
# initialise score vectors
scores = {team: [0] * n for team in teams}
for ballot in ballots:
for position, team in enumerate(ballot):
scores[team][position] += 1
# sort key: descending score vector, then ascending name
ranked = sorted(teams, key=lambda t: (tuple(-c for c in scores[t]), t))
return ",".join(ranked)