Explore
ProGrad Programs
About Us

Edit
Reply




Edit

Program to find all symmetric pairs in an array | FACE Prep

Published on 09 Mar 2020

Program to find all symmetric pairs in an array is discussed here. Two pairs (p,q) and (r,s) are said to be symmetric when q is equal to r and p is equal to s. For example, (5,10) and (10,5) are symmetric pairs.


For example,

Consider a 2D array,


Input:


arr [6] [2] = {{1, 2}, {3, 4}, {5, 6}, {2, 1}, {4, 3},{10,11}}


Output:


{1,2} and {2,1} are symmetric

{3,4} abd {4,3} are symmetric


This problem can be solved in two different ways.


Method 1: Using two loops, one loop to traverse the pairs and the other loop to check if similar pair is existing.


Method 2: An efficient way to solve this problem is to use hashing. Insert each array pairs into the hash table with the first element of the pair as the key and the second element as the value. Traverse the hash table to check if the pairs are found again.


Algorithm to find all symmetric pairs in an array


  1. Input the array from the user.
  2. Use two loops.
  3. One loop for traversing the array and the other loop to check if symmetric pair is found in the array.
  4. If symmetric pair is found, print the pairs.


Program to find all symmetric pairs in an array is given below.


C
C++
Java
Python 3

Output
Input - 6 2 1 2 3 4 5 6 2 1 4 3 10 11 Output - (3,4) (4,3)


Time complexity: O(n^2)


Algorithm to find symmetric pairs in an array using hashing


  1. Input the array from the user.
  2. From all the array pairs, the first element is used as the key and the second element is used as the value.
  3. Traverse all the pairs one by one.
  4. For every pair, check if its second element is found in the hash table.
  5. If yes, then compare the first element with the value of the matched entry of the hash table.
  6. If the value and the first element match, it is displayed as a symmetric pair.
  7. Else, insert the first element as the key and second element as value and repeat the same.


Program to find all symmetric pairs in an array using hashing is given below.


C++
Java

Output
Output - Symmentric pairs : (1,2) (3,4)


Time complexity: O(n)


Recommended Programs






If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in
Explore 'c'
Articles