Skip to main content

Tournament Winners - Solution & Explanation

HardPremiumFree on FleetCodeDatabase4 min readAsked at: Wayfair
Practice this problem

Problem Statement

Table: Players

+-------------+-------+
| Column Name | Type  |
+-------------+-------+
| player_id   | int   |
| group_id    | int   |
+-------------+-------+
player_id is the primary key (column with unique values) of this table.
Each row of this table indicates the group of each player.

Table: Matches

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| match_id      | int     |
| first_player  | int     |
| second_player | int     | 
| first_score   | int     |
| second_score  | int     |
+---------------+---------+
match_id is the primary key (column with unique values) of this table.
Each row is a record of a match, first_player and second_player contain the player_id of each match.
first_score and second_score contain the number of points of the first_player and second_player respectively.
You may assume that, in each match, players belong to the same group.

 

The winner in each group is the player who scored the maximum total points within the group. In the case of a tie, the lowest player_id wins.

Write a solution to find the winner in each group.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
Players table:
+-----------+------------+
| player_id | group_id   |
+-----------+------------+
| 15        | 1          |
| 25        | 1          |
| 30        | 1          |
| 45        | 1          |
| 10        | 2          |
| 35        | 2          |
| 50        | 2          |
| 20        | 3          |
| 40        | 3          |
+-----------+------------+
Matches table:
+------------+--------------+---------------+-------------+--------------+
| match_id   | first_player | second_player | first_score | second_score |
+------------+--------------+---------------+-------------+--------------+
| 1          | 15           | 45            | 3           | 0            |
| 2          | 30           | 25            | 1           | 2            |
| 3          | 30           | 15            | 2           | 0            |
| 4          | 40           | 20            | 5           | 2            |
| 5          | 35           | 50            | 1           | 1            |
+------------+--------------+---------------+-------------+--------------+
Output: 
+-----------+------------+
| group_id  | player_id  |
+-----------+------------+ 
| 1         | 15         |
| 2         | 35         |
| 3         | 40         |
+-----------+------------+

Approach Overview

Problem Overview: Each player belongs to a tournament group and plays matches that produce scores. The task is to compute the total score for every player and return the winner of each group. If multiple players tie with the same score, the player with the smallest player_id wins the group.

Approach 1: Aggregate Scores + Join With Group Maximum (O(n log n) time, O(n) space)

Start by computing the total score per player. Each match contributes points to two players, so you normalize the data using UNION ALL to produce a single stream of (player_id, score). Then use GROUP BY player_id to sum scores. After computing totals, join this result with the Players table to associate each player with a group_id. For each group, compute the maximum total score and filter players that match it. Finally, resolve ties using MIN(player_id). This approach relies on standard SQL aggregation and joins, making it portable across most SQL engines.

Approach 2: Aggregation + Window Ranking (O(n log n) time, O(n) space)

A cleaner solution uses window functions. First compute each player's total score using the same normalized match table and GROUP BY. Join the aggregated scores with the Players table to attach group information. Then apply RANK() or ROW_NUMBER() over PARTITION BY group_id ORDER BY total_score DESC, player_id ASC. This ranking guarantees the highest score appears first while automatically resolving ties by the smallest player ID. Selecting rows where rank equals 1 directly returns the winner of each group. This pattern is common in analytical SQL problems and keeps the query compact and easy to maintain.

Both approaches depend heavily on GROUP BY aggregation to compute total scores. The window function variant is typically preferred because it avoids nested joins and expresses the ranking logic directly in SQL.

Recommended for interviews: The aggregation + window ranking approach. Interviewers expect you to normalize match results, compute player totals, and then rank players inside each group. Demonstrating the aggregation logic shows understanding of relational data, while using window functions shows strong SQL proficiency.

Solution

Code

MySQL

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Aggregate Scores + Join With Group MaximumO(n log n)O(n)Works in SQL systems without window functions or when sticking to basic aggregation and joins
Aggregation + Window RankingO(n log n)O(n)Best for modern SQL engines like MySQL/PostgreSQL where window functions simplify ranking logic

Video Solution

Leetcode HARD 1194 - Tournament Winners MULTI-COLUMN JOIN TRICK - Explained by Everyday Data Science • Everyday Data Science • 1,248 views views

Frequently Asked Questions

Is Tournament Winners easy or hard?
Tournament Winners is generally considered a hard SQL problem because it combines multiple concepts: normalizing match results, aggregating player scores, grouping by tournament group, and resolving ties correctly using ranking or ordered comparisons.
Tournament Winners Python/Java solution
This problem is categorized as a database challenge, so the expected solution is written in SQL (commonly MySQL). Instead of procedural code in Python or Java, the logic is implemented using SELECT queries, GROUP BY aggregation, joins, and window functions.
How to solve Tournament Winners in O(n)?
A near O(n) approach aggregates scores per player using GROUP BY after normalizing match results with UNION ALL. However, determining the top player per group usually requires sorting or ranking, which pushes practical complexity closer to O(n log n). Window functions like ROW_NUMBER() provide the cleanest implementation.
What is the best approach for Tournament Winners?
The most efficient approach aggregates total scores per player and then ranks players inside each group using a SQL window function such as ROW_NUMBER() or RANK(). Partition by group_id and order by total_score descending and player_id ascending to resolve ties. The row with rank 1 represents the group winner.
Is Tournament Winners asked at Google/Amazon/Meta?
SQL aggregation and ranking problems similar to Tournament Winners appear in database interviews at companies like Amazon, Google, and Meta. Candidates are often expected to combine GROUP BY, joins, and window functions to compute top performers within groups.
What data structure is used in Tournament Winners?
In SQL terms, the solution relies on relational tables combined with aggregation operations. GROUP BY creates per-player aggregates, and window functions such as ROW_NUMBER or RANK simulate ranking structures over partitions of rows.
What is the time complexity of Tournament Winners?
The query primarily performs aggregation and sorting for ranking. Aggregation over all match rows is O(n), while the ranking step introduces sorting that results in roughly O(n log n) time depending on the SQL engine's execution plan. Space usage is O(n) for intermediate aggregated results.

Ready to solve this problem?

Practice Tournament Winners with our built-in code editor and test cases.

Practice on FleetCode