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
- 41 lines of Java from the credited upstream file 1366.java.
- The implementation visibly relies on sequence storage.
- 5 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.
1class Team {2 public char name;3 public int[] rank;4 public Team(char name, int teamSize) {5 this.name = name;6 this.rank = new int[teamSize];7 }8}9 10class Solution {11 public String rankTeams(String[] votes) {12 final int teamSize = votes[0].length();13 StringBuilder sb = new StringBuilder();14 Team[] teams = new Team[26];15 16 for (int i = 0; i < 26; ++i)17 teams[i] = new Team((char) ('A' + i), teamSize);18 19 for (final String vote : votes)20 for (int i = 0; i < teamSize; ++i)21 ++teams[vote.charAt(i) - 'A'].rank[i];22 23 Arrays.sort(teams, new Comparator<Team>() {24 @Override25 public int compare(Team a, Team b) {26 for (int i = 0; i < a.rank.length; ++i)27 if (a.rank[i] > b.rank[i])28 return -1;29 else if (a.rank[i] < b.rank[i])30 return 1;31 return a.name - b.name;32 }33 });34 35 for (int i = 0; i < teamSize; ++i)36 sb.append(teams[i].name);37 38 return sb.toString();39 }40}41