KatInterview

Aggregate Tournament Standings from User Rankings

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingarrayssortingaggregation

Last updated

Tests pairwise comparison aggregation, majority voting with tie-breaking, and ranking by win totals.

You receive ranked lists from n users evaluating m items, each labeled 0 through m - 1.

Each user i provides an array rankings[i] containing all m item IDs in their preferred order. Earlier positions indicate stronger preference: if item a appears before item b in rankings[i], user i prefers a to b.

Build an overall ranking using these rules:

Head-to-head comparisons:

For any two distinct items x and y, determine which one wins their direct matchup:

  • Count how many users prefer x over y (call this votes_for_x)
  • Item x defeats item y when either:
    • votes_for_x exceeds half the total users (strict majority: votes_for_x > n / 2), OR
    • votes_for_x equals exactly half (tie in votes: votes_for_x * 2 == n) AND x has a smaller ID than y

Overall ranking:

Each item's strength is measured by its victory count: the number of other items it defeats in head-to-head matchups.

Item x ranks higher than item y when:

  • x has more victories than y, OR
  • They have equal victories and x has a smaller ID

Return all m item IDs ordered from strongest to weakest according to this ranking.

Constraints:

  • 1 <= n <= 1000
  • 1 <= m <= 100
  • Each rankings[i] is a valid permutation of [0, 1, ..., m-1]

Examples

Example 1

Input: compute_ranked_items(3, 4, [[0, 1, 2, 3], [0, 2, 1, 3], [1, 0, 2, 3]])

Output: [0, 1, 2, 3]

Example 2

Input: compute_ranked_items(2, 3, [[0, 1, 2], [2, 1, 0]])

Output: [0, 1, 2]

Example 3

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

Output: [4, 3, 2, 1, 0]

Hints

Hint 1

Build a matrix tracking how many users prefer each item over each other item by examining positions in the ranking arrays.

Hint 2

Use integer arithmetic (multiply by 2) when checking for majority to avoid floating-point precision issues.

Hint 3

An item's victory count can be computed by checking all possible opponents and applying the defeat rules consistently.