Rank Tournament Leaders by Multi-Level Criteria
Heaps, Sorting & SearchAuto-graded · 18 test casesLast updated
Tests sorting and aggregation skills by computing tournament standings with points, goal difference, and goals scored as tie-breakers.
You are organizing a tournament with n teams, each assigned a unique identifier from 0 to n - 1. The tournament results are provided as a list of match outcomes.
You receive:
- An integer
nrepresenting the total number of teams - A 2D list
matcheswhere each entrymatches[i] = [team_a, team_b, goals_a, goals_b]describes one match:team_ascoredgoals_agoals andteam_bscoredgoals_bgoals
Scoring Rules:
- A team earns 3 points for a win (when it scores more goals than its opponent)
- A team earns 1 point for a draw (when both teams score the same number of goals)
- A team earns 0 points for a loss
Ranking Criteria (applied in order):
Teams are ranked by the following rules, checking each criterion only when the previous ones result in a tie:
- Total points (higher is better)
- Goal difference (goals scored minus goals conceded; higher is better)
- Total goals scored (higher is better)
- Team identifier (lower identifier is better)
Your task is to determine the top two teams according to these ranking rules and return their identifiers as a list [first, second].
Constraints:
2 <= n <= 10^41 <= len(matches) <= 10^50 <= team_a, team_b < nwithteam_a != team_b0 <= goals_a, goals_b <= 100- Teams that do not appear in any match still exist and have zero points, zero goal difference, and zero goals scored
Examples
Example 1
Input: rank_top_two_teams(3, [[0, 1, 2, 1], [1, 2, 3, 0], [0, 2, 1, 1]])
Output: [0, 1]
Example 2
Input: rank_top_two_teams(3, [[0, 1, 2, 2], [1, 2, 1, 1], [0, 2, 0, 0]])
Output: [1, 0]
Hints
Hint 1
Track three statistics for each team: points earned, goals scored, and goals conceded. Goal difference can be computed as needed.
Hint 2
Use a composite sorting key that applies all four tie-breaking rules in priority order. Negate numeric values where higher is better to convert the problem into a standard ascending sort.
Hint 3
Remember to include all teams from 0 to n-1 in your ranking, even if they don't appear in any matches.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution breaks down into two clear phases: aggregating match statistics and ranking teams by the composite criteria.
Phase 1: Aggregate Statistics
Process each match once, updating four values for the two participating teams:
- Add the goals each team scored to its goals-scored total
- Add the goals each team conceded to its goals-conceded total
- Award points based on the outcome: 3 for a win, 1 for a draw, 0 for a loss
This takes a single pass through the matches list.
Phase 2: Rank by Composite Key
Construct a sorting key that encodes all four ranking criteria. Python's tuple comparison naturally applies lexicographic ordering—it compares the first element, then breaks ties using the second element, and so on.
The key for each team is:
(-points, -goal_difference, -goals_scored, team_id)
Negating the first three values converts "higher is better" into "lower sorts first" under ascending sort order. The team identifier stays positive since a smaller identifier is preferred. Sort all team identifiers by this key and return the first two.
Correctness
- Symmetric updates: Every match updates both teams correctly. Team A's goals scored become Team B's goals conceded, and vice versa.
- Point assignment: The conditional logic directly implements the win/draw rules with no special cases.
- Tie-breaking precedence: Tuple comparison enforces the exact priority order specified: points first, then goal difference, then goals scored, then identifier.
- Completeness: Iterating over
range(n)ensures every team is ranked, including those with no matches (who correctly get zero for all statistics).
Complexity
- Time: O(m + n log n) where m is the number of matches. Aggregation is O(m), sorting is O(n log n).
- Space: O(n) for the statistics arrays and sorted list.
Code
from typing import List
def rank_top_two_teams(n: int, matches: List[List[int]]) -> List[int]:
points = [0] * n
goals_scored = [0] * n
goals_conceded = [0] * n
for team_a, team_b, goals_a, goals_b in matches:
goals_scored[team_a] += goals_a
goals_conceded[team_a] += goals_b
goals_scored[team_b] += goals_b
goals_conceded[team_b] += goals_a
if goals_a > goals_b:
points[team_a] += 3
elif goals_b > goals_a:
points[team_b] += 3
else:
points[team_a] += 1
points[team_b] += 1
standings = sorted(
range(n),
key=lambda team: (
-points[team],
-(goals_scored[team] - goals_conceded[team]),
-goals_scored[team],
team
)
)
return standings[:2]