KatInterview

Podium Finish: Pick the Two Best Clubs in a League Table

Heaps, Sorting & SearchAuto-graded · 24 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingtuple-keystie-breaking

Last updated

Rank teams with a multi-level tiebreak (points, goal difference, goals scored, index) and return the best two indices, testing composite keys and efficient selection.

A league has n teams, numbered 0 to n - 1. Their results are stored in four arrays of equal length. For team i:

  • wins[i] is the number of matches it won,
  • draws[i] is the number of matches it drew,
  • scored[i] is the total goals it scored,
  • conceded[i] is the total goals it let in.

A win is worth 3 points and a draw is worth 1 point, so team i has 3 * wins[i] + draws[i] points. Losses give no points.

Build the league table and return the indices of the team in first place and the team in second place.

Ranking rules

Compare two teams using the following criteria in order. A later criterion is consulted only if the teams are equal on every earlier one.

  1. The team with more points ranks higher.
  2. The team with the larger goal difference (scored[i] - conceded[i], which may be negative) ranks higher.
  3. The team with more goals scored ranks higher.
  4. The team with the smaller index ranks higher.

Because criterion 4 never produces a tie, the ranking is a strict order and the answer is unique.

Output

Return a list [first, second] with the index of the top-ranked team followed by the index of the second-ranked team.

Constraints

  • 2 <= n <= 100000, where n is the common length of the four arrays
  • 0 <= wins[i] <= 1000
  • 0 <= draws[i] <= 1000
  • 0 <= scored[i] <= 100000
  • 0 <= conceded[i] <= 100000
  • Goal difference can be negative.

Examples

Example 1

Input: top_two_clubs([1, 3, 2, 3], [2, 0, 3, 0], [5, 7, 6, 9], [5, 3, 5, 5])

Output: [3, 1]

Example 2

Input: top_two_clubs([2, 2], [1, 1], [4, 4], [2, 2])

Output: [0, 1]

Example 3

Input: top_two_clubs([0, 4, 3], [5, 0, 4], [2, 10, 3], [1, 2, 3])

Output: [2, 1]

Hints

Hint 1

Each team can be summarized by a single tuple. Python compares tuples element by element and only looks at the next element when the earlier ones are equal, which mirrors the tiebreak rules.

Hint 2

Tuple comparison picks the smallest by default, so negate the quantities where larger is better (points, goal difference, goals scored) and keep the index as it is.

Hint 3

You only need two teams, not a full ordering. Find the best team, then find the best among the remaining indices (exclude by index). This takes linear time.