Rank Teams by Votes — LeetCode 1366 Python Solution
MediumArrayHash TableStringCountingSorting
- Problem
- #1366
- Pattern
- Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- votes = ["ABC","ACB","ABC","ACB","ACB"]
- Output
- "ACB"
- Explanation
- Team A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team.
Python solution
Python
class Solution:
def rankTeams(self, votes: List[str]) -> str:
m = len(votes[0])
cnt = defaultdict(lambda: [0] * m)
for vote in votes:
for i, c in enumerate(vote):
cnt[c][i] += 1
return "".join(sorted(cnt, key=lambda c: (cnt[c], -ord(c)), reverse=True))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times m + m^2 \times \log m) |
| Space | O(m^2) auxiliary |
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1366. Rank Teams by Votes is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1366. Rank Teams by Votes?
- LeetCode 1366. Rank Teams by Votes is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1366. Rank Teams by Votes?
- The Python solution on this page runs in O(n \times m + m^2 \times \log m).
- What is the space complexity of LeetCode 1366. Rank Teams by Votes?
- The Python solution on this page uses O(m^2) auxiliary space.
- What topics does LeetCode 1366. Rank Teams by Votes cover?
- LeetCode 1366. Rank Teams by Votes is tagged Array, Hash Table, String, Counting and Sorting on LeetCode.