Skip to content

1366. Rank Teams by Votes 👍

  • Time: $O(n)$
  • Space: $O(26^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
struct Team {
  char name;
  vector<int> rank;
  Team(char name, int teamSize) : name(name), rank(teamSize) {}
};

class Solution {
 public:
  string rankTeams(vector<string>& votes) {
    const int teamSize = votes[0].size();
    string ans;
    vector<Team> teams;

    for (int i = 0; i < 26; ++i)
      teams.push_back(Team('A' + i, teamSize));

    for (const string& vote : votes)
      for (int i = 0; i < teamSize; ++i)
        ++teams[vote[i] - 'A'].rank[i];

    ranges::sort(teams, [](const Team& a, const Team& b) {
      return a.rank == b.rank ? a.name < b.name : a.rank > b.rank;
    });

    for (int i = 0; i < teamSize; ++i)
      ans += teams[i].name;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Team {
  public char name;
  public int[] rank;
  public Team(char name, int teamSize) {
    this.name = name;
    this.rank = new int[teamSize];
  }
}

class Solution {
  public String rankTeams(String[] votes) {
    final int teamSize = votes[0].length();
    StringBuilder sb = new StringBuilder();
    Team[] teams = new Team[26];

    for (int i = 0; i < 26; ++i)
      teams[i] = new Team((char) ('A' + i), teamSize);

    for (final String vote : votes)
      for (int i = 0; i < teamSize; ++i)
        ++teams[vote.charAt(i) - 'A'].rank[i];

    Arrays.sort(teams, new Comparator<Team>() {
      @Override
      public int compare(Team a, Team b) {
        for (int i = 0; i < a.rank.length; ++i)
          if (a.rank[i] > b.rank[i])
            return -1;
          else if (a.rank[i] < b.rank[i])
            return 1;
        return a.name - b.name;
      }
    });

    for (int i = 0; i < teamSize; ++i)
      sb.append(teams[i].name);

    return sb.toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from dataclasses import dataclass


@dataclass
class Team:
  name: str
  rank: list[int]

  def __init__(self, name: str, teamSize: int):
    self.name = name
    self.rank = [0] * teamSize


class Solution:
  def rankTeams(self, votes: list[str]) -> str:
    teamSize = len(votes[0])
    teams = [Team(chr(ord('A') + i), teamSize) for i in range(26)]

    for vote in votes:
      for i in range(teamSize):
        teams[ord(vote[i]) - ord('A')].rank[i] += 1

    teams.sort(key=lambda x: (x.rank, -ord(x.name)), reverse=True)
    return ''.join(team.name for team in teams[:teamSize])