Skip to main content

Premier League Table Ranking - Solution & Explanation

EasyPremiumFree on FleetCodeDatabase5 min read
Practice this problem

Problem Statement

Table: TeamStats

+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| team_id          | int     |
| team_name        | varchar |
| matches_played   | int     |
| wins             | int     |
| draws            | int     |
| losses           | int     |
+------------------+---------+
team_id is the unique key for this table.
This table contains team id, team name, matches_played, wins, draws, and losses.

Write a solution to calculate the points and rank for each team in the league. Points are calculated as follows:

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

Note: Teams with the same points must be assigned the same rank.

Return the result table ordered by points in descending, and then by team_name in ascending order.

The query result format is in the following example.

 

Example:

Input:

TeamStats table:

+---------+-----------------+----------------+------+-------+--------+
| team_id | team_name       | matches_played | wins | draws | losses |
+---------+-----------------+----------------+------+-------+--------+
| 1       | Manchester City | 10             | 6    | 2     | 2      |
| 2       | Liverpool       | 10             | 6    | 2     | 2      |
| 3       | Chelsea         | 10             | 5    | 3     | 2      |
| 4       | Arsenal         | 10             | 4    | 4     | 2      |
| 5       | Tottenham       | 10             | 3    | 5     | 2      |
+---------+-----------------+----------------+------+-------+--------+

Output:

+---------+-----------------+--------+----------+
| team_id | team_name       | points | position |
+---------+-----------------+--------+----------+
| 2       | Liverpool       | 20     | 1        |
| 1       | Manchester City | 20     | 1        |
| 3       | Chelsea         | 18     | 3        |
| 4       | Arsenal         | 16     | 4        |
| 5       | Tottenham       | 14     | 5        |
+---------+-----------------+--------+----------+

Explanation:

  • Manchester City and Liverpool both have 20 points (6 wins * 3 points + 2 draws * 1 point), so they share position 1.
  • Chelsea has 18 points (5 wins * 3 points + 3 draws * 1 point) and is position 3rd.
  • Arsenal has 16 points (4 wins * 3 points + 4 draws * 1 point) and is position 4th.
  • Tottenham has 14 points (3 wins * 3 points + 5 draws * 1 point) and is position 5th.

The output table is ordered by points in descending order, then by team_name in ascending order.

Approach Overview

Problem Overview: You are given match or standings data for Premier League teams and need to produce the final league table ranking. Teams must be ordered by competition rules (typically points first, then tie‑breakers such as goal difference or goals scored) and assigned a ranking position.

Approach 1: Window Function Ranking (SQL) (Time: O(n log n), Space: O(n))

The most direct solution uses a SQL window function such as RANK() or DENSE_RANK(). First sort teams by the required ordering criteria (for example points DESC, goal_difference DESC, goals_scored DESC). The window function then assigns a rank based on this ordering. Internally the database performs a sort before computing the window frame, giving roughly O(n log n) time complexity with O(n) space for intermediate results. This approach is concise and idiomatic for relational queries, which is why it appears frequently in database interview questions.

The key insight is that ranking logic should not be implemented with manual joins or self comparisons. A window function already provides row ordering and rank assignment in a single pass after sorting. For example:

RANK() OVER (ORDER BY points DESC, goal_diff DESC)

This computes the league position exactly as a scoreboard would. If multiple teams share the same statistics, RANK() gives them the same position while skipping the next rank number. When sequential ranks are required, DENSE_RANK() is the better option.

Approach 2: Pandas DataFrame Ranking (Time: O(n log n), Space: O(n))

In the Pandas version, the idea is identical but implemented with DataFrame operations. First call sort_values() on the ranking columns (points, goal difference, etc.). After sorting, assign the league position using rank() or by resetting the index. Sorting dominates the runtime, resulting in O(n log n) time complexity and O(n) extra memory for the reordered DataFrame.

Pandas is useful when the dataset originates from analytics pipelines rather than a relational database. You manipulate the table in memory and compute rankings with vectorized operations. The conceptual mapping between SQL window functions and Pandas ranking functions is almost one‑to‑one, making it easy to switch between environments.

Both approaches rely on the same core idea: order the table correctly, then assign a rank based on that order. This pattern appears frequently in analytics queries involving leaderboards, competition standings, or scoreboards. Understanding window functions such as RANK(), DENSE_RANK(), and ROW_NUMBER() is essential for solving ranking problems in SQL and advanced window function queries.

Recommended for interviews: The window function approach is what interviewers expect. It shows you understand modern SQL features and can avoid inefficient self‑joins or nested queries. Explaining how sorting defines ranking and why RANK() vs DENSE_RANK() matters demonstrates deeper database query knowledge.

Solution

We can use the RANK() window function to calculate the ranking of the teams, and then sort by score and team name.

Code

MySQL

Pandas

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
SQL Window Function (RANK / DENSE_RANK)O(n log n)O(n)Standard relational database queries where ranking must follow ordered columns
Pandas DataFrame RankingO(n log n)O(n)Data analysis workflows using Python where the standings table is processed in memory

Video Solution

Leetcode 3246 - Premier League Ranking ORDER RANK() WINDOW - Explained by Everyday Data ScienceEveryday Data Science596 views views

Frequently Asked Questions

Is Premier League Table Ranking easy or hard?
Premier League Table Ranking is considered an easy database problem. The challenge mainly tests familiarity with SQL window functions and ordering rules rather than complex algorithms or data structures.
Premier League Table Ranking Python/Java solution
In SQL environments like MySQL, use RANK() OVER (ORDER BY ...) to assign positions. In Python with Pandas, sort the DataFrame using sort_values() and compute rankings using the rank() method or by resetting the index after sorting.
How to solve Premier League Table Ranking in O(n)?
A strict O(n) solution is generally not possible because the table must be ordered by ranking rules such as points and goal difference. Sorting requires O(n log n) time in relational databases. Once sorted, computing the rank itself is linear.
What is the best approach for Premier League Table Ranking?
The best approach uses a SQL window function such as RANK() or DENSE_RANK() with an ORDER BY clause on the ranking criteria (points, goal difference, etc.). The database sorts the rows and assigns positions automatically. This method is concise, efficient, and commonly expected in database interviews.
Is Premier League Table Ranking asked at Google/Amazon/Meta?
Database ranking queries appear frequently in interviews at large tech companies and data-focused roles. Variations involving window functions, leaderboards, and ranking metrics are common SQL interview problems across companies such as Amazon and analytics-focused teams.
What data structure is used in Premier League Table Ranking?
The problem operates on tabular data stored in a relational table or DataFrame. The main concept is a window function over an ordered dataset rather than a traditional data structure like a hash map or tree.
What is the time complexity of Premier League Table Ranking?
The dominant operation is sorting the teams by ranking criteria, which takes O(n log n) time. After sorting, the window function assigns ranks in a single pass. Space complexity is typically O(n) for intermediate query results.

Ready to solve this problem?

Practice Premier League Table Ranking with our built-in code editor and test cases.

Practice on FleetCode