Rank Teams by Votes - Problem

In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.

The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.

You are given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.

Return a string of all teams sorted by the ranking system.

Input & Output

Example 1 — Basic Voting
$ Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
Output: ACB
💡 Note: Team A gets 2 first-place votes, C gets 3. C wins first position. For second position: A gets 3 votes, C gets 2, so A is second. B is last. Result: ACB
Example 2 — Tie Breaking
$ Input: votes = ["WXYZ","XYZW"]
Output: XWYZ
💡 Note: First position tie: W=1, X=1. Check second position: W=0, X=1, so X wins. Third position: Y=1, Z=1, tie broken alphabetically Y
Example 3 — Alphabetical Fallback
$ Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
Output: ABCDEFGHIJKLMNOPQRSTUVWXYZ
💡 Note: Only one vote, so all teams have same vote count (1) at their respective positions. Since all teams tie in voting, they are sorted alphabetically: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Constraints

  • 1 ≤ votes.length ≤ 1000
  • 1 ≤ votes[i].length ≤ 26
  • votes[i].length == votes[j].length for all i, j
  • votes[i][j] is an English uppercase letter
  • All characters in votes[i] are unique

Visualization

Tap to expand
Rank Teams by Votes INPUT votes[] array (5 voters) [0]: "ABC" [1]: "ACB" [2]: "ABC" [3]: "ACB" [4]: "ACB" Teams: A, B, C A B C 3 positions per vote ALGORITHM STEPS 1 Count Votes Track each team's rank counts 2 Build Count Table Position 1, 2, 3 for each team Team Pos1 Pos2 Pos3 A 5 0 0 B 0 2 3 C 0 3 2 3 Compare Position 1 A=5, B=0, C=0 (A wins!) 4 Tiebreak: Position 2 B=2, C=3 (C beats B!) Sort: A first, then C, then B FINAL RESULT Final Ranking 1st Place A 5 first-place votes 2nd Place C 3rd: B Output String: "ACB" OK - Teams ranked! Key Insight: Use a count array for each team to store votes at each position. Sort teams by comparing position counts from highest (pos 1) to lowest. If all positions tie, use alphabetical order. Time: O(n * m * log(m)) where n = votes, m = teams | Space: O(m * m) for count storage TutorialsPoint - Rank Teams by Votes | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
23.5K Views
Medium Frequency
~25 min Avg. Time
982 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen