Back to blog

March 30, 2026 · 4 min read

Two Sum with Hash Map: My Reliable O(n) Pattern

A practical walkthrough of how I use a hash map for Two Sum, including edge-case checks and why one-pass lookup is enough.

AlgorithmsData StructuresLeetCode

Complexity

Time: O(n)

Space: O(n)

Problem in My Words

Given a list of numbers and a target value, find two different indices whose values add up to the target.

Approach

Scan once and store seen numbers in a hash map. For each number, compute its complement. If complement exists in the map, return indices.

Key Points

  • Use one pass to avoid nested loops.
  • Map stores value to index for quick lookup.
  • Check complement before inserting current element.

Implementation

function twoSum(nums: number[], target: number): [number, number] {
  const seen = new Map<number, number>();

  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);
  }

  throw new Error("No valid pair found");
}