Hacker Rank SQL

Symmetric Pairs Solution

Hello Friends in this article i am gone to share Hacker Rank SQL Solutions with you | Symmetric Pairs Solution


Also Visit:ย  Placements Solution


 

Problem

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

Column Type
X Integer
Y Integer

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

X Y
20 20
20 20
20 21
23 22
22 23
21 20

Sample Output

20 20
20 21
22 23

 

Solution โ€“ Symmetric Pairs

MySQL Code
SELECTย X,
ย ย ย ย ย ย ย Y
FROMย FUNCTIONSย F1
WHEREย EXISTS
ย ย ย ย (SELECTย *
ย ย ย ย ย FROMย FUNCTIONSย F2
ย ย ย ย ย WHEREย F2.Yย =ย F1.X
ย ย ย ย ย ย ย ANDย F2.Xย =ย F1.Y
ย ย ย ย ย ย ย ANDย F2.Xย >ย F1.X)
ย ย ANDย (Xย !=ย Y)
UNION
SELECTย X,
ย ย ย ย ย ย ย Y
FROMย FUNCTIONSย F1
WHEREย Xย =ย Y
ย ย ANDย (
ย ย ย ย ย ย ย ย ย (SELECTย COUNT(*)
ย ย ย ย ย ย ย ย ย ย FROMย FUNCTIONS
ย ย ย ย ย ย ย ย ย ย WHEREย Xย =ย F1.X
ย ย ย ย ย ย ย ย ย ย ย ย ANDย Yย =ย F1.X)ย >ย 1)
ORDERย BYย X;

 


What are symmetric pairs in Hackerrank?

Two pairs (a, b) and (c, d) are said to be symmetric if c is equal to b and a is equal to d. For example, (10, 20) and (20, 10) are symmetric. Given an array of pairs find all symmetric pairs in it

How do you find a symmetric pair?

For every pair, check if its second element is found in the hash table. If yes, then compare the first element with the value of the matched entry of the hash table. If the value and the first element match, it is displayed as a symmetric pair.

 

 

Disclaimer: The above Problems are generated by Hacker Rank but the Solutions are Provided by NYANDER.COM. All Hacker Rank SQL Solutions Shared only for Educational and Learning Purpose.