Talentd
FleetCode
Make and follow sheets.Sign in

Premier League Table Ranking III solution and explanation

MediumDatabase7 min read70.6% acceptanceUpdated 24 Mar 2026Premium elsewhere, free here
Leetcode MEDIUM 3322 - Premier League Table Ranking III - RANKING in SQL | Everyday Data ScienceEveryday Data Science · 6:47 · 508 viewsWatch on YouTube

The problem

Table: SeasonStats

+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| season_id        | int     |
| team_id          | int     |
| team_name        | varchar |
| matches_played   | int     |
| wins             | int     |
| draws            | int     |
| losses           | int     |
| goals_for        | int     |
| goals_against    | int     |
+------------------+---------+
(season_id, team_id) is the unique key for this table.
This table contains season id, team id, team name, matches played, wins, draws, losses, goals scored (goals_for), and goals conceded (goals_against) for each team in each season.

Write a solution to calculate the points, goal difference, and position for each team in each season. The position ranking should be determined as follows:

  • Teams are first ranked by their total points (highest to lowest)
  • If points are tied, teams are then ranked by their goal difference (highest to lowest)
  • If goal difference is also tied, teams are then ranked alphabetically by team name

Points are calculated as follows:

  • 3 points for a win
  • 1 point for a draw
  • 0 points for a loss

Goal difference is calculated as: goals_for - goals_against

Return the result table ordered by season_id in ascending order, then by position in ascending order, and finally by team_name in ascending order.

The query result format is in the following example.

Example:

Input:

SeasonStats table:

+------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+
| season_id  | team_id | team_name         | matches_played | wins | draws | losses | goals_for | goals_against |
+------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+
| 2021       | 1       | Manchester City   | 38             | 29   | 6     | 3      | 99        | 26            |
| 2021       | 2       | Liverpool         | 38             | 28   | 8     | 2      | 94        | 26            |
| 2021       | 3       | Chelsea           | 38             | 21   | 11    | 6      | 76        | 33            |
| 2021       | 4       | Tottenham         | 38             | 22   | 5     | 11     | 69        | 40            |
| 2021       | 5       | Arsenal           | 38             | 22   | 3     | 13     | 61        | 48            |
| 2022       | 1       | Manchester City   | 38             | 28   | 5     | 5      | 94        | 33            |
| 2022       | 2       | Arsenal           | 38             | 26   | 6     | 6      | 88        | 43            |
| 2022       | 3       | Manchester United | 38             | 23   | 6     | 9      | 58        | 43            |
| 2022       | 4       | Newcastle         | 38             | 19   | 14    | 5      | 68        | 33            |
| 2022       | 5       | Liverpool         | 38             | 19   | 10    | 9      | 75        | 47            |
+------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+

Output:

+------------+---------+-------------------+--------+-----------------+----------+
| season_id  | team_id | team_name         | points | goal_difference | position |
+------------+---------+-------------------+--------+-----------------+----------+
| 2021       | 1       | Manchester City   | 93     | 73              | 1        |
| 2021       | 2       | Liverpool         | 92     | 68              | 2        |
| 2021       | 3       | Chelsea           | 74     | 43              | 3        |
| 2021       | 4       | Tottenham         | 71     | 29              | 4        |
| 2021       | 5       | Arsenal           | 69     | 13              | 5        |
| 2022       | 1       | Manchester City   | 89     | 61              | 1        |
| 2022       | 2       | Arsenal           | 84     | 45              | 2        |
| 2022       | 3       | Manchester United | 75     | 15              | 3        |
| 2022       | 4       | Newcastle         | 71     | 35              | 4        |
| 2022       | 5       | Liverpool         | 67     | 28              | 5        | 
+------------+---------+-------------------+--------+-----------------+----------+

Explanation:

  • For the 2021 season:
    • Manchester City has 93 points (29 * 3 + 6 * 1) and a goal difference of 73 (99 - 26).
    • Liverpool has 92 points (28 * 3 + 8 * 1) and a goal difference of 68 (94 - 26).
    • Chelsea has 74 points (21 * 3 + 11 * 1) and a goal difference of 43 (76 - 33).
    • Tottenham has 71 points (22 * 3 + 5 * 1) and a goal difference of 29 (69 - 40).
    • Arsenal has 69 points (22 * 3 + 3 * 1) and a goal difference of 13 (61 - 48).
  • For the 2022 season:
    • Manchester City has 89 points (28 * 3 + 5 * 1) and a goal difference of 61 (94 - 33).
    • Arsenal has 84 points (26 * 3 + 6 * 1) and a goal difference of 45 (88 - 43).
    • Manchester United has 75 points (23 * 3 + 6 * 1) and a goal difference of 15 (58 - 43).
    • Newcastle has 71 points (19 * 3 + 14 * 1) and a goal difference of 35 (68 - 33).
    • Liverpool has 67 points (19 * 3 + 10 * 1) and a goal difference of 28 (75 - 47).
  • The teams are ranked first by points, then by goal difference, and finally by team name.
  • The output is ordered by season_id ascending, then by rank ascending, and finally by team_name ascending.

Approach overview

Problem Overview: You are given Premier League team statistics and need to produce the league table ranking. Teams must be ordered by their performance metrics (such as points and tie‑breakers) and assigned a rank following league table rules.

