...

/

Solution Review: Find Symmetric Pairs in an Array

Solution Review: Find Symmetric Pairs in an Array

Learn a detailed analysis of the different ways to solve the "Find Symmetric Pairs in an Array" challenge.

Solution 1: Using HashSet

Press + to interact
using System;
using System.Collections.Generic;
namespace chapter_9
{
class challenge_3
{
// Function to find symmetric pairs
static string findSymmetric(int [,]arr, int size)
{
// Create an empty hash table
HashSet<string> hash = new HashSet<string>(); ;
string result = " ";
// Traverse rows of given 2D array
for (int i = 0; i < size; i++)
{
// Store values in current row
string pair = "{" + (arr[i,0]).ToString() + ", " +
arr[i,1].ToString() + "}";
// Store values in current row in reverse order
string reverse = "{" + arr[i,1].ToString() + ", " +
arr[i,0].ToString() + "}";
// Check if reverse pair of current pair is already present in the hash table
if (hash.Contains(reverse))
{
//Symmetric pair found
result += reverse + pair ;
}
// Insert pair in hash table
hash.Add(pair);
}
return result;
}
static void Main(string[] args)
{
int [,] arr = {{1,2},{3,4},{5,9},{4,3},{9,5}};
string symmetric = findSymmetric(arr, 5);
Console.WriteLine(symmetric);
return;
}
}
}

The solution above uses a C# HashSet. You will grab each pair from the given array and check if a mirror pair in the hash table exists. If true, you will ...