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 arr as a const Array of Number values and uses a real Map, not a plain object, for the lookup table.
  • The index loop computes const need = target - arr[i], checks seen.has(need), and on a hit builds result = [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.
  • Map compares Number keys 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}, before arr[1] finds complement 2 and returns [0, 1]. The final console.log uses a template string to create and print [0, 1]; allocation is the input array, the Map, 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.