MediumNo. 1366

Rank Teams by Votes — LeetCode 1366 Python Solution

Pattern
Sorting
Topics
Array, Hash Table, String, Counting, Sorting
Reading time
2 min

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

PythonSolution
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

Time
O(n × m + m2 × log m)
Space · auxiliary
O(m2)

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

Related problems
No.ProblemDifficulty
0692Top K Frequent WordsMedium
0049Group AnagramsMedium
0169Majority ElementEasy
0229Majority Element IIMedium
0347Top K Frequent ElementsMedium
0451Sort Characters By FrequencyMedium

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 × m + m2 × log m).

What is the space complexity of LeetCode 1366. Rank Teams by Votes?

The Python solution on this page uses O(m2) 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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.