intermediate
Review: two-sum that pairs an element with itself
This is recall. The code looks finished and is wrong. Find the defect and fix it. You are graded on tests you cannot see.
Two-sum is the most-assigned interview question in existence, so a model wrote it for the umpteenth time and shipped it with a green test suite. It returns correct pairs for every input — except when the two numbers that sum to the target are the same value at two different positions. Then it returns one position twice, and the caller's arithmetic quietly goes wrong.
/**
* Returns the indices of the two distinct entries that sum to `target`, or
* null when no such pair exists.
*/
export function twoSum(nums: number[], target: number): [number, number] | null {
const seen = new Map<number, number>()
for (let i = 0; i < nums.length; i++) {
const need = target - (nums[i] as number)
seen.set(nums[i] as number, i)
if (seen.has(need)) {
return [seen.get(need) as number, i]
}
}
return null
}review — find the defectCtrl+↵ submits · Ctrl+Shift+↵ runsstarter code