DEV HARBOUR

Home / Resources

Solve Two Sum with a hash map

A worked JavaScript example, loop invariant, complexity analysis, and edge-case tests.

Given an array of numbers and a target, return the indices of two distinct entries whose sum equals the target. This exercise teaches a useful habit: identify the information you need from earlier iterations before choosing a data structure.

Start with a small example

For [3, 2, 4] and target 6, the answer is [1, 2]. Return indices rather than the values 2 and 4. A nested loop can compare every pair, but it repeats work: with n numbers there are n(n−1)/2 possible pairs.

Store the complement's location

When the current value is 4, you need to know whether 2 appeared earlier. A map from value to index answers that question. Check the map before inserting the current entry so that one index cannot be used twice.

function twoSum(nums, target) {
  const seen = new Map();
  for (let i = 0; i < nums.length; i++) {
    const needed = target - nums[i];
    if (seen.has(needed)) return [seen.get(needed), i];
    seen.set(nums[i], i);
  }
  return null;
}

After index 0, the map contains 3 → 0. At index 1, the needed value is 4, which is absent, so store 2 → 1. At index 2, the needed value is 2; return [1, 2]. The loop invariant is that the map contains only values from indices strictly before the current index.

Check the tricky inputs

Complexity and limits

With typical constant-time map operations, the expected running time is O(n) and additional storage is O(n). For currency, use integer minor units rather than comparing floating-point sums. If multiple pairs exist, this implementation returns the first pair found in scan order; it does not enumerate every answer.

Try it yourself

Write assertions for all four inputs above, then change the function to return whether a pair exists. Explain why sorting would require retaining the original indices. Use DSA Practice to experiment; the browser runner checks samples, while official server grading is currently unavailable.

Reference: MDN: Map. The walkthrough and exercises above are written for Dev Harbour.

Dev Harbour · Updated November 24, 2026 · Report a correction