Skip to content

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 · 2 min read

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.

Ehsan Gazar helps software engineers take LLM and agent systems from demo to production. He writes about building LLM systems that hold up in production: evals, tracing, RAG, agent architecture and cost control. He teaches the Senior to Staff AI Engineer cohort on Maven, where engineers learn to design and defend these systems.

Go further
Live cohort on Maven

Forward Deployed AI Engineering: From Customer Problem to Production Value

A live Maven cohort for engineers: 10 live 90-minute sessions taking one AI engagement from customer problem to production, ending with eight artefacts and a working slice in your own repo.

January cohort starts Tue 12 Jan 2027, Tue & Thu 6:30pm London. Enrolling now, 20 seats, $1,800.

View the live cohort

Keep reading