Opening the reading…
Opening the reading…
SORTING › CUSTOM SORT
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →The rule compares teams at first place before it considers second place, and second place before it considers third place. For each team, record a count for every position: its first-place count, its second-place count, and so on. This produces one count vector per team, and the overall ranking compares these vectors from left to right.
When two vectors first differ, the team with the larger count at that position wins, because every later position is irrelevant once an earlier position breaks the tie. If the vectors never differ, the teams are genuinely tied by votes, so comparing their letters alphabetically gives a deterministic final order.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(nm + m^2 log m) | Building the count table visits each of the n votes at all m positions. Sorting performs O(m log m) comparisons, and one comparison may scan all m positions before finding a difference, so the worst case is O(m^2 log m) for sorting. |
| Space | O(26m) extra, or O(m) with the fixed alphabet | The count table has 26 rows and m columns, while sorting the m-character string uses only the sort routine's small auxiliary stack. The returned string is required output and is excluded. This bound does not degrade with the arrangement of the votes; even the worst tie pattern only makes comparisons scan farther, not the count table grow. |
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string rankTeams(vector<string>& votes) {
if (votes.empty()) return "";
int n = votes.size();
int m = votes[0].size();
vector<vector<int>> cnt(26, vector<int>(m, 0));
for (const string& vote : votes) {
for (int i = 0; i < m; ++i) {
cnt[vote[i] - 'A'][i]++;
}
}
string teams = votes[0];
sort(teams.begin(), teams.end(), [&](char a, char b) {
int ia = a - 'A';
int ib = b - 'A';
for (int i = 0; i < m; ++i) {
if (cnt[ia][i] != cnt[ib][i]) {
return cnt[ia][i] > cnt[ib][i];
}
}
return a < b;
});
return teams;
}
};The comparator must scan positions in voting order, not in whichever order is convenient. Returning as soon as one count differs is safe because that position is the first evidence separating the teams. The final a < b comparison is reached only when every count matches, so it implements the problem's alphabetical tie-break without overriding any meaningful vote result.