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.
We'll cover the following...
Solution 1: Using HashSet
Press + to interact
using System;using System.Collections.Generic;namespace chapter_9{class challenge_3{// Function to find symmetric pairsstatic string findSymmetric(int [,]arr, int size){// Create an empty hash tableHashSet<string> hash = new HashSet<string>(); ;string result = " ";// Traverse rows of given 2D arrayfor (int i = 0; i < size; i++){// Store values in current rowstring pair = "{" + (arr[i,0]).ToString() + ", " +arr[i,1].ToString() + "}";// Store values in current row in reverse orderstring reverse = "{" + arr[i,1].ToString() + ", " +arr[i,0].ToString() + "}";// Check if reverse pair of current pair is already present in the hash tableif (hash.Contains(reverse)){//Symmetric pair foundresult += reverse + pair ;}// Insert pair in hash tablehash.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 ...