Sort Competitors by Vote Position Counts
Heaps, Sorting & SearchAuto-graded · 18 test casesLast updated
Tests multi-criteria sorting with position-based vote counting and lexicographic tiebreaking.
You are given a collection of voting ballots. Each ballot contains the same set of competitors, listed in order of preference from most to least preferred.
Your task is to determine the final ranking of all competitors using these rules:
-
Position-based vote counts: Compare how many times each competitor appears at position 0 (most preferred). The competitor with more votes at position 0 ranks higher. If there's a tie, compare position 1 counts. If still tied, compare position 2, and so on through all positions.
-
Alphabetical tiebreaker: If two competitors have identical vote counts at every position, the one whose identifier comes first alphabetically ranks higher.
Return the final ranking as a list of competitor identifiers.
Constraints
- All ballots contain exactly the same competitors in some order
- Each ballot has between 1 and 26 competitors
- There are between 1 and 1000 ballots
- Competitor identifiers are non-empty strings
- Each competitor appears exactly once per ballot
Examples
Example 1
Input: sort_by_votes([['A', 'B', 'C'], ['A', 'C', 'B'], ['B', 'A', 'C']])
Output: ['A', 'B', 'C']
Example 2
Input: sort_by_votes([['Z', 'X'], ['X', 'Z']])
Output: ['X', 'Z']
Hints
Hint 1
Build a frequency table tracking how many times each competitor appears at each position across all ballots.
Hint 2
Use Python's tuple comparison: tuples are compared element-by-element from left to right.
Hint 3
Since you want higher counts to rank first but tuples sort ascending, negate the counts and append the identifier for the final tiebreak.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires sorting competitors using a custom multi-level comparison rule. The key insight is to build a vote count profile for each competitor, then construct sort keys that encode the comparison rules.
For each competitor, we create a vector where element i represents how many ballots placed that competitor at position i. When comparing two competitors, we look at these vectors position by position: whoever has more votes at position 0 wins. If tied, we check position 1, then position 2, and so forth. If all counts match, the alphabetically smaller identifier wins.
Python's tuple comparison naturally implements this left-to-right precedence. However, tuple comparison orders smaller values first, but we need larger vote counts to rank first. The solution: negate all counts, then append the competitor identifier as the final element. Now standard ascending sort produces the correct ranking.
Why It Works
- Python compares tuples lexicographically. The first differing element determines the order.
- At the first position where two competitors have different vote counts, the one with more votes has the more negative value after negation, so it sorts earlier.
- If all vote counts are identical, comparison reaches the final element (the identifier string), and alphabetical order breaks the tie.
- Since identifiers are unique, no two sort keys are identical, guaranteeing a total ordering.
Complexity
Let B = number of ballots and N = number of competitors.
Time: O(B · N) to build the vote count table by iterating through all ballot entries. Sorting N competitors with keys of length N+1 takes O(N² log N) for the comparisons. Total: O(B · N + N² log N).
Space: O(N²) for the vote count dictionary storing N vectors of length N, plus O(N²) for the sort keys.
With the given constraints (N ≤ 26, B ≤ 1000), the counting phase dominates at roughly 26,000 operations.
Solution
from typing import List
def sort_by_votes(ballots: List[List[str]]) -> List[str]:
competitors = ballots[0]
num_positions = len(competitors)
vote_counts = {comp: [0] * num_positions for comp in competitors}
for ballot in ballots:
for pos, comp in enumerate(ballot):
vote_counts[comp][pos] += 1
return sorted(
competitors,
key=lambda comp: tuple([-cnt for cnt in vote_counts[comp]] + [comp])
)