← Daily Logs
LeetCode 1

Two Sum

EasyJun 25, 2026arrayhash map

Find the two indices whose values add up to a target. The naive double loop is O(n²); a hash map trades a little memory to do it in one pass.

The problem

Given an array of integers and a target, return the indices of the two numbers that add up to the target. Exactly one valid answer exists, and you can't use the same element twice.

The brute-force version is the first thing that comes to mind: for every number, scan the rest of the array looking for its complement. That's two nested loops and O(n²) time, which is fine for tiny inputs and slow the moment the array grows.

The approach

The insight is that for each number `x`, I'm looking for exactly one specific other number: `target - x`. So instead of searching for it, I can remember every number I've already seen and check in O(1) whether the complement is among them.

One pass: for each element, compute what I still need, and if I've seen it before, I'm done — return both indices. Otherwise record the current number and its index and move on. Because I check before I insert, I never accidentally pair an element with itself.

The solution

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

Time O(n)Space O(n)

All entries