#1366

Rank Teams by Votes

Medium
ArrayHash TableStringSortingCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution efficiently counts votes and sorts teams using a custom comparator. This method handles ties effectively and is more scalable for larger inputs.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a dictionary to count votes for each team at each position.
  2. 2Step 2: Create a list of teams and sort it using a custom comparator based on the vote counts and team names.
  3. 3Step 3: Return the sorted list as a string.
solution.py8 lines
1def rankTeams(votes):
2    from collections import defaultdict
3    rank = defaultdict(lambda: [0] * len(votes[0]))
4    for vote in votes:
5        for i, team in enumerate(vote):
6            rank[team][i] += 1
7    sorted_teams = sorted(rank.keys(), key=lambda x: (rank[x], x), reverse=True)
8    return ''.join(sorted_teams)

Complexity note: The time complexity is O(n log n) due to the sorting step of the teams based on their ranks. The space complexity is O(n) because we store the vote counts for each team.

  • 1Understanding how to handle ties is crucial for this problem.
  • 2Using a dictionary to count votes allows for efficient access and updates.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.