...
/Solution Review: Find Two Pairs in an Array with an Equal Sum
Solution Review: Find Two Pairs in an Array with an Equal Sum
This lesson contains a detailed analysis that helps solve the "Find Two Pairs in an Array with an Equal Sum" challenge.
We'll cover the following...
Solution: Sums stored as hash keys
Press + to interact
using System;using System.Collections.Generic;namespace chapter_9{class challenge_5{static string findPair(int[] arr, int size){string result = "";// Create HashMap with Key being sum and value being a pair i.e key = 3 , value = {1,2}// Traverse all possible pairs in given arr and store sums in map// If sum already exist then print out the two pairs.Dictionary<int, int[]> hMap = new Dictionary<int, int[]>();int sum;int[] prev_pair = null;for (int i = 0; i < size; ++i){for (int j = i + 1; j < size; ++j){sum = arr[i] + arr[j]; //calculate sumif (!hMap.ContainsKey(sum)){// If the sum is not present in Map then insert it along with pairint[] temp_Arr = new int[2];temp_Arr[0] = arr[i];temp_Arr[1] = arr[j];hMap[sum] = temp_Arr;}else{//Sum already present in Mapprev_pair = hMap[sum];// Since array elements are distinct, we don't// need to check if any element is common among pairsresult += "{" + prev_pair[0].ToString() + "," + prev_pair[1].ToString() + "}{" + arr[i].ToString() + "," + arr[j].ToString() + "}";return result;}}}//end of forreturn result;}static void Main(string[] args){int[] arr = { 3, 4, 7, 1, 12, 9 };Console.WriteLine(findPair(arr, 6));}}}
On ...