Problem
Table: Coordinates
+-------------+------+
| Column Name | Type |
+-------------+------+
| X | int |
| Y | int |
+-------------+------+
Each row includes X and Y, where both are integers. Table may contain duplicate values.
Two coordindates (X1, Y1)
and (X2, Y2)
are said to be symmetric coordintes if X1 == Y2
and X2 == Y1
.
Write a solution that outputs, among all these symmetric coordintes , only those unique coordinates that satisfy the condition X1 <= Y1
.
Return the result table ordered byX
and Y
(respectively) inascending order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Approach
We join the table with itself to find symmetric pairs (X1, Y1)
and (X2, Y2)
such that X1 = Y2
and X2 = Y1
. We only keep unique pairs where X1 <= Y1
and order the result as required.
Code
MySQL
|
|
Oracle
|
|
PostgreSQL
|
|
Explanation
We self-join the table to find symmetric pairs, filter for X <= Y
, and use DISTINCT
to ensure uniqueness. The result is ordered as required.
Complexity
- ⏰ Time complexity:
O(N^2)
in the worst case due to the self-join, where N is the number of rows. - 🧺 Space complexity:
O(N)
for storing the result set.