Two Sum with a Dictionary
csharpC# and .NETbeginnerinterview-prep
Find two numbers that add up to a target in O(n) by remembering each value's index and looking up the complement.
Console.WriteLine(string.Join(", ", TwoSum(new[] { 2, 7, 11, 15 }, 9))); // 0, 1
Console.WriteLine(TwoSum(new[] { 1, 2, 3 }, 10).Length); // 0
// One pass. For each value, check whether the number that completes the sum was seen earlier.
// O(n) time and O(n) space, instead of O(n squared) with two nested loops.
static int[] TwoSum(int[] numbers, int target)
{
var indexByValue = new Dictionary<int, int>();
for (int i = 0; i < numbers.Length; i++)
{
int complement = target - numbers[i];
if (indexByValue.TryGetValue(complement, out int j)) return new[] { j, i };
indexByValue[numbers[i]] = i;
}
return Array.Empty<int>();
}