I was asked in an interview to write a function for finding all pairs of ints in an array that add up to N. My answer was kinda bulky:
HashSet<Tuple<int,int>> PairsThatSumToN ( int [] arr, int N )
{
HashSet<int> arrhash = new HashShet<int> (arr);
HashSet<Tuple<int,int>> result = new HashSet<Tuple<int,int>>();
for ( int i in arrhash )
{
int j = N - i;
if ( arrhash.Contains(j) ) result.Add(new Tuple<int,int> (i,j));
}
return result;
}
I'm a beginner to C#, come from a C++ background, and I have a few questions about how to make this better:
Is it innefficient to iterate through a
HashSet
? In other words, would my procedure be more efficient (although less compact) if I changed it toHashSet<Tuple<int,int>> PairsThatSumToN ( int [] arr, int N ) { HashSet<int> arrhash = new HashShet<int> (); HashSet<Tuple<int,int>> result = new HashSet<Tuple<int,int>>(); for ( int i in arr ) { int j = N - i; if ( arrhash.Contains(j) ) result.Add(new Type<int,int> (i,j)); arrHash.Add(i); } return result; }
?????
I realize that
Add
is more like an "Add if not already in there", so I have a useless operation whenever I runresult.Add(new Tuple<int,int> (i,j))
for ani,j
pair that is already in the set. The more repeated pairs in the array, the more useless operations, and there's all the overhead of allocating the new Tuple that may never be used. Is there a way to optimize this by checking whether the pairi,j
is a Tuple in the set before creating a new Tuple out of said pair and trying to add it?Speaking of the above allocation of a
new Tuple
on the heap, do I need to free this memory if I don't end up adding that Tuple to the result? Potential memory leak here?There has to be some way of combining the two sets
HashSet<int> arrhash = new HashShet<int> (arr); HashSet<Tuple<int,int>> result = new HashSet<Tuple<int,int>>();
In a sense, they contain redundant information since every int in the second one is also in the first one. Something feels "wrong" about having to sets here, yet I can't think of a better way to do it.
Better yet, does the .NET library have any way of doing a 1-line solution for the problem? ;)
Paging Dr. Skeet.