KatInterview

Rank Teams by Weighted Voting Tiers

Heaps, Sorting & SearchAuto-graded · 17 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingcustom sort keyshash maps

Last 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

  1. 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.
  2. 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.
  3. 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 000
  • 1 ≤ number of teams ≤ 26 (at most 26 distinct teams)
  • Each team name is 1–8 uppercase ASCII letters.
  • If ballots is 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.