Tournament Winners — LeetCode 1194 Python Solution
HardLeetCode PremiumDatabase
- Problem
- #1194
- Reading time
- 7 min
- Source
- leetcode.com
Table schema
SQL
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.Example
SQL
+-------------+-------+
| 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.Python solution
Python
import duckdb
import pandas as pd
def solution(players: pd.DataFrame, matches: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Players", players)
con.register("Matches", matches)
return con.execute("""WITH
s AS (
SELECT first_player AS player_id, first_score AS score, group_id
FROM
Matches AS m
JOIN Players AS p ON m.first_player = p.player_id
UNION ALL
SELECT second_player AS player_id, second_score AS score, group_id
FROM
Matches AS m
JOIN Players AS p ON m.second_player = p.player_id
),
t AS (
SELECT group_id, player_id, SUM(score) AS scores
FROM s
GROUP BY player_id
),
p AS (
SELECT
group_id,
player_id,
RANK() OVER (
PARTITION BY group_id
ORDER BY scores DESC, player_id
) AS rk
FROM t
)
SELECT group_id, player_id
FROM p
WHERE rk = 1;""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1194. Tournament Winners?
- LeetCode 1194. Tournament Winners is rated Hard on LeetCode.
- What topics does LeetCode 1194. Tournament Winners cover?
- LeetCode 1194. Tournament Winners is tagged Database on LeetCode.
- Is LeetCode 1194. Tournament Winners a premium problem?
- Yes. LeetCode 1194. Tournament Winners is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.