Arrays and Iteration
Two-Sum with Hash Lookup
Walk the array once, storing seen values in a lookup table. When the complement is already present, the result indices are known.
Algorithm
Basic Implementation
basic.js
const arr = [2, 7, 11, 4, 5];
const target = 9;
const seen = new Map();
let result = null;
for (let i = 0; i < arr.length; i++) {
const need = target - arr[i];
if (seen.has(need)) {
result = [seen.get(need), i];
break;
}
seen.set(arr[i], i);
}
console.log(`[${result[0]}, ${result[1]}]`);
Complexity
- Time: O(n) average
- Space: O(n)
Implementation notes
- JavaScript stores
arras aconstArrayofNumbervalues and uses a realMap, not a plain object, for the lookup table. - The index loop computes
const need = target - arr[i], checksseen.has(need), and on a hit buildsresult = [seen.get(need), i]before breaking. On a miss,seen.set(arr[i], i)records the current value as the key and the current index as the value. MapcomparesNumberkeys by SameValueZero semantics; for these finite integer values, complement lookup behaves like ordinary numeric equality. Insertion order is stable for replay display, though the algorithm looks up by key rather than iterating the map.- The replay shows one insertion,
{2: 0}, beforearr[1]finds complement2and returns[0, 1]. The finalconsole.loguses a template string to create and print[0, 1]; allocation is the input array, theMap, the two-element result array, and the output string, all handled by the JavaScript runtime GC.
execution replay
The checked-in replay follows the language-neutral state table for `array-two-sum-hash`.
cross-language comparison
This JavaScript DSA version keeps the same data and final output as every other DSA book in this wave.