Best way to find two numbers in an array whose sum is a specific number with JavaScript?

Finding two numbers in an array that sum to a target value is a common programming problem. We'll explore an efficient solution using JavaScript.

Problem Statement

Given an array of numbers, find two elements whose sum equals a specific target value:

var numbers = [10, 3, 40, 50, 20, 30, 100]
Target sum = 80

We need to find pairs like (50, 30) where 50 + 30 = 80.

Efficient Solution Using Hash Map

The optimal approach uses a hash map to store visited numbers and their complements, achieving O(n) time complexity:

function findTwoSum(numbers, targetSum) {
    var visited = {};
    
    for (var i = 0; i < numbers.length; i++) {
        var currentNumber = numbers[i];
        var complement = targetSum - currentNumber;
        
        // Check if complement exists in visited numbers
        if (visited[complement] !== undefined) {
            return {
                firstNumber: complement,
                secondNumber: currentNumber,
                indices: [visited[complement], i]
            };
        }
        
        // Store current number with its index
        visited[currentNumber] = i;
    }
    
    return null; // No pair found
}

var numbers = [10, 3, 40, 50, 20, 30, 100];
console.log("Finding two numbers that sum to 80:");
console.log(findTwoSum(numbers, 80));
Finding two numbers that sum to 80:
{ firstNumber: 30, secondNumber: 50, indices: [ 5, 3 ] }

How It Works

Two Sum Algorithm Process Array: [10, 3, 40, 50, 20, 30, 100] | Target: 80 Step 1: Check 10 ? Complement = 80 - 10 = 70 ? 70 not in hash map ? Store: {10: 0} Step 2: Check 30 ? Complement = 80 - 30 = 50 ? 50 found in hash map! ? Return pair: (50, 30) Key Insight: For each number N, we look for (Target - N) in our hash map If found, we have our pair. If not, we store N for future lookups.

Alternative: Brute Force Method

A simpler but less efficient O(n²) approach using nested loops:

function findTwoSumBruteForce(numbers, targetSum) {
    for (var i = 0; i < numbers.length; i++) {
        for (var j = i + 1; j < numbers.length; j++) {
            if (numbers[i] + numbers[j] === targetSum) {
                return {
                    firstNumber: numbers[i],
                    secondNumber: numbers[j],
                    indices: [i, j]
                };
            }
        }
    }
    return null;
}

var numbers = [10, 3, 40, 50, 20, 30, 100];
console.log("Brute force result:");
console.log(findTwoSumBruteForce(numbers, 80));
Brute force result:
{ firstNumber: 50, secondNumber: 30, indices: [ 3, 5 ] }

Comparison

Method Time Complexity Space Complexity Best For
Hash Map O(n) O(n) Large arrays
Brute Force O(n²) O(1) Small arrays

Conclusion

The hash map approach is the most efficient solution for finding two numbers that sum to a target. It trades space for time complexity, making it ideal for larger datasets.

Updated on: 2026-03-15T23:18:59+05:30

534 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements