Two Sum

Difficulty: Easy

Given a list of numbers and a target, find two different numbers that add up to the target and return their indexes.

There is always exactly one valid pair, and you can't use the same element twice.

Examples

Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]

nums[0] + nums[1] = 2 + 7 = 9.

Input: nums = [3, 2, 4], target = 6
Output: [1, 2]

nums[1] + nums[2] = 2 + 4 = 6.

Input: nums = [3, 3], target = 6
Output: [0, 1]

Constraints

  • 2 <= nums.length <= 10^4

  • -10^9 <= nums[i], target <= 10^9

  • Exactly one valid answer exists.

Approach

The direct way checks every pair to see if it adds up to the target. That works, but repeats a lot of work.

A faster way walks the list once. For each number, ask "what number would complete the target with this one?" If you've already seen it, you're done. A hash table answers "have I seen this value?" instantly, so one pass is enough.

Solutions

Brute Force - Check Every Pair

Try every pair and check if it adds up to the target. The most obvious solution, but it does far more work than needed as the list grows.

function twoSum(nums, target) {
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] + nums[j] === target) {
        return [i, j];
      }
    }
  }
  return [];
}

Time: O(n²) · Space: O(1)

Optimal - Hash Map

Walk the list once. For each number, check whether the value that completes the pair (target - currentNumber) was already seen. A Map checks this instantly and remembers each number's position.

function twoSum(nums, target) {
  const seen = new Map(); // value -> index

  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];
    if (seen.has(complement)) {
      return [seen.get(complement), i];
    }
    seen.set(nums[i], i);
  }

  return [];
}

Time: O(n) · Space: O(n)