Two sum problem in linear time in JavaScript

The Two Sum Problem is a classic algorithmic challenge that asks us to find two numbers in an array that add up to a specific target value. This article demonstrates how to solve this problem efficiently in linear time using JavaScript.

What is the Two Sum Problem?

The Two Sum Problem requires finding a pair of indices in an array of numbers that add up to a given target sum. Given an array of integers and a target sum, we need to return the indices of two numbers that sum to the target value.

The key constraint is that each element in the array can only be used once, and you cannot use the same element twice. The solution should return the indices of the pair that adds up to the target.

Problem Example

const arr = [2, 5, 9, 7, 3, 8, 1];
const targetSum = 10;
// We need to find indices where arr[i] + arr[j] = 10
Possible pairs:
[0, 5] ? arr[0] + arr[5] = 2 + 8 = 10
[2, 6] ? arr[2] + arr[6] = 9 + 1 = 10  
[3, 4] ? arr[3] + arr[4] = 7 + 3 = 10

Brute Force Approach (O(n²) Time)

The straightforward approach uses nested loops to check every possible pair combination:

function twoSumBruteForce(arr, targetSum) {
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (arr[i] + arr[j] === targetSum) {
                return [i, j];
            }
        }
    }
    return []; // No pair found
}

const arr = [2, 7, 11, 15];
const result = twoSumBruteForce(arr, 9);
console.log(result);
[0, 1]

Time Complexity: O(n²) - nested loops
Space Complexity: O(1) - constant space

Optimal HashMap Approach (O(n) Time)

To achieve linear time complexity, we use a HashMap to store values and their indices as we iterate through the array once:

function twoSum(arr, targetSum) {
    const hashMap = {};
    
    for (let i = 0; i < arr.length; i++) {
        const currentValue = arr[i];
        const complement = targetSum - currentValue;
        
        // Check if complement exists in hashMap
        if (hashMap[complement] !== undefined) {
            return [hashMap[complement], i];
        }
        
        // Store current value and its index
        hashMap[currentValue] = i;
    }
    
    return []; // No pair found
}

const arr = [2, 7, 11, 15];
const result = twoSum(arr, 9);
console.log(result);
console.log(`Values: ${arr[result[0]]} + ${arr[result[1]]} = ${arr[result[0]] + arr[result[1]]}`);
[0, 1]
Values: 2 + 7 = 9

How the HashMap Solution Works

The algorithm works by storing each number and its index in a HashMap as we iterate. For each current number, we calculate its complement (target - current) and check if this complement already exists in our HashMap. If it does, we've found our pair!

function twoSumWithSteps(arr, targetSum) {
    const hashMap = {};
    console.log(`Finding two numbers that sum to ${targetSum}`);
    
    for (let i = 0; i < arr.length; i++) {
        const currentValue = arr[i];
        const complement = targetSum - currentValue;
        
        console.log(`Index ${i}: value=${currentValue}, looking for complement=${complement}`);
        
        if (hashMap[complement] !== undefined) {
            console.log(`Found! complement ${complement} at index ${hashMap[complement]}`);
            return [hashMap[complement], i];
        }
        
        hashMap[currentValue] = i;
        console.log(`Stored: hashMap[${currentValue}] = ${i}`);
    }
    
    return [];
}

const arr = [3, 2, 4];
const result = twoSumWithSteps(arr, 6);
console.log(`Result: [${result}]`);
Finding two numbers that sum to 6
Index 0: value=3, looking for complement=3
Stored: hashMap[3] = 0
Index 1: value=2, looking for complement=4
Stored: hashMap[2] = 1
Index 2: value=4, looking for complement=2
Found! complement 2 at index 1
Result: [1,2]

Complexity Comparison

Approach Time Complexity Space Complexity Best For
Brute Force O(n²) O(1) Small arrays, memory-constrained
HashMap O(n) O(n) Large arrays, performance-critical

Edge Cases

// Test edge cases
console.log("Empty array:", twoSum([], 5));
console.log("Single element:", twoSum([1], 1));
console.log("No solution:", twoSum([1, 2, 3], 10));
console.log("Duplicate values:", twoSum([3, 3], 6));
Empty array: []
Single element: []
No solution: []
Duplicate values: [0,1]

Conclusion

The HashMap approach solves the Two Sum Problem in optimal O(n) linear time by trading space for speed. This technique demonstrates how data structures like HashMaps can dramatically improve algorithm efficiency, making it suitable for large datasets and performance-critical applications.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements