Problem 1366

Abstract / Summary

Rank teams by counting how many times each team beats another and order them accordingly.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
20 lines | 557 bytes | submitted September 28, 2023 | GitHub   5% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Counting
  • Hash Table
  • Sorting
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 5 | μ = 5.37 | σ = 1.87

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
24 links | 12 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

32 solutions   September 28, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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