KatInterview

Rank Tournament Leaders by Multi-Level Criteria

Heaps, Sorting & SearchAuto-graded · 18 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingsimulationaggregation

Last 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 n representing the total number of teams
  • A 2D list matches where each entry matches[i] = [team_a, team_b, goals_a, goals_b] describes one match: team_a scored goals_a goals and team_b scored goals_b goals

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:

  1. Total points (higher is better)
  2. Goal difference (goals scored minus goals conceded; higher is better)
  3. Total goals scored (higher is better)
  4. 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^4
  • 1 <= len(matches) <= 10^5
  • 0 <= team_a, team_b < n with team_a != team_b
  • 0 <= 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.