Python 1366.py
class Solution:
def rankTeams(self, votes: List[str]) -> str:
teams = {}
for c in votes[0]:
teams[c] = 255 - ord(c) # reverse
places = len(teams)
for v in votes:
for i, c in enumerate(v):
shift = 10000**(1 + places - i)
teams[c] += shift
all = []
for t in teams:
all.append((teams[t], t))
result = ""
for score, name in sorted(all, reverse = True):
result += name
return result
Difficulty
and has an acceptance rate of about 60% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Counting
- Hash Table
- Sorting
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The rankTeams method receives a collection of vote strings, each string containing the same set of team identifiers ordered by preference. The algorithm converts these rankings into a single numeric score per team, then orders the teams by those scores to produce the final ranking string.
Initialization of Team Scores
The first loop extracts the distinct team identifiers from the first vote and creates a dictionary that maps each team to a base value derived from its character code:
teams = {}
for c in votes[0]:
teams[c] = 255 - ord(c) # reverse alphabetical seed
The expression 255 - ord(c) yields a larger seed for letters earlier in the alphabet, establishing a deterministic tie-breaker that prefers alphabetical order when all other criteria are equal.
Determining the Weight of Each Position
The variable places records the number of teams, which also equals the length of each vote string:
places = len(teams)
For every vote, the inner loop walks through each character and computes a positional weight (shift). The weight is a power of 10000 that depends on how far the position is from the end of the ranking:
for v in votes:
for i, c in enumerate(v):
shift = 10000**(1 + places - i)
teams[c] += shift
Because the exponent grows as the position moves toward the front of the vote, earlier preferences contribute a dramatically larger amount to the team’s total score. This encoding collapses the entire ranking vector into a single integer while preserving the relative importance of each rank.
Collecting Scores for Sorting
After all votes have been processed, the algorithm builds a list of (score, team) tuples:
all = []
for t in teams:
all.append((teams[t], t))
Each tuple pairs the accumulated integer score with its corresponding team identifier, preparing the data for a straightforward sort.
Ordering Teams and Producing the Result
The list of tuples is sorted in descending order based on the numeric score. Because the initial seed already encodes alphabetical precedence, the sort automatically resolves ties without additional logic:
result = ""
for score, name in sorted(all, reverse=True):
result += name
return result
The final string concatenates the team identifiers in the order determined by the sorted scores, delivering the required ranking.
Edge Cases Handled
When multiple teams receive identical positional contributions across all votes, the initial seed (255 - ord(c)) ensures that the alphabetical order is used as a deterministic fallback. The algorithm also gracefully handles the situation where there is only a single vote; the positional weights still differentiate the teams, and the alphabetical seed resolves any remaining ties.
Performance Optimizations
The design avoids storing a two-dimensional count matrix. By encoding the rank frequencies into a single large integer per team, the method reduces memory overhead to a simple dictionary of integers. Updating scores uses direct arithmetic (+= shift), which is faster than incrementing separate counters for each rank. The final sorting step works on a list whose size equals the number of distinct teams, guaranteeing that the dominant cost scales with the number of teams rather than the total number of votes. This approach yields a compact and efficient solution for the ranking problem.
ELI5 - Simplified Explanation
Imagine a large group of friends voting for their favorite crayon colors. Each person writes down the colors in order from their most favorite to their least favorite.
The computer needs a way to figure out which color wins overall. It starts by looking at all the different colors available. For every color, it keeps a secret scorecard that starts with a tiny number.
Then, it goes through every single ballot one by one. When a color shows up in first place on a ballot, it gets a massive bonus added to its scorecard. If a color shows up in second place, it gets a slightly smaller bonus, and so on for every position.
The computer is very careful to give much bigger points for being in first place than in any other spot. It keeps track of these big totals for every single color.
Once every ballot has been counted, the computer looks at all the final scorecards. It lines up the colors, putting the one with the biggest score at the very front of the line. Finally, it reads the names of the colors starting from the front of the line to the back to show which colors everyone liked the best.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | Rust | TS | |||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| martianoff | Scala | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| martianoff | Scala | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 911: Online Election
Solved On The Same Day
- problem 880: Decoded String at Index
- problem 912: Sort an Array
- problem 923: 3Sum With Multiplicity
- problem 973: K Closest Points to Origin
- problem 1010: Pairs of Songs With Total Durations Divisible by 60
- problem 1054: Distant Barcodes
- problem 1079: Letter Tile Possibilities
- problem 1090: Largest Values From Labels
- problem 1347: Minimum Number of Steps to Make Two Strings Anagram
- problem 1419: Minimum Number of Frogs Croaking
- problem 1738: Find Kth Largest XOR Coordinate Value
- problem 1814: Count Nice Pairs in an Array
- problem 1985: Find the Kth Largest Integer in the Array
- problem 2018: Check if Word Can Be Placed In Crossword
- problem 2150: Find All Lonely Numbers in the Array
- problem 2182: Construct String With Repeat Limit
- problem 2225: Find Players With Zero or One Losses
- problem 2232: Minimize Result by Adding Parentheses to Expression
- problem 2244: Minimum Rounds to Complete All Tasks
- problem 2284: Sender With Largest Word Count
- problem 2343: Query Kth Smallest Trimmed Number
- problem 2526: Find Consecutive Integers from a Data Stream
- problem 2844: Minimum Operations to Make a Special Number
- problem 2860: Happy Students
- problem 906: Super Palindromes
- problem 992: Subarrays with K Different Integers
- problem 1106: Parsing A Boolean Expression
- problem 1601: Maximum Number of Achievable Transfer Requests
- problem 2081: Sum of k-Mirror Numbers
- problem 2122: Recover the Original Array
- problem 2416: Sum of Prefix Scores of Strings
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality