Symmetric Coordinates - Problem

You are given a table Coordinates containing pairs of integer coordinates.

Symmetric coordinates are defined as two coordinate pairs (X1, Y1) and (X2, Y2) where X1 == Y2 and X2 == Y1.

Write a SQL query to find all unique symmetric coordinate pairs that satisfy the condition X <= Y.

Requirements:

  • Return only coordinates where X <= Y to avoid duplicates
  • Order results by X ascending, then by Y ascending
  • Handle duplicate coordinate pairs in the input table

Table Schema

Coordinates
Column Name Type Description
X int X coordinate value
Y int Y coordinate value
Note: Table may contain duplicate coordinate pairs. No primary key defined.

Input & Output

Example 1 — Basic Symmetric Pairs
Input Table:
X Y
1 2
2 1
3 3
4 5
Output:
X Y
1 2
3 3
💡 Note:

(1,2) and (2,1) are symmetric because X1=Y2=1 and Y1=X2=2. We return (1,2) since 1≤2.

(3,3) is symmetric with itself since X=Y=3.

(4,5) has no symmetric partner in the table, so it's excluded.

Example 2 — Duplicates Handling
Input Table:
X Y
1 1
1 1
2 3
Output:
X Y
1 1
💡 Note:

The duplicate (1,1) entries are symmetric with themselves. DISTINCT ensures we return only one (1,1) result.

(2,3) has no symmetric partner (3,2) in the table, so it's excluded from results.

Example 3 — No Symmetric Pairs
Input Table:
X Y
1 5
2 4
3 7
Output:
X Y
💡 Note:

None of the coordinates have symmetric partners in the table:

• (1,5) would need (5,1) - not present

• (2,4) would need (4,2) - not present

• (3,7) would need (7,3) - not present

Result is empty.

Constraints

  • 1 ≤ coordinates count ≤ 1000
  • -1000 ≤ X, Y ≤ 1000
  • Table may contain duplicate coordinate pairs

Visualization

Tap to expand
Symmetric Coordinates INPUT X Y (1,2) (2,1) (3,4) (4,3) (5,5) Coordinates Table: X Y 1 2 2 1 3 4 4 3 5 5 ALGORITHM STEPS 1 Store in HashSet Add all (X,Y) pairs to set Set: {(1,2),(2,1),(3,4), (4,3),(5,5)} 2 Check Symmetric For (X,Y): lookup (Y,X) (1,2) --> find (2,1) OK (3,4) --> find (4,3) OK (5,5) --> find (5,5) OK 3 Filter: X <= Y Keep only unique pairs (1,2): 1<=2 OK | (3,4): 3<=4 OK (5,5): 5<=5 OK 4 Sort Results Order by X, then Y Sorted: (1,2), (3,4), (5,5) FINAL RESULT Symmetric Pairs Found: (1,2) <--> (2,1) (3,4) <--> (4,3) (5,5) Self-symmetric Output (X <= Y): (1, 2) (3, 4) (5, 5) Key Insight: Two coordinates (X1,Y1) and (X2,Y2) are symmetric when X1==Y2 AND X2==Y1. Using a HashSet allows O(1) lookup for the symmetric pair. Filter X<=Y to avoid duplicates (e.g., report (1,2) not (2,1)). Self-symmetric pairs like (5,5) satisfy X==Y naturally. TutorialsPoint - Symmetric Coordinates | Optimal Solution (HashSet O(n))
Asked in
Amazon 12 Microsoft 8 Google 6
23.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen