Given an array and a target, find two numbers that add up to the target (return their indices or the pair).
Brute force checks every pair — O(n^2). The optimal one-pass approach keeps a hash map of value -> index; for each element x, check whether (target - x) has already been seen. O(n) time, O(n) space. Clarify whether indices or values are required and how duplicates are handled.
public static int[] twoSum(int[] a, int target) {
Map<Integer,Integer> seen = new HashMap<>();
for (int i = 0; i < a.length; i++) {
int need = target - a[i];
if (seen.containsKey(need)) return new int[]{seen.get(need), i};
seen.put(a[i], i);
}
return new int[]{-1, -1};
}function twoSum(a, target) {
const seen = new Map();
for (let i = 0; i < a.length; i++) {
const need = target - a[i];
if (seen.has(need)) return [seen.get(need), i];
seen.set(a[i], i);
}
return [-1, -1];
}def two_sum(a, target):
seen = {}
for i, x in enumerate(a):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
return [-1, -1]The complement trick — "have I already seen the value that completes this?" — reconciles debits/credits and matches request/response pairs.
A candidate gives the nested-loop O(n^2) solution. What is the key idea for O(n)?