Two Sum
Given an integer array and target, return the indexes of two different values whose sum equals the target.
Course progress
Problem 26 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [2, 7, 11, 15]; target = 9
Expected output
(0, 1)
What is happening?
At index 1, the value 7 needs a complement of 2. That value was seen at index 0, so the matching index pair is (0, 1).
Solution strategy
Build the right mental model
As each value is visited, look for its required complement among previously seen values. Store the current value only after checking it.
Core concepts
dictionary · lookup
Complexity
Average time O(n), space O(n).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for two-sum
using System;
using System.Collections.Generic;
class Program
{
static int[] TwoSum(int[] numbers, int target)
{
var seen = new Dictionary<int, int>();
for (int i = 0; i < numbers.Length; i++)
{
int complement = target - numbers[i];
int otherIndex;
if (seen.TryGetValue(complement, out otherIndex)) return new[] { otherIndex, i };
seen[numbers[i]] = i;
}
throw new ArgumentException("No pair adds to the target.");
}
static void Main()
{
int[] result = TwoSum(new[] { 2, 7, 11, 15 }, 9);
Console.WriteLine("(" + result[0] + ", " + result[1] + ")");
}
}Knowledge check
Questions students often ask
What is the main idea behind two sum?
As each value is visited, look for its required complement among previously seen values. Store the current value only after checking it.
What is the time and space complexity of this solution?
Average time O(n), space O(n).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.