Tournament Winners - Problem
Imagine you're organizing a multi-group tournament where players compete within their groups. Each player belongs to exactly one group, and matches are played only between players from the same group.
Your task: Determine the winner of each group based on total points scored across all matches.
You have two tables:
- Players: Contains
player_idand theirgroup_id - Matches: Contains match details with
first_player,second_player, and their respective scores
Winner Rules:
- The player with the highest total points in their group wins
- In case of a tie, the player with the lowest player_id wins
Return the winner of each group. The result can be in any order.
Input & Output
example_1.sql โ Basic Tournament
$
Input:
Players: [[1,2],[2,1],[3,1],[4,1],[5,2]]<br>Matches: [[1,3,4,5,2],[2,4,3,8,4],[3,1,5,6,3]]
โบ
Output:
[[1,3],[2,1]]
๐ก Note:
Group 1: Player 3 scored 8+4=12 points, Player 4 scored 2+8=10 points โ Player 3 wins
Group 2: Player 1 scored 6 points, Player 5 scored 3 points โ Player 1 wins
Group 2: Player 1 scored 6 points, Player 5 scored 3 points โ Player 1 wins
example_2.sql โ Tie Breaker
$
Input:
Players: [[1,1],[2,1],[3,2]]<br>Matches: [[1,1,2,10,10],[2,3,3,5,0]]
โบ
Output:
[[1,1],[2,3]]
๐ก Note:
Group 1: Both players scored 10 points, but Player 1 has lower ID โ Player 1 wins
Group 2: Player 3 scored 5 points โ Player 3 wins
Group 2: Player 3 scored 5 points โ Player 3 wins
example_3.sql โ Multiple Matches
$
Input:
Players: [[1,1],[2,1]]<br>Matches: [[1,1,2,8,12],[2,2,1,15,7],[3,1,2,6,9]]
โบ
Output:
[[1,2]]
๐ก Note:
Player 1: 8+7+6=21 points
Player 2: 12+15+9=36 points โ Player 2 wins Group 1
Player 2: 12+15+9=36 points โ Player 2 wins Group 1
Constraints
- 1 โค players.length โค 5 ร 104
- 1 โค matches.length โค 105
- 1 โค player_id โค 105
- 1 โค group_id โค 103
- 0 โค first_score, second_score โค 100
- All player_id values are unique
- Players in each match belong to the same group
Visualization
Tap to expand
Understanding the Visualization
1
Setup Phase
Create scorecards for all players and organize them by house/group
2
Match Processing
As each match completes, immediately update player scores and check for new house leaders
3
Champion Selection
Final champions emerge based on highest scores, with lowest ID breaking ties
4
Results
Each house has exactly one champion, determined efficiently in a single pass
Key Takeaway
๐ฏ Key Insight: Process matches once while maintaining group leaders in hash maps, avoiding the need for multiple passes through the data
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code