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.
First, we can divide the problem into smaller parts. We want to compare all pairs and find the sy pairs. We can use a cross join to compare the pairs with the required conditions. However, there are two problems with this approach.
First, if we compare all pairs and get all sy pairs, the results may have duplicates. For example, the pair (20, 20) would appear twice in the results. We can use the distinct keyword to exclude the duplicates.
Second, if we have the pair (20, 20) only once in the dataset, it will still be included in the final results as a sy pair if we compare it with itself. We can solve this problem by not comparing the pair with itself. Another solution is to use the count function to count the number of times each pair appears in the results. If the count is 1, then the pair is not a sy pair.
WITH t AS
(SELECT *,
row_number() over(
ORDER BY X) AS roN
FROM functions)
SELECT DISTINCT t.X,
t.Y
FROM t
INNER JOIN t t1 ON t.X = t1.Y
AND t.Y = t1.X
AND t.X <= t.y
AND t.roN <> t1.roN
ORDER BY t.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 →
First, we can divide the problem into smaller parts. We want to compare all pairs and find the sy pairs. We can use a cross join to compare the pairs with the required conditions. However, there are two problems with this approach.
First, if we compare all pairs and get all sy pairs, the results may have duplicates. For example, the pair (20, 20) would appear twice in the results. We can use the distinct keyword to exclude the duplicates.
Second, if we have the pair (20, 20) only once in the dataset, it will still be included in the final results as a sy pair if we compare it with itself. We can solve this problem by not comparing the pair with itself. Another solution is to use the count function to count the number of times each pair appears in the results. If the count is 1, then the pair is not a sy pair.
WITH t AS (SELECT *, row_number() over( ORDER BY X) AS roN FROM functions) SELECT DISTINCT t.X, t.Y FROM t INNER JOIN t t1 ON t.X = t1.Y AND t.Y = t1.X AND t.X <= t.y AND t.roN <> t1.roN ORDER BY t.X