Original answer - O(n log n)
How about:
- Sort the array (or a copy). This is O(n log n)
- Iterate over the array, and for each value
x
do a binary search for x + no
- Each binary search is O(log n)
- Overall O(n log n)
Overall cost: O(n log n)
Modification to the above, as per Steve Jessop's comment:
FWIW, you don't have to do a binary search for x + no. As you iterate over the array, you can maintain a second iteration point in advance of the first one. Since the array is sorted, at each step x + no is greater than or equal to what x + no was in the previous step, so a linear search starting at the second iteration point from the previous step only ever goes forward and hence is O(n) total for the whole outer iteration, even though it isn't O(1) for each of the n steps.
This still requires a sort beforehand, which is O(n log n) though.
Best answer IMO (simple to implement and O(n))
EDIT: Or, of course, build a HashSet
to make the containment check even quicker (assuming that creating the set is amortized O(n) and lookups are O(1)):
HashSet<int> values = new HashSet<int>(array);
foreach (int value in array)
{
if (values.Contains(value + no))
{
// Found a match
}
}