ror_coding

[HackerRank] Symmetric Pairs 본문

Coding Test/SQL

[HackerRank] Symmetric Pairs

ro_rdil_31 2025. 6. 14. 14:24
728x90

20 20이 self join하는 예외 케이스 나눠서 풀기 !

 

Question

You are given a table, Functions, containing two columns: X and Y.

Two pairs (X1, Y1) and (X2, Y2) are said to be symmetric pairs if X1 = Y2 and X2 = Y1.

Write a query to output all such symmetric pairs in ascending order by the value of X. List the rows such that X1 ≤ Y1.

Sample Input

Sample Output

20 20
20 21
22 23

 

Point

 

  • 20 20이 하나만 있을 때 서로 self join해서 20 20 20 20 이 되는 문제점 존재.
    • -> X,Y가 같을 때 케이스를 따로 group by - count를 이용해서 2개 이상일 때 출력.

 

Code

 

SELECT X, Y -- 20 20이 하나만 있을 때 SELF JOIN 되는 케이스 방지.
FROM FUNCTIONS
WHERE X = Y
GROUP BY X, Y
HAVING COUNT(*) >= 2

UNION

SELECT F1.X, F1.Y
FROM FUNCTIONS F1
JOIN FUNCTIONS F2 ON (F1.X = F2.Y) AND (F1.Y = F2.X)
WHERE F1.X < F1.Y

ORDER BY 1

 

now me

728x90

'Coding Test > SQL' 카테고리의 다른 글

[HackerRank] The Report  (0) 2025.06.14
[HackerRank] Type of Triangle  (0) 2025.06.14
[HackerRank] Binary Tree Nodes  (0) 2025.04.05
[HackerRank] Occupations  (0) 2025.04.05
[Programmers Lv.5] 멸종위기의 대장균 찾기 - 301651  (0) 2025.01.16