We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Simple query
SELECT DISTINCT p1.x, p1.y
FROM Functions p1
JOIN Functions p2
ON p1.x = p2.y AND p1.y = p2.x
WHERE
p1.x < p1.y
OR p1.x IN (
SELECT x
FROM Functions
WHERE x = y
GROUP BY x
HAVING COUNT(*) > 1
)
ORDER BY p1.x;
With cte
WITH SymmetricPairs AS (
SELECT f1.x, f1.y
FROM Functions f1
JOIN Functions f2
ON f1.x = f2.y AND f1.y = f2.x
),
Filtered AS (
SELECT DISTINCT x, y
FROM SymmetricPairs
WHERE x < y
UNION
SELECT x, y
FROM Functions
WHERE x = y
GROUP BY x, y
HAVING COUNT(*) > 1
)
SELECT *
FROM Filtered
ORDER BY x;
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Symmetric Pairs
You are viewing a single comment's thread. Return to all comments →
Simple query SELECT DISTINCT p1.x, p1.y FROM Functions p1 JOIN Functions p2 ON p1.x = p2.y AND p1.y = p2.x WHERE p1.x < p1.y OR p1.x IN ( SELECT x FROM Functions WHERE x = y GROUP BY x HAVING COUNT(*) > 1 ) ORDER BY p1.x;
With cte
WITH SymmetricPairs AS ( SELECT f1.x, f1.y FROM Functions f1 JOIN Functions f2 ON f1.x = f2.y AND f1.y = f2.x ), Filtered AS ( SELECT DISTINCT x, y FROM SymmetricPairs WHERE x < y
UNION
SELECT x, y FROM Functions WHERE x = y GROUP BY x, y HAVING COUNT(*) > 1 )
SELECT * FROM Filtered ORDER BY x;