← Hash MapDSA 1.3.A
Complement Lookup
{value: index} map; check the complement before storing. Two Sum.
The canonical example is Two Sum on an unsorted array — no sorting, so the opposite-ends trick from the two-pointers pattern doesn't apply, and a hash map fills in instead.
int* twoSum(int *nums, int n, int target) {
HashMap seen = {0}; /* value -> index */
for (int i = 0; i < n; i++) {
int complement = target - nums[i];
if (seen.contains(complement)) {
return (int[]){ seen[complement], i };
}
seen[nums[i]] = i;
}
return NULL;
}The order matters: check for the complement before storing the current value, not after — otherwise a target that needs the same element twice would match against itself. First pass at this used range(len(nums) - 1), which quietly skips the last element; the fix is just range(len(nums)), since there's no reason the last element can't be the one that completes a pair.
Notes from readers
Comments — via GitHub