Find the two indices whose values add up to a target. The brute force checks every pair in O(n²); the elegant answer makes a single pass, using a hash map as memoryso each element can instantly ask "have I already seen my missing half?"
Given nums = [2,7,11,15] and target = 9, return the indices of the two numbers that sum to the target. Here nums[0] + nums[1] = 2 + 7 = 9, so the answer is [0, 1]. Exactly one valid pair is guaranteed, and you can't reuse the same index twice.
x, the only partner that works is target − x. Instead of scanning the rest of the array for it, keep a hash map of every value seen so far → its index and check that partner in O(1).That converts "search for the partner" (O(n) each, O(n²) total) into "look it up" (O(1) each, O(n) total). The map turns the array into instant memory.
need = target − nums[i].needis already a key in the map, you've found the pair: return [map.get(need), i].nums[i] → i into the map and move on.Sorting then walking two pointers inward is O(n log n) and O(1) extra space — but sorting scrambles the original indices, and this problem wants indices. You'd have to store (value, index) pairs and sort those. The hash map is cleaner here. (Two pointers shines on the sorted variant and on 3Sum.)
target − value.function twoSum(nums: number[], target: number): number[] {
// value -> the index where we last saw it
const seen = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i]; // the complement
if (seen.has(need)) {
return [seen.get(need)!, i]; // found the pair
}
seen.set(nums[i], i); // remember for later
}
return []; // problem guarantees we never reach here
}Map from value to index. We use a Map (not a plain object) so numeric keys stay numeric and lookups are clean O(1).target − nums[i]. We compute it once.i is the answer. Checking first guarantees the two indices are distinct.n elements, and every map operation (has/get/set) is amortized O(1). Total O(n) time, O(n) space for the map.[] or a sentinel. The classic version guarantees exactly one.| "find two that sum to target" | hash map of complements |
| "have I seen X before?" in one pass | Map / Set as memory |
| array is sorted + return values | two pointers inward |
| need original indices | store value → index |
const seen = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (seen.has(need)) return [seen.get(need)!, i];
seen.set(nums[i], i); // check THEN store
}target − nums[i] — the only value that can pair with it.nums[i], which value does the map look up?nums=[3,2,4], target=6, the answer is: