All the Matches of the League
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Table: Teams
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| team_name | varchar |
+-------------+---------+
team_name is the column with unique values of this table.
Each row of this table shows the name of a team.
Write a solution to report all the possible matches of the league. Note that every two teams play two matches with each other, with one team being the home_team once and the other time being the away_team.
Return the result table in any order.
The result format is in the following example.
Examples
Example 1:
Input:
Teams table:
+-------------+
| team_name |
+-------------+
| Leetcode FC |
| Ahly SC |
| Real Madrid |
+-------------+
Output:
+-------------+-------------+
| home_team | away_team |
+-------------+-------------+
| Real Madrid | Leetcode FC |
| Real Madrid | Ahly SC |
| Leetcode FC | Real Madrid |
| Leetcode FC | Ahly SC |
| Ahly SC | Real Madrid |
| Ahly SC | Leetcode FC |
+-------------+-------------+
Explanation: All the matches of the league are shown in the table.
Solution
Method 1 – Using Self Join
Intuition
The key idea is to generate all possible pairs of teams where the home and away teams are different. By joining the Teams table with itself, we can pair each team with every other team, ensuring both home and away matches are covered.
Approach
- Perform a self join on the
Teamstable, aliasing it ast1(home team) andt2(away team). - In the join condition, ensure that
t1.team_nameis not equal tot2.team_nameto avoid pairing a team with itself. - Select
t1.team_nameashome_teamandt2.team_nameasaway_team. - This will generate all possible matches, with each pair appearing twice (once for each home/away configuration).
Code
MySQL
SELECT
t1.team_name AS home_team,
t2.team_name AS away_team
FROM
Teams t1
JOIN
Teams t2
ON
t1.team_name <> t2.team_name;
Complexity
- ⏰ Time complexity:
O(n^2), wherenis the number of teams (since each team is paired with every other team). - 🧺 Space complexity:
O(1)(excluding output), as the query does not use extra space beyond the result set.