Two Sum — return indices of two numbers that add up to a target
cs-jun-006
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Model answer
I use a Dictionary<int, int> mapping each value to its index. For each element, I compute the complement (target minus the element) and check if it is already in the dictionary. If yes, the two indices are the stored index and the current index — return immediately. If not, store the current value and index. This is O(n) time and O(n) space. The brute-force nested loop is O(n²) and fails at scale.
Code example
public int[] TwoSum(int[] nums, int target)
{
var seen = new Dictionary<int, int>(); // value -> index
for (int i = 0; i < nums.Length; i++)
{
int complement = target - nums[i];
if (seen.TryGetValue(complement, out int j))
return new[] { j, i };
seen[nums[i]] = i;
}
throw new ArgumentException("No solution");
}
// Test
var result = TwoSum(new[] { 2, 7, 11, 15 }, 9);
Console.WriteLine($"[{result[0]}, {result[1]}]"); // [0, 1]
Follow-up
How would you modify the solution if the array is sorted and you can only use O(1) extra space? (Two-pointer approach.)