Back to problems
#1Easy·hash-map·1 min read

Two Sum

arrayhash-table

Problem

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.

Intuition

The brute force approach checks every pair — O(n²). We can do better by trading space for time: as we iterate, store each number's index in a hash map. For each number, check if target - num already exists in the map.

Solution

function twoSum(nums: number[], target: number): number[] {
  const map = new Map<number, number>();
 
  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];
    if (map.has(complement)) {
      return [map.get(complement)!, i];
    }
    map.set(nums[i], i);
  }
 
  return [];
}

Complexity

  • Time: O(n) — single pass through the array
  • Space: O(n) — hash map stores at most n elements

Key Takeaway

When you need to find pairs that satisfy a condition, a hash map lets you look up complements in O(1) instead of scanning the rest of the array.