Find Symmetric Pairs

Medium SQLJOIN

Problem

Schema: Friend(a INT, b INT). Each row says "a is friends with b". Return all symmetric pairs — pairs (a, b) where (b, a) also exists, with a < b to avoid duplicates.

Example 1 Input: (1,2) (2,1) (3,4) Output: (1, 2)

Constraints

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

SQL

SELECT f1.a, f1.b
FROM Friend f1
JOIN Friend f2 ON f2.a = f1.b AND f2.b = f1.a
WHERE f1.a < f1.b;

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Find Symmetric Pairs interactively → ← All solutions