Two Sum

Easy

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

Examples

InputOutput
nums = [2, 7, 11, 15], target = 9[0, 1]
nums = [3, 2, 4], target = 6[1, 2]

Python Solution

def two_sum(nums: list[int], target: int) -> list[int]:
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

JavaScript Solution

function twoSum(nums, target) {
  const seen = new Map();
  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 [];
}

Step-by-Step Explanation

  1. Use a hash map to store each number and its index as we iterate.
  2. For each number, compute the complement (target - num).
  3. If the complement exists in the map, we've found our pair—return both indices.
  4. Otherwise, add the current number and its index to the map.

Complexity Analysis

TimeO(n)
SpaceO(n)

Tags

ArrayHash Map

Related Problems

Related Tools

All Problems