← Back to JavaScript, page 6

javascript-0114 · Easy fresher

How do you solve two-sum in O(n) time, and what other problems use the same hashing idea?

Walk the array once and keep a Map from each value you have seen to its index. For each number, check whether target minus the number is already in the Map, and if so return both indexes. This turns an O(n squared) search into O(n) time with O(n) space, and the same idea finds duplicates, counts, and subarrays with a given sum.

Full answer

Two-sum asks for the indexes of two numbers in an array that add up to a target. The brute force version tries every pair, which is O(n squared). A hash lookup replaces the inner loop.

Algorithm: create an empty Map named seen. For each index i with value n, compute need = target - n. If seen has need, return [seen.get(need), i]. Otherwise store seen.set(n, i). Because you check before you store, an element is never paired with itself, and duplicates work: for [3, 3] with target 6, the second 3 finds the first. Time is O(n), space is O(n).

If the array is sorted, two pointers also work in O(1) space, but sorting an unsorted array first loses the original indexes.

Questions to ask: is there always exactly one answer, can the same element be used twice, are values negative or fractional, and what to return when there is no answer (usually null or an empty array).

The same idea, remembering what you have seen, solves many problems:

  • Contains duplicate: a Set and an early return.
  • First non-repeating character: count with a Map, then scan.
  • Subarray sum equals k: store prefix sums and how often each occurred.
  • Most frequent element: count in a Map.
  • Intersection of two arrays: put one in a Set and filter the other.

Choose Map and Set over plain objects for these, because keys of any type work and there are no inherited property surprises such as constructor. Note that Map keys use SameValueZero, so NaN matches NaN.

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

const hasDuplicate = (items) => new Set(items).size !== items.length;

function firstUniqueChar(text) {
  const counts = new Map();
  for (const ch of text) counts.set(ch, (counts.get(ch) ?? 0) + 1);
  for (const [index, ch] of [...text].entries()) if (counts.get(ch) === 1) return index;
  return -1;
}

function subarraySumCount(numbers, k) {
  const prefixCounts = new Map([[0, 1]]);
  let sum = 0;
  let count = 0;
  for (const n of numbers) {
    sum += n;
    count += prefixCounts.get(sum - k) ?? 0;
    prefixCounts.set(sum, (prefixCounts.get(sum) ?? 0) + 1);
  }
  return count;
}

const intersection = (a, b) => {
  const set = new Set(a);
  return [...new Set(b.filter((x) => set.has(x)))];
};

console.log(twoSum([2, 7, 11, 15], 9), twoSum([3, 2, 4], 6), twoSum([3, 3], 6), twoSum([1, 2], 10));
console.log(hasDuplicate([1, 2, 3, 1]), hasDuplicate([1, 2, 3]));
console.log(firstUniqueChar('leetcode'), firstUniqueChar('aabb'));
console.log(subarraySumCount([1, 1, 1], 2), subarraySumCount([1, 2, 3], 3), subarraySumCount([1, -1, 0], 0));
console.log(intersection([1, 2, 2, 1], [2, 2, 3]));

Run with Node.js v24.22.1 as js-114.js; two runs gave identical output. Output: [ 0, 1 ] [ 1, 2 ] [ 0, 1 ] null true false 0 -1 2 2 3 [ 2 ]

Key points

  • Check target minus current in a Map of seen values, then store the current value.
  • Check before storing so an element is not paired with itself; duplicates still work.
  • O(n) time and O(n) space, against O(n squared) for pairs.
  • Clarify uniqueness, reuse of elements, and the no-answer return value.
  • Same pattern: duplicates, counts, prefix sums, intersections; prefer Map and Set to plain objects.

Common mistakes

  • Storing the current value before checking, which pairs an element with itself.
  • Using a nested loop and accepting O(n squared) without mentioning the hash version.
  • Sorting first and losing the original indexes.
  • Using plain objects as hash maps and getting inherited keys such as constructor.

Follow-ups

  • How would you solve two-sum when the array is sorted and you want O(1) space?
  • How would you return all pairs and avoid duplicate pairs?
  • How does the prefix sum idea find subarrays that sum to k?

Tips

  • Describe the brute force, then the hash version, then the cost trade-off.
  • Say check-then-store and why it matters.
  • Mention that Map and Set work for any key type.