Remember earlier work so each lookup replaces another scan.
- Know this
- Use Set for membership and Map for counts or indices. Decide exactly what each key represents.
- Keep true
- Before processing index i, the map contains only earlier indices.
- Watch for
- Look up the complement before inserting the current value, or you can reuse the same index. Check undefined, not truthiness: index 0 is valid.
function twoSum(a: number[], target: number): number[] {
const seen = new Map<number, number>();
for (let i = 0; i < a.length; i++) {
const j = seen.get(target - a[i]!);
if (j !== undefined) return [j, i];
seen.set(a[i]!, i);
}
return [];
}TRACE ITtwoSum([2, 7, 11, 15], 9) → [0, 1]