Approach 1: Window Function Ranking (O(n log n) time, O(n) space)

The most practical solution uses SQL window functions. First sort teams by the ranking criteria used in league tables, typically points DESC, then tie‑breakers such as goal_difference DESC and goals_scored DESC. After ordering the rows, apply a ranking function like RANK() or DENSE_RANK() using OVER (ORDER BY ...). The database engine performs the ordering and assigns ranks in a single pass over the sorted result set. Time complexity is O(n log n) due to sorting, and space complexity is O(n) for the intermediate ordered dataset.

This approach is ideal for relational datasets because ranking logic stays inside the query. Window functions are optimized by most SQL engines and avoid complicated self‑joins or subqueries. If you work with analytics queries or leaderboard problems, this pattern appears frequently. See related patterns in database queries and SQL window functions.

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

In a Pandas environment, replicate the same logic using DataFrame sorting followed by ranking. First call sort_values() on the ranking columns in descending order. Then use rank() with the appropriate method (such as dense or min) to generate league positions. Pandas internally sorts the rows and computes ranks across the ordered dataset. Time complexity remains O(n log n) because sorting dominates, and space complexity is O(n) for the DataFrame.

This version is useful when the dataset is already loaded into Python for analysis. It mirrors SQL logic closely, which makes it easy to translate between query solutions and data analysis workflows. More patterns like this appear in pandas data manipulation problems.

Recommended for interviews: The window function solution is the expected answer. Interviewers want to see that you know how to compute rankings using RANK() or DENSE_RANK() instead of manual comparisons or nested queries. Understanding how ordering and ranking interact shows strong SQL fundamentals.

Solution

We can use the window function RANK() to rank the teams by grouping them by season and sorting based on points, goal difference, and team name.

Finally, we just need to sort by season_id, position, and team_name.

SELECT
    season_id,
    team_id,
    team_name,
    wins * 3 + draws points,
    goals_for - goals_against goal_difference,
    RANK() OVER (
        PARTITION BY season_id
        ORDER BY wins * 3 + draws DESC, goals_for - goals_against DESC, team_name
    ) position
FROM SeasonStats
ORDER BY 1, 6, 3;
import pandas as pd


def process_team_standings(season_stats: pd.DataFrame) -> pd.DataFrame:
    season_stats["points"] = season_stats["wins"] * 3 + season_stats["draws"]
    season_stats["goal_difference"] = (
        season_stats["goals_for"] - season_stats["goals_against"]
    )

    season_stats = season_stats.sort_values(
        ["season_id", "points", "goal_difference", "team_name"],
        ascending=[True, False, False, True],
    )

    season_stats["position"] = season_stats.groupby("season_id").cumcount() + 1

    return season_stats[
        ["season_id", "team_id", "team_name", "points", "goal_difference", "position"]
    ]
Try this approach in the editor

Complexity analysis

ApproachTimeSpaceWhen to Use
SQL Window Function RankingO(n log n)O(n)Best choice for SQL interview questions and leaderboard-style ranking queries
Pandas Sort + RankO(n log n)O(n)When working with the dataset in Python for analytics or preprocessing

Frequently asked questions

Is Premier League Table Ranking III easy or hard?

The problem is typically rated Medium because it requires familiarity with SQL window functions. Developers comfortable with RANK(), DENSE_RANK(), and ORDER BY clauses usually solve it quickly, but it can be challenging if you have not worked with analytic SQL functions before.

Premier League Table Ranking III Python/Java solution

In SQL environments such as MySQL, use RANK() or DENSE_RANK() over an ORDER BY clause. In Python, load the data into a Pandas DataFrame, sort using sort_values(), and compute positions with rank(). Both approaches rely on sorting followed by ranking.

How to solve Premier League Table Ranking III in O(n)?

Achieving true O(n) is unlikely because ranking requires ordered results. Database engines generally perform a sort before applying RANK() or DENSE_RANK(), which leads to O(n log n) complexity. The optimal practical solution uses a window function after sorting by the ranking columns.

What is the best approach for Premier League Table Ranking III?

The standard solution uses SQL window functions such as RANK() or DENSE_RANK() with an ORDER BY clause on the ranking criteria (points and tie‑breakers). This approach lets the database compute the leaderboard directly after sorting the teams. Time complexity is O(n log n) because the rows must be ordered before ranking.

Is Premier League Table Ranking III asked at Google/Amazon/Meta?

Ranking and leaderboard problems using SQL window functions are common in data and analytics interviews at companies like Amazon, Google, and Meta. Variants often ask candidates to compute ranks, dense ranks, or top performers using SQL queries.

What data structure is used in Premier League Table Ranking III?

The problem primarily relies on relational table operations and SQL window functions. Internally, the database engine sorts rows and assigns ranks across the ordered partition. No explicit data structures are required beyond the table and the ordered result set.

What is the time complexity of Premier League Table Ranking III?

The dominant operation is sorting the teams by points and other tie‑breakers. Sorting requires O(n log n) time, while the ranking step using a window function runs in linear time over the sorted rows. Space complexity is typically O(n) for the result set.

Comments

Now write it yourselfClose this page and solve Premier League Table Ranking III in the editor, without looking.
Practise Premier League Table Ranking III