Approach
Sorting and greedy selection
For Rank Teams by Votes, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 31 lines of C++ from the credited upstream file 1366.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Team {2 char name;3 vector<int> rank;4 Team(char name, int teamSize) : name(name), rank(teamSize) {}5};6 7class Solution {8 public:9 string rankTeams(vector<string>& votes) {10 const int teamSize = votes[0].size();11 string ans;12 vector<Team> teams;13 14 for (int i = 0; i < 26; ++i)15 teams.push_back(Team('A' + i, teamSize));16 17 for (const string& vote : votes)18 for (int i = 0; i < teamSize; ++i)19 ++teams[vote[i] - 'A'].rank[i];20 21 ranges::sort(teams, ranges::greater{}, [](const Team& team) {22 return pair<vector<int>, char>{team.rank, -team.name};23 });24 25 for (int i = 0; i < teamSize; ++i)26 ans += teams[i].name;27 28 return ans;29 }30};31