Rank Teams by Votes
Problem
Given an array of voter rankings of teams (each a string permutation), return a string of team labels ordered by: rank-1 votes desc, then rank-2 votes desc, …; ties broken by alphabetical team name.
votes = ["ABC","ACB","ABC","ACB","ACB"]"ACB"def rank_teams(votes):
m = len(votes[0])
tally = {c: [0] * m for c in votes[0]}
for v in votes:
for i, c in enumerate(v):
tally[c][i] += 1
return ''.join(sorted(tally, key=lambda c: ([-x for x in tally[c]], c)))
function rankTeams(votes) {
const m = votes[0].length;
const tally = {};
for (const c of votes[0]) tally[c] = new Array(m).fill(0);
for (const v of votes) for (let i = 0; i < m; i++) tally[v[i]][i]++;
return Object.keys(tally).sort((a, b) => {
for (let i = 0; i < m; i++) if (tally[a][i] !== tally[b][i]) return tally[b][i] - tally[a][i];
return a < b ? -1 : 1;
}).join("");
}
class Solution {
public String rankTeams(String[] votes) {
int m = votes[0].length();
Map tally = new HashMap<>();
for (char c : votes[0].toCharArray()) tally.put(c, new int[m]);
for (String v : votes) for (int i = 0; i < m; i++) tally.get(v.charAt(i))[i]++;
List teams = new ArrayList<>(tally.keySet());
teams.sort((a, b) -> {
int[] ta = tally.get(a), tb = tally.get(b);
for (int i = 0; i < m; i++) if (ta[i] != tb[i]) return tb[i] - ta[i];
return a - b;
});
StringBuilder sb = new StringBuilder();
for (char c : teams) sb.append(c);
return sb.toString();
}
}
string rankTeams(vector& votes) {
int m = votes[0].size();
map> tally;
for (char c : votes[0]) tally[c] = vector(m, 0);
for (auto& v : votes) for (int i = 0; i < m; i++) tally[v[i]][i]++;
string s = votes[0];
sort(s.begin(), s.end(), [&](char a, char b) {
for (int i = 0; i < m; i++) if (tally[a][i] != tally[b][i]) return tally[a][i] > tally[b][i];
return a < b;
});
return s;
}
Explanation
The ranking rule says: a team that got more first-place votes wins; if tied, compare second-place votes, then third, and so on; if still tied, the alphabetically smaller name wins. The key idea is to turn each team into a vector of position counts and then just sort by that vector.
We build tally, a map from each team to an array of length m (the number of rank positions). For every ballot, position i holds team v[i], so we do tally[v[i]][i] += 1 to record one vote for that team at that rank.
Then we sort the teams. The key compares the tally vectors: we want higher counts first, so each count is negated ([-x for x in tally[c]]), and ties fall back to the team letter c for alphabetical order.
Example: ["ABC","ACB","ABC","ACB","ACB"]. A is ranked 1st in all 5 ballots, so A leads. B and C are tied at rank 1 (zero each) but at rank 2, C appears 3 times vs B's 2, so C beats B. Result: "ACB".