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: ZMNAGUEDSJYLBOPHRQICWFXTVK
💡 Note: Only one vote, so all teams have same vote count (1) at their respective positions. Result is alphabetically sorted: 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: Multi-Position Voting System"ABC""ACB""ABC""ACB""ACB"Input: 5 votes from different votersVote Counts by Position:Position 0: A=2, C=3Position 1: A=3, C=2Position 2: B=5Ranking Logic:1. C wins (3 > 2 at pos 0)2. A second (3 > 2 at pos 1)3. B last (only option)Final Result: "ACB"
Understanding the Visualization
1
Input Votes
Array of vote strings, each voter ranks all teams
2
Count by Position
Count votes each team receives at each position
3
Sort Teams
Sort by position priority, then alphabetically
Key Takeaway
🎯 Key Insight: Count votes by position priority, then sort teams using multi-level comparison (position votes + alphabetical)
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