Link copied to clipboard. Share away!

Dissmis

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.

- Input the array from the user.
- Use two loops.
- One loop for traversing the array and the other loop to check if symmetric pair is found in the array.
- 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)

- Input the array from the user.
- From all the array pairs, the first element is used as the
**key**and the second element is used as the**value**. - Traverse all the pairs one by one.
- 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.
- 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**

×