I\'m having a integer array of 10 Million elements, how to write a function in C# which returns True if the array has a pair which sums up to 75.
My code is:
This is a bucketing problem. You want buckets of 0s to pair with 75s, 1s to pair with 74s, etcetera. Bucketing is a Dictionary jobby. A Dictionary
gives you a result in O(n) amortized. If you only care about a bool result then a HashSet
is good enough. You can't get better than O(n).
static bool PairExists(int[] arr, int sum) {
var set = new HashSet();
foreach (int elem in arr) set.Add(elem);
foreach (int elem in set)
if (set.Contains(sum - elem)) return true;
return false;
}
If the array is likely to contain the pair then you could consider testing after the Add() call, still O(n).