KatInterview

Sort Competitors by Vote Position Counts

Heaps, Sorting & SearchAuto-graded · 18 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingcustom-comparatorcounting

Last 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:

  1. 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.

  2. 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.