Algorithm

Two Sum Algorithm

You have a list of numbers and a target. Find two numbers that add up to the target. Return their indices.

10 Mar 2024

Two Sum Algorithm

You have a list of numbers and a target. Find two numbers that add up to the target. Return their indices.

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

This is LeetCode problem #1 for a reason. It teaches the most important optimization pattern in algorithms: trading space for time.

The brute force way

Check every pair. Two nested loops. Simple and slow.

Javascript
function twoSumBrute(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).

The hash map way

For each number, calculate what its complement would be (target - nums[i]). Check if you've already seen that complement. If yes, you're done. If not, store the current number and its index in a map.

Javascript
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 [];
}

Time: O(n). Space: O(n).

The trade-off

The brute force approach uses no extra memory but checks n² pairs. The hash map approach uses O(n) memory but finishes in one pass. You're literally buying time with space.

This same pattern — "can I avoid repeated work by remembering what I've seen?" — applies to countless problems. Get comfortable with it. It's the single most useful algorithmic trick I know.

Keep reading