# C++ program to find all symmetric elements in an array

## Program to find all the symmetric elements in an array.

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.

It may be assumed that the first elements of all pairs are distinct.

Example:

Input: arr[] = {{11, 20}, {30, 40}, {5, 10}, {40, 30}, {10, 5}}

Output: Following pairs have symmetric pairs (30, 40) (5, 10) ## Algorithm:-

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.

## C++ Code:-

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void symmetric_pairs(int **arr,int n)
{
// Create an empty hashMap
map<int,int>mpp;
// Traverse through the array
for (int i = 0i < ni++)
{
// First element as key and second element as value for each pair
int first = arr[i];
int second = arr[i];

int val;
// Look for second element of this pair in hashtable
if(mpp.find(second)!=mpp.end())
val = mpp[second];
else
val=-1;

// If found and value in hash matches with first element of this pair, we found symmetry
if ( val == fir)
System.out.print(“(“ + sec + “, “ + fir + “)” + ” “);

else  // Else put second element of this pair in hash table
mpp[first]=second;
}
}

void main(String arg[])
{
cout<<“Enter number of pairs you want to insert”;
int n;
cin>>n;
int **arr=new int*[n];
for(int i=0;i<n;i++)
{
arr[i]=new int;
}
cout<<\nEnter elements of all pairs 1 by 1 :-“;
for(int i=0;i<n;i++)
{
cin>>a[i]>>a[i];
}
cout<<“Symmetric pairs : “;
find_symmetric_pairs(arr,n);
}

Output
Enter number of pairs you want to insert 5
Enter elements of all pairs 1 by 1 :-
1 2 3 4 5 6 2 1 4 3
Symmetric elements are
{1,2}
{3,4}