Attempting to tackle the 2-Sum problem with a simple Javascript solution. The challenge involves finding pairs of integers in an array that add up to a specific target sum.
After reviewing several language-agnostic examples utilizing hash tables, I set out to create my own Javascript implementation:
// Integer set:
arr = [1,4,2,3,0,5];
// Target sum:
arg = 7;
// Generate hash table
hashTable = {};
arr.forEach(function(value, index){
hashTable[value] = index;
});
// hashTable = {
// 0: 4,
// 1: 0,
// 2: 2,
// 3: 3,
// 4: 1,
// 5: 5,
// }
for (var i = 0; i < arr.length; i++) {
if (hashTable[arg - arr[i]]) {
console.log([hashTable[arg - arr[i]], i])
}
}
Expecting the pairs 4,3 and 5,2 but getting 3,1 5,2 1,3 and 2,5. While trying to pinpoint the error by manually tracing through the logic, it is evident that something isn't aligned with the referenced language-agnostic solutions found online (here and here). Seeking assistance to identify and rectify the discrepancy.