Problem
Table: Teams
|
|
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:
|
|
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
Teams
table, aliasing it ast1
(home team) andt2
(away team). - In the join condition, ensure that
t1.team_name
is not equal tot2.team_name
to avoid pairing a team with itself. - Select
t1.team_name
ashome_team
andt2.team_name
asaway_team
. - This will generate all possible matches, with each pair appearing twice (once for each home/away configuration).
Code
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
, wheren
is 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.