MediumNo. 1841LeetCode Premium
League Statistics — LeetCode 1841 Python Solution
- Topics
- Database
- Reading time
- 8 min
- Source
- leetcode.com
Table schema
Table: Teams +----------------+---------+ | Column Name | Type | +----------------+---------+ | team_id | int | | team_name | varchar | +----------------+---------+ team_id is the column with unique values for this table. Each row contains information about one team in the league.Example
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| team_id | int |
| team_name | varchar |
+----------------+---------+
team_id is the column with unique values for this table.
Each row contains information about one team in the league.Python solution
import duckdb
import pandas as pd
def solution(teams: pd.DataFrame, matches: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Teams", teams)
con.register("Matches", matches)
return con.execute("""WITH
Scores AS (
SELECT
home_team_id AS team_id,
CASE
WHEN home_team_goals > away_team_goals THEN 3
WHEN home_team_goals < away_team_goals THEN 0
ELSE 1
END AS score,
home_team_goals AS goals,
away_team_goals AS away_goals
FROM Matches
UNION ALL
SELECT
away_team_id AS team_id,
CASE
WHEN home_team_goals > away_team_goals THEN 0
WHEN home_team_goals < away_team_goals THEN 3
ELSE 1
END AS score,
away_team_goals AS goals,
home_team_goals AS away_goals
FROM Matches
)
SELECT
team_name,
COUNT(1) AS matches_played,
SUM(score) AS points,
SUM(goals) AS goal_for,
SUM(away_goals) AS goal_against,
(SUM(goals) - SUM(away_goals)) AS goal_diff
FROM
Scores AS s
JOIN Teams AS t ON s.team_id = t.team_id
GROUP BY s.team_id
ORDER BY points DESC, goal_diff DESC, team_name;""").df()Complexity
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0175 | Combine Two Tables | Easy |
| 0176 | Second Highest Salary | Medium |
| 0177 | Nth Highest Salary | Medium |
| 0178 | Rank Scores | Medium |
| 0180 | Consecutive Numbers | Medium |
| 0181 | Employees Earning More Than Their Managers | Easy |
Frequently asked questions
- How hard is LeetCode 1841. League Statistics?
LeetCode 1841. League Statistics is rated Medium on LeetCode.
- What topics does LeetCode 1841. League Statistics cover?
LeetCode 1841. League Statistics is tagged Database on LeetCode.
- Is LeetCode 1841. League Statistics a premium problem?
Yes. LeetCode 1841. League Statistics is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.