Rank Teams by Votes
Problem
A group of voters ranks a fixed set of teams in an election. Each voter submits a ballot as a string, where each character is a team's unique single-letter identifier, and the order of the letters in that string represents their personal ranking of the teams from most preferred to least preferred.
You are given votes, an array of these ballot strings. Every ballot contains the exact same set of letters (one per team), just possibly arranged differently. Determine the overall team ranking using the following rule: a team's position is decided by how many voters ranked it 1st; ties in first-place votes are broken by how many voters ranked it 2nd, then 3rd, and so on through every position, comparing counts at each position in order until the tie is resolved. If two teams remain tied after comparing all positions, the one whose letter comes first alphabetically ranks higher.
Return a single string containing all the team letters ordered from the winning team to the last-place team according to these rules.
- You must consider every position, not just the first-place count, when resolving ties.
- Ties broken purely alphabetically only happen if a full comparison across all rank positions still leaves teams tied.
- The output must include every team letter exactly once.
Examples
Example 1:
Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
Output: "ACB"
Explanation:
- A appears 1st on all 5 ballots, so A wins outright.
- For 2nd place, B appears 2nd twice ("ABC" occurs twice) and C appears 2nd three times ("ACB" occurs three times), so C outranks B.
- Final order: A, C, B.
Example 2:
Input: votes = ["WXYZ","XYZW","YZWX","ZWXY"]
Output: "WXYZ"
Explanation:
- Each of W, X, Y, Z receives exactly one 1st-place vote, one 2nd-place vote, one 3rd-place vote, and one 4th-place vote, so every position count is tied across all four teams.
- With a complete tie at every rank, the result falls back to alphabetical order: W, X, Y, Z.
Example 3:
Input: votes = ["QP","PQ","QP"]
Output: "QP"
Explanation:
- Q is ranked 1st on 2 of the 3 ballots versus P's 1, so Q takes the top spot and P is second.
Constraints
1 <= votes.length <= 10001 <= votes[i].length <= 26votes[i]consists of distinct uppercase English letters.- All ballots in
voteshave the same length and contain the same set of letters, just possibly in a different order.
Solution
Sign in to get AI feedback on your answer. Your work is saved while you do.
Sign in to evaluate