Rank Teams by Votes

medium array hash map string counting sorting

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.

Inputvotes = ["ABC","ACB","ABC","ACB","ACB"]
Output"ACB"
A is #1 5x. C beats B at position-2 (3 vs 2).

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;
}
Time: O(V·m + m^2 log m) Space: O(m^2